text stringlengths 54 60.6k |
|---|
<commit_before>/*
* This file is part of the SPLINTER library.
* Copyright (C) 2012 Bjarne Grimstad (bjarne.grimstad@gmail.com).
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "matlab.h"
#include <datatable.h>
#include <bspline.h>
#include <bsplineregression.h>
#include <pspline.h>
#include <radialbasisfunction.h>
#include <polynomialregression.h>
#include "definitions.h"
#include <set>
using namespace SPLINTER;
// 1 if the last function call caused an error, 0 else
int lastFuncCallError = 0;
const char *error_string = "No error.";
static void set_error_string(const char *new_error_string)
{
error_string = new_error_string;
lastFuncCallError = 1;
}
// Keep a list of objects so we avoid performing operations on objects that don't exist
std::set<obj_ptr> objects = std::set<obj_ptr>();
/* Cast the obj_ptr to a DataTable * */
static DataTable *get_datatable(obj_ptr datatable_ptr)
{
lastFuncCallError = 0;
if (objects.count(datatable_ptr) > 0)
{
return (DataTable *) datatable_ptr;
}
set_error_string("Invalid reference to DataTable: Maybe it has been deleted?");
return nullptr;
}
/* Cast the obj_ptr to an Approximant * */
static Approximant *get_approximant(obj_ptr approximant_ptr)
{
lastFuncCallError = 0;
if (objects.count(approximant_ptr) > 0)
{
return (Approximant *) approximant_ptr;
}
set_error_string("Invalid reference to Approximant: Maybe it has been deleted?");
return nullptr;
}
static DenseVector get_densevector(double *x, int x_dim)
{
DenseVector xvec(x_dim);
for (int i = 0; i < x_dim; i++)
{
xvec(i) = x[i];
}
return xvec;
}
extern "C"
{
/* 1 if the last call to the library resulted in an error,
* 0 otherwise. This is used to avoid throwing exceptions across library boundaries,
* and we expect the caller to manually check the value of this flag.
*/
int get_error() {
return lastFuncCallError;
}
const char *get_error_string()
{
return error_string;
}
/* DataTable constructor */
obj_ptr datatable_init()
{
obj_ptr dataTable = (obj_ptr) new DataTable();
objects.insert(dataTable);
return dataTable;
}
obj_ptr datatable_load_init(const char *filename)
{
obj_ptr dataTable = (obj_ptr) new DataTable(filename);
objects.insert(dataTable);
return dataTable;
}
void datatable_add_samples(obj_ptr datatable_ptr, double *x, int n_samples, int x_dim, int size)
{
DataTable *dataTable = get_datatable(datatable_ptr);
if (dataTable != nullptr) {
DenseVector vec(x_dim);
for (int i = 0; i < n_samples; ++i)
{
for (int j = 0; j < x_dim; ++j)
{
vec(j) = x[i + j * size];
}
dataTable->addSample(vec, x[i + x_dim * size]);
}
}
}
unsigned int datatable_get_num_variables(obj_ptr datatable_ptr)
{
DataTable *dataTable = get_datatable(datatable_ptr);
if (dataTable != nullptr) {
return dataTable->getNumVariables();
}
return 0;
}
unsigned int datatable_get_num_samples(obj_ptr datatable_ptr)
{
DataTable *dataTable = get_datatable(datatable_ptr);
if (dataTable != nullptr) {
return dataTable->getNumSamples();
}
return 0;
}
void datatable_save(obj_ptr datatable_ptr, const char *filename)
{
DataTable *dataTable = get_datatable(datatable_ptr);
if (dataTable != nullptr) {
dataTable->save(filename);
}
}
// Deletes the previous handle and loads a new
obj_ptr datatable_load(obj_ptr datatable_ptr, const char *filename)
{
// Delete and reset error, as it will get set if the DataTable didn't exist.
datatable_delete(datatable_ptr);
lastFuncCallError = 0;
obj_ptr dataTable = (obj_ptr) new DataTable(filename);
objects.insert(dataTable);
return dataTable;
}
void datatable_delete(obj_ptr datatable_ptr)
{
DataTable *dataTable = get_datatable(datatable_ptr);
if (dataTable != nullptr) {
objects.erase(datatable_ptr);
delete dataTable;
}
}
/* BSpline constructor */
obj_ptr bspline_init(obj_ptr datatable_ptr, int degree) {
obj_ptr bspline = nullptr;
auto table = get_datatable(datatable_ptr);
if (table != nullptr) {
BSplineType bsplineType;
switch (degree) {
case 1: {
bsplineType = BSplineType::LINEAR;
break;
}
case 2: {
bsplineType = BSplineType::QUADRATIC;
break;
}
case 3: {
bsplineType = BSplineType::CUBIC;
break;
}
case 4: {
bsplineType = BSplineType::QUARTIC;
break;
}
default: {
set_error_string("Invalid BSplineType!");
return nullptr;
}
}
bspline = (obj_ptr) new BSpline(doBSplineRegression(*table, bsplineType));
objects.insert(bspline);
}
return bspline;
}
obj_ptr bspline_load_init(const char *filename)
{
obj_ptr bspline = (obj_ptr) new BSpline(filename);
objects.insert(bspline);
return bspline;
}
/* PSpline constructor */
obj_ptr pspline_init(obj_ptr datatable_ptr, double lambda)
{
obj_ptr pspline = nullptr;
auto table = get_datatable(datatable_ptr);
if (table != nullptr) {
pspline = (obj_ptr) new BSpline(computePSpline(*table, lambda));
objects.insert(pspline);
}
return pspline;
}
obj_ptr pspline_load_init(const char *filename)
{
obj_ptr pspline = (obj_ptr) new BSpline(filename);
objects.insert(pspline);
return pspline;
}
/* RadialBasisFunction constructor */
obj_ptr rbf_init(obj_ptr datatable_ptr, int type_index, int normalized)
{
obj_ptr rbf = nullptr;
auto table = get_datatable(datatable_ptr);
if (table != nullptr) {
RadialBasisFunctionType type;
switch (type_index) {
case 1:
type = RadialBasisFunctionType::THIN_PLATE_SPLINE;
break;
case 2:
type = RadialBasisFunctionType::MULTIQUADRIC;
break;
case 3:
type = RadialBasisFunctionType::INVERSE_QUADRIC;
break;
case 4:
type = RadialBasisFunctionType::INVERSE_MULTIQUADRIC;
break;
case 5:
type = RadialBasisFunctionType::GAUSSIAN;
break;
default:
type = RadialBasisFunctionType::THIN_PLATE_SPLINE;
break;
}
bool norm = normalized != 0;
rbf = (obj_ptr) new RadialBasisFunction(*table, type, norm);
objects.insert(rbf);
}
return rbf;
}
obj_ptr rbf_load_init(const char *filename) {
obj_ptr rbf = (obj_ptr) new RadialBasisFunction(filename);
objects.insert(rbf);
return rbf;
}
/* PolynomialRegression constructor */
obj_ptr polynomial_regression_init(obj_ptr datatable_ptr, int *degrees, int degrees_dim) {
obj_ptr polyfit = nullptr;
auto table = get_datatable(datatable_ptr);
if (table != nullptr) {
auto degreeVec = std::vector<unsigned int>(degrees_dim);
for (int i = 0; i < degrees_dim; ++i) {
degreeVec.at(i) = (unsigned int) degrees[i];
}
polyfit = (obj_ptr) new PolynomialRegression(*table, degreeVec);
objects.insert(polyfit);
}
return polyfit;
}
obj_ptr polynomial_regression_load_init(const char *filename) {
obj_ptr polyfit = (obj_ptr) new PolynomialRegression(filename);
objects.insert(polyfit);
return polyfit;
}
double eval(obj_ptr approximant, double *x, int x_dim) {
double retVal = 0.0;
auto approx = get_approximant(approximant);
if (approx != nullptr) {
auto xvec = get_densevector(x, x_dim);
retVal = approx->eval(xvec);
}
return retVal;
}
double *eval_jacobian(obj_ptr approximant, double *x, int x_dim) {
double *retVal = nullptr;
auto approx = get_approximant(approximant);
if (approx != nullptr) {
auto xvec = get_densevector(x, x_dim);
DenseMatrix jacobian = approx->evalJacobian(xvec);
/* Copy jacobian from stack to heap */
int numCoefficients = jacobian.cols() * jacobian.rows();
retVal = (double *) malloc(sizeof(double) * numCoefficients);
memcpy(retVal, jacobian.data(), sizeof(double) * numCoefficients);
}
return retVal;
}
double *eval_hessian(obj_ptr approximant, double *x, int x_dim) {
double *retVal = nullptr;
auto approx = get_approximant(approximant);
if (approx != nullptr) {
auto xvec = get_densevector(x, x_dim);
DenseMatrix hessian = approx->evalHessian(xvec);
/* Copy jacobian from stack to heap */
int numCoefficients = hessian.cols() * hessian.rows();
retVal = (double *) malloc(sizeof(double) * numCoefficients);
memcpy(retVal, hessian.data(), sizeof(double) * numCoefficients);
}
return retVal;
}
int get_num_variables(obj_ptr approximant) {
int retVal = 0;
auto approx = get_approximant(approximant);
if (approx != nullptr) {
retVal = approx->getNumVariables();
}
return retVal;
}
void save(obj_ptr approximant, const char *filename) {
auto approx = get_approximant(approximant);
if (approx != nullptr) {
approx->save(filename);
}
}
void load(obj_ptr approximant, const char *filename) {
auto approx = get_approximant(approximant);
if (approx != nullptr) {
approx->load(filename);
}
}
void delete_approximant(obj_ptr approximant) {
auto approx = get_approximant(approximant);
if (approx != nullptr) {
objects.erase(approximant);
delete approx;
}
}
}
<commit_msg>Formatting in matlab.cpp<commit_after>/*
* This file is part of the SPLINTER library.
* Copyright (C) 2012 Bjarne Grimstad (bjarne.grimstad@gmail.com).
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "matlab.h"
#include <datatable.h>
#include <bspline.h>
#include <bsplineregression.h>
#include <pspline.h>
#include <radialbasisfunction.h>
#include <polynomialregression.h>
#include "definitions.h"
#include <set>
using namespace SPLINTER;
// 1 if the last function call caused an error, 0 else
int lastFuncCallError = 0;
const char *error_string = "No error.";
static void set_error_string(const char *new_error_string)
{
error_string = new_error_string;
lastFuncCallError = 1;
}
// Keep a list of objects so we avoid performing operations on objects that don't exist
std::set<obj_ptr> objects = std::set<obj_ptr>();
/* Cast the obj_ptr to a DataTable * */
static DataTable *get_datatable(obj_ptr datatable_ptr)
{
lastFuncCallError = 0;
if (objects.count(datatable_ptr) > 0)
{
return (DataTable *) datatable_ptr;
}
set_error_string("Invalid reference to DataTable: Maybe it has been deleted?");
return nullptr;
}
/* Cast the obj_ptr to an Approximant * */
static Approximant *get_approximant(obj_ptr approximant_ptr)
{
lastFuncCallError = 0;
if (objects.count(approximant_ptr) > 0)
{
return (Approximant *) approximant_ptr;
}
set_error_string("Invalid reference to Approximant: Maybe it has been deleted?");
return nullptr;
}
static DenseVector get_densevector(double *x, int x_dim)
{
DenseVector xvec(x_dim);
for (int i = 0; i < x_dim; i++)
{
xvec(i) = x[i];
}
return xvec;
}
extern "C"
{
/* 1 if the last call to the library resulted in an error,
* 0 otherwise. This is used to avoid throwing exceptions across library boundaries,
* and we expect the caller to manually check the value of this flag.
*/
int get_error() {
return lastFuncCallError;
}
const char *get_error_string()
{
return error_string;
}
/* DataTable constructor */
obj_ptr datatable_init()
{
obj_ptr dataTable = (obj_ptr) new DataTable();
objects.insert(dataTable);
return dataTable;
}
obj_ptr datatable_load_init(const char *filename)
{
obj_ptr dataTable = (obj_ptr) new DataTable(filename);
objects.insert(dataTable);
return dataTable;
}
void datatable_add_samples(obj_ptr datatable_ptr, double *x, int n_samples, int x_dim, int size)
{
DataTable *dataTable = get_datatable(datatable_ptr);
if (dataTable != nullptr)
{
DenseVector vec(x_dim);
for (int i = 0; i < n_samples; ++i)
{
for (int j = 0; j < x_dim; ++j)
{
vec(j) = x[i + j * size];
}
dataTable->addSample(vec, x[i + x_dim * size]);
}
}
}
unsigned int datatable_get_num_variables(obj_ptr datatable_ptr)
{
DataTable *dataTable = get_datatable(datatable_ptr);
if (dataTable != nullptr)
{
return dataTable->getNumVariables();
}
return 0;
}
unsigned int datatable_get_num_samples(obj_ptr datatable_ptr)
{
DataTable *dataTable = get_datatable(datatable_ptr);
if (dataTable != nullptr)
{
return dataTable->getNumSamples();
}
return 0;
}
void datatable_save(obj_ptr datatable_ptr, const char *filename)
{
DataTable *dataTable = get_datatable(datatable_ptr);
if (dataTable != nullptr)
{
dataTable->save(filename);
}
}
// Deletes the previous handle and loads a new
obj_ptr datatable_load(obj_ptr datatable_ptr, const char *filename)
{
// Delete and reset error, as it will get set if the DataTable didn't exist.
datatable_delete(datatable_ptr);
lastFuncCallError = 0;
obj_ptr dataTable = (obj_ptr) new DataTable(filename);
objects.insert(dataTable);
return dataTable;
}
void datatable_delete(obj_ptr datatable_ptr)
{
DataTable *dataTable = get_datatable(datatable_ptr);
if (dataTable != nullptr)
{
objects.erase(datatable_ptr);
delete dataTable;
}
}
/* BSpline constructor */
obj_ptr bspline_init(obj_ptr datatable_ptr, int degree)
{
obj_ptr bspline = nullptr;
auto table = get_datatable(datatable_ptr);
if (table != nullptr)
{
BSplineType bsplineType;
switch (degree) {
case 1: {
bsplineType = BSplineType::LINEAR;
break;
}
case 2: {
bsplineType = BSplineType::QUADRATIC;
break;
}
case 3: {
bsplineType = BSplineType::CUBIC;
break;
}
case 4: {
bsplineType = BSplineType::QUARTIC;
break;
}
default: {
set_error_string("Invalid BSplineType!");
return nullptr;
}
}
bspline = (obj_ptr) new BSpline(doBSplineRegression(*table, bsplineType));
objects.insert(bspline);
}
return bspline;
}
obj_ptr bspline_load_init(const char *filename)
{
obj_ptr bspline = (obj_ptr) new BSpline(filename);
objects.insert(bspline);
return bspline;
}
/* PSpline constructor */
obj_ptr pspline_init(obj_ptr datatable_ptr, double lambda)
{
obj_ptr pspline = nullptr;
auto table = get_datatable(datatable_ptr);
if (table != nullptr)
{
pspline = (obj_ptr) new BSpline(computePSpline(*table, lambda));
objects.insert(pspline);
}
return pspline;
}
obj_ptr pspline_load_init(const char *filename)
{
obj_ptr pspline = (obj_ptr) new BSpline(filename);
objects.insert(pspline);
return pspline;
}
/* RadialBasisFunction constructor */
obj_ptr rbf_init(obj_ptr datatable_ptr, int type_index, int normalized)
{
obj_ptr rbf = nullptr;
auto table = get_datatable(datatable_ptr);
if (table != nullptr)
{
RadialBasisFunctionType type;
switch (type_index)
{
case 1:
type = RadialBasisFunctionType::THIN_PLATE_SPLINE;
break;
case 2:
type = RadialBasisFunctionType::MULTIQUADRIC;
break;
case 3:
type = RadialBasisFunctionType::INVERSE_QUADRIC;
break;
case 4:
type = RadialBasisFunctionType::INVERSE_MULTIQUADRIC;
break;
case 5:
type = RadialBasisFunctionType::GAUSSIAN;
break;
default:
type = RadialBasisFunctionType::THIN_PLATE_SPLINE;
break;
}
bool norm = normalized != 0;
rbf = (obj_ptr) new RadialBasisFunction(*table, type, norm);
objects.insert(rbf);
}
return rbf;
}
obj_ptr rbf_load_init(const char *filename)
{
obj_ptr rbf = (obj_ptr) new RadialBasisFunction(filename);
objects.insert(rbf);
return rbf;
}
/* PolynomialRegression constructor */
obj_ptr polynomial_regression_init(obj_ptr datatable_ptr, int *degrees, int degrees_dim)
{
obj_ptr polyfit = nullptr;
auto table = get_datatable(datatable_ptr);
if (table != nullptr)
{
auto degreeVec = std::vector<unsigned int>(degrees_dim);
for (int i = 0; i < degrees_dim; ++i)
{
degreeVec.at(i) = (unsigned int) degrees[i];
}
polyfit = (obj_ptr) new PolynomialRegression(*table, degreeVec);
objects.insert(polyfit);
}
return polyfit;
}
obj_ptr polynomial_regression_load_init(const char *filename)
{
obj_ptr polyfit = (obj_ptr) new PolynomialRegression(filename);
objects.insert(polyfit);
return polyfit;
}
double eval(obj_ptr approximant, double *x, int x_dim)
{
double retVal = 0.0;
auto approx = get_approximant(approximant);
if (approx != nullptr)
{
auto xvec = get_densevector(x, x_dim);
retVal = approx->eval(xvec);
}
return retVal;
}
double *eval_jacobian(obj_ptr approximant, double *x, int x_dim)
{
double *retVal = nullptr;
auto approx = get_approximant(approximant);
if (approx != nullptr)
{
auto xvec = get_densevector(x, x_dim);
DenseMatrix jacobian = approx->evalJacobian(xvec);
/* Copy jacobian from stack to heap */
int numCoefficients = jacobian.cols() * jacobian.rows();
retVal = (double *) malloc(sizeof(double) * numCoefficients);
memcpy(retVal, jacobian.data(), sizeof(double) * numCoefficients);
}
return retVal;
}
double *eval_hessian(obj_ptr approximant, double *x, int x_dim)
{
double *retVal = nullptr;
auto approx = get_approximant(approximant);
if (approx != nullptr)
{
auto xvec = get_densevector(x, x_dim);
DenseMatrix hessian = approx->evalHessian(xvec);
/* Copy jacobian from stack to heap */
int numCoefficients = hessian.cols() * hessian.rows();
retVal = (double *) malloc(sizeof(double) * numCoefficients);
memcpy(retVal, hessian.data(), sizeof(double) * numCoefficients);
}
return retVal;
}
int get_num_variables(obj_ptr approximant)
{
int retVal = 0;
auto approx = get_approximant(approximant);
if (approx != nullptr)
{
retVal = approx->getNumVariables();
}
return retVal;
}
void save(obj_ptr approximant, const char *filename)
{
auto approx = get_approximant(approximant);
if (approx != nullptr) {
approx->save(filename);
}
}
void load(obj_ptr approximant, const char *filename)
{
auto approx = get_approximant(approximant);
if (approx != nullptr) {
approx->load(filename);
}
}
void delete_approximant(obj_ptr approximant)
{
auto approx = get_approximant(approximant);
if (approx != nullptr)
{
objects.erase(approximant);
delete approx;
}
}
}
<|endoftext|> |
<commit_before>#include <taichi/common/util.h>
#include <taichi/common/task.h>
#include <taichi/math.h>
#include <taichi/system/timer.h>
#include <Eigen/Dense>
TC_NAMESPACE_BEGIN
constexpr int rounds = 8192;
constexpr int N = 1024;
template <int dim, typename T>
real eigen_matmatmul() {
std::vector<Eigen::Matrix<T, dim, dim>> A, B, C;
A.resize(N);
B.resize(N);
C.resize(N);
auto t = Time::get_time();
for (int r = 0; r < rounds; r++) {
for (int i = 0; i < N; i++) {
C[i] = A[i] * B[i];
}
}
return Time::get_time() - t;
};
#define BENCHMARK(x) \
{ \
real t = x##_matmatmul<dim, T>(); \
fmt::print("Matrix<{}, {}>, {} = {:8.3f} ms\n", dim, \
sizeof(T) == 4 ? "float32" : "float64", #x, t * 1000.0_f); \
}
template <int dim, typename T>
void run() {
BENCHMARK(eigen);
}
auto benchmark_matmul = []() {
run<2, float32>();
run<3, float32>();
run<4, float32>();
run<2, float64>();
run<3, float64>();
run<4, float64>();
};
TC_REGISTER_TASK(benchmark_matmul);
TC_NAMESPACE_END
<commit_msg>AOSOA<commit_after>#include <taichi/common/util.h>
#include <taichi/common/task.h>
#include <taichi/math.h>
#include <taichi/system/timer.h>
#include <Eigen/Dense>
TC_NAMESPACE_BEGIN
constexpr int rounds = 16384;
constexpr int N = 1024;
template <int dim, typename T>
real eigen_matmatmul() {
std::vector<Eigen::Matrix<T, dim, dim>> A, B, C;
A.resize(N);
B.resize(N);
C.resize(N);
auto t = Time::get_time();
for (int r = 0; r < rounds; r++) {
for (int i = 0; i < N; i++) {
C[i] = A[i] * B[i];
}
}
return Time::get_time() - t;
};
template <int dim, typename T>
real taichi_matmatmul() {
std::vector<TMatrix<T, dim>> A, B, C;
A.resize(N);
B.resize(N);
C.resize(N);
auto t = Time::get_time();
for (int r = 0; r < rounds; r++) {
for (int i = 0; i < N; i++) {
C[i] = A[i] * B[i];
}
}
return Time::get_time() - t;
};
// array of dim * dim * 8 * float32
template <int dim>
void AOSOA_matmul(float32 *A, float32 *B, float32 *C) {
for (int r = 0; r < rounds; r++) {
for (int t = 0; t < N / 8; t++) {
__m256 a[dim * dim], b[dim * dim];
const int p = dim * dim * 8 * t;
for (int i = 0; i < dim * dim; i++) {
a[i] = _mm256_loadu_ps(&A[p + 8 * i]);
b[i] = _mm256_loadu_ps(&B[p + 8 * i]);
}
for (int i = 0; i < dim; i++) {
for (int j = 0; j < dim; j++) {
__m256 c = a[i * dim] * b[j];
for (int k = 0; k < dim - 1; k++) {
c = _mm256_fmadd_ps(a[i * dim + k], b[k * dim + j], c);
}
_mm256_storeu_ps(&C[p + 8 * (i * dim + j)], c);
}
}
}
}
}
template <int dim, typename T>
real AOSOA_matmatmul() {
std::vector<T> A, B, C;
A.resize(N * dim * dim);
B.resize(N * dim * dim);
C.resize(N * dim * dim);
auto t = Time::get_time();
AOSOA_matmul<dim>(A.data(), B.data(), C.data());
return Time::get_time() - t;
};
#define BENCHMARK(x) \
{ \
real t = x##_matmatmul<dim, T>(); \
fmt::print("Matrix<{}, {}> {:10s} = {:8.3f} ms\n", dim, \
sizeof(T) == 4 ? "float32" : "float64", #x, t * 1000.0_f); \
}
template <int dim, typename T>
void run() {
BENCHMARK(eigen);
BENCHMARK(taichi);
BENCHMARK(AOSOA);
fmt::print("\n");
}
auto benchmark_matmul = []() {
run<2, float32>();
run<3, float32>();
run<4, float32>();
/*
run<2, float64>();
run<3, float64>();
run<4, float64>();
*/
};
TC_REGISTER_TASK(benchmark_matmul);
TC_NAMESPACE_END
<|endoftext|> |
<commit_before>#ifndef HEADER_GUARD_NEW_MOVE_H
#define HEADER_GUARD_NEW_MOVE_H
#include <string>
#include <vector>
typedef std::vector<std::string>* contents;
void mvline (contents, unsigned long);
void mv (contents, unsigned long y, unsigned long x);
void mvrel (contents, long y, long x);
void mvcol (contents, unsigned long col);
void mvsot (contents);
void mveol (contents);
void mvsol (contents);
void mvsop (contents);
void mveop (contents);
void mvd (contents, long times = 1);
void mvu (contents, long times = 1);
void mvfw (contents, unsigned long words = 1);
void mvbw (contents, unsigned long words = 1);
void mvf (contents, unsigned long times = 1);
void mvb (contents, unsigned long times = 1);
#endif
<commit_msg>``contents'' is a real class now<commit_after>#ifndef HEADER_GUARD_NEW_MOVE_H
#define HEADER_GUARD_NEW_MOVE_H
#include <string>
#include <vector>
#include "file_contents.hh"
int to_visual(const std::string& cont, int x);
void redrawyx(contents&);
void mvline (contents&, unsigned long);
void mv (contents&, unsigned long y, unsigned long x);
void mvrel (contents&, long y, long x);
void mvcol (contents&, unsigned long col);
void mvsot (contents&);
void mveol (contents&);
void mvsol (contents&);
void mvsop (contents&);
void mveop (contents&);
void mvd (contents&, long times = 1);
void mvu (contents&, long times = 1);
void mvfw (contents&, unsigned long words = 1);
void mvbw (contents&, unsigned long words = 1);
void mvf (contents&, unsigned long times = 1);
void mvb (contents&, unsigned long times = 1);
#endif
<|endoftext|> |
<commit_before>#include "OrientationSensorsWrapper.h"
#include "SDLogDriver.h"
#include "DualEncoderDriver.h"
#include "MotorDriver.h"
#include "PlanarAccelerationModule.h"
#include "TireContactModule.h"
#include "FrontLiftedDetection.h"
#include "constants.h"
#include <Wire.h>
#include <SD.h>
enum {
WAITING_FOR_COMMAND,
PREPARE_TO_FIGHT,
IN_COMBAT,
RECALIBRATE,
BRAINDEAD,
TEST_MODE
} robot_state = WAITING_FOR_COMMAND;
uint32_t prepare_micros;
void log_info()
{
log_data_pack.timestamp = millis();
log_data_pack.acc_x = position.getAccX();
log_data_pack.acc_y = position.getAccY();
log_data_pack.acc_z = position.getAccZ();
log_data_pack.gyro_x = position.getGyroX();
log_data_pack.gyro_y = position.getGyroY();
log_data_pack.gyro_z = position.getGyroZ();
log_data_pack.ahrs_x = position.getRoll();
log_data_pack.ahrs_y = position.getPitch();
log_data_pack.ahrs_z = position.getYaw();
log_data_pack.leftSpeed = leftEncoder.getSpeed();
log_data_pack.rightSpeed = rightEncoder.getSpeed();
logDataPack();
}
void setup()
{
Serial.begin(115200);
SD.begin(4);
initLogger();
initDualEncoders();
initMotors();
pinMode(LEFT_SENSOR_PIN, INPUT);
pinMode(RIGHT_SENSOR_PIN, INPUT);
Wire.begin();
Wire.setClock(400000);
position.init();
tiresContactInit(TIRE_LOST_OF_CONTACT_DEGREES);
initFrontLifted(FRONT_LIFTED_THRESHOLD);
}
void serialCommand()
{
static int left = 0;
static int right = 0;
if(Serial.available() == 0) return;
char cmd = Serial.read();
if(cmd == 'l')
{
left = 0;
if(Serial.available() > 0)
{
int dir = 1;
if(Serial.peek() == '-')
{
dir = -1;
Serial.read();
}
while(Serial.available() > 0)
{
char digit = Serial.read();
left = left * 10 + (digit - '0');
}
left *= dir;
}
setMotors(left, right);
}
else if(cmd == 'r')
{
right = 0;
if(Serial.available() > 0)
{
int dir = 1;
if(Serial.peek() == '-')
{
dir = -1;
Serial.read();
}
while(Serial.available() > 0)
{
char digit = Serial.read();
right = right * 10 + (digit - '0');
}
right *= dir;
}
setMotors(left, right);
}
else if(cmd == 'd')
{
dumpLog();
}
}
void readProximitySensors(int& left, int& right)
{
left = digitalRead(LEFT_SENSOR_PIN) ^ 1;
right = digitalRead(RIGHT_SENSOR_PIN) ^ 1;
}
void getCommand()
{
static int left = 0;
static int right = 0;
static int last_left = 0;
static int last_right = 0;
static int command_counter = 0;
readProximitySensors(left, right);
if(robot_state == WAITING_FOR_COMMAND)
{
if(right)
{
if(left > last_left)
{
++command_counter;
Serial.print("Command counter: ");
Serial.println(command_counter);
}
}
else if(right < last_right)
{
switch(command_counter)
{
case 0:
robot_state = PREPARE_TO_FIGHT;
prepare_micros = micros();
break;
case 1:
robot_state = RECALIBRATE;
position.calibrate();
plannarAcceleration.calibrate();
robot_state = WAITING_FOR_COMMAND;
break;
case 2:
robot_state = TEST;
setMotors(80, 80);
break;
}
command_counter = 0;
}
}
else if(left && right)
{
if(robot_state == PREPARE_TO_FIGHT)
robot_state = WAITING_FOR_COMMAND;
else
{
robot_state = BRAINDEAD;
setMotors(0, 0);
}
}
last_left = left;
last_right = right;
}
void loop()
{
static uint32_t last_sample_micros = 0;
static uint32_t last_log_micros = 0;
static uint32_t last_blink_micros = 0;
uint32_t current_micros = micros();
{ // blink control
uint32_t full_cycle;
uint32_t high_cycle;
if(robot_state == BRAINDEAD)
{
full_cycle = MICROS_PER_SECOND * 2;
high_cycle = MICROS_PER_SECOND;
}
else if(robot_state == PREPARE_TO_FIGHT)
{
full_cycle = MICROS_PER_SECOND / 10;
high_cycle = MICROS_PER_SECOND / 20;
}
else
{
full_cycle = MICROS_PER_SECOND / 2;
high_cycle = MICROS_PER_SECOND / 3;
}
if(current_micros - last_blink_micros >= full_cycle)
{
digitalWrite(LED_PIN, HIGH);
last_blink_micros = current_micros;
}
else if(current_micros - last_blink_micros >= high_cycle)
{
digitalWrite(LED_PIN, LOW);
}
}
if(robot_state == BRAINDEAD)
{
setMotors(0, 0);
return;
}
if(robot_state == PREPARE_TO_FIGHT)
{
if(current_micros - prepare_micros >= MICROS_PER_SECOND * 5)
{
robot_state = IN_COMBAT;
}
}
// Read sensors
if(current_micros - last_sample_micros >= MICROS_PER_SECOND / SAMPLE_FREQUENCY)
{
position.read_sensors();
getCommand();
last_sample_micros = current_micros;
}
// Log data
if(current_micros - last_log_micros >= MICROS_PER_SECOND / LOG_FREQUENCY)
{
log_info();
last_log_micros = current_micros;
if(robot_state == TEST_MODE)
{
Serial.print(getLeftTireContactState()); Serial.print(" ");
Serial.print(getRightTireContactState()); Serial.print(" ");
Serial.print(getFrontLiftedState()); Serial.println("");
}
}
serialCommand();
}
<commit_msg>Proxomity sensor command bug fixes<commit_after>#include "OrientationSensorsWrapper.h"
#include "SDLogDriver.h"
#include "DualEncoderDriver.h"
#include "MotorDriver.h"
#include "PlanarAccelerationModule.h"
#include "TireContactModule.h"
#include "FrontLiftedDetection.h"
#include "constants.h"
#include <Wire.h>
#include <SD.h>
enum {
WAITING_FOR_COMMAND,
PREPARE_TO_FIGHT,
IN_COMBAT,
RECALIBRATE,
BRAINDEAD,
TEST_MODE
} robot_state = WAITING_FOR_COMMAND;
uint32_t prepare_micros;
void log_info()
{
log_data_pack.timestamp = millis();
log_data_pack.acc_x = position.getAccX();
log_data_pack.acc_y = position.getAccY();
log_data_pack.acc_z = position.getAccZ();
log_data_pack.gyro_x = position.getGyroX();
log_data_pack.gyro_y = position.getGyroY();
log_data_pack.gyro_z = position.getGyroZ();
log_data_pack.ahrs_x = position.getRoll();
log_data_pack.ahrs_y = position.getPitch();
log_data_pack.ahrs_z = position.getYaw();
log_data_pack.leftSpeed = leftEncoder.getSpeed();
log_data_pack.rightSpeed = rightEncoder.getSpeed();
logDataPack();
}
void setup()
{
Serial.begin(115200);
SD.begin(4);
initLogger();
initDualEncoders();
initMotors();
pinMode(LEFT_SENSOR_PIN, INPUT);
pinMode(RIGHT_SENSOR_PIN, INPUT);
Wire.begin();
Wire.setClock(400000);
position.init();
tiresContactInit(TIRE_LOST_OF_CONTACT_DEGREES);
initFrontLifted(FRONT_LIFTED_THRESHOLD);
}
void serialCommand()
{
static int left = 0;
static int right = 0;
if(Serial.available() == 0) return;
char cmd = Serial.read();
if(cmd == 'l')
{
left = 0;
if(Serial.available() > 0)
{
int dir = 1;
if(Serial.peek() == '-')
{
dir = -1;
Serial.read();
}
while(Serial.available() > 0)
{
char digit = Serial.read();
left = left * 10 + (digit - '0');
}
left *= dir;
}
setMotors(left, right);
}
else if(cmd == 'r')
{
right = 0;
if(Serial.available() > 0)
{
int dir = 1;
if(Serial.peek() == '-')
{
dir = -1;
Serial.read();
}
while(Serial.available() > 0)
{
char digit = Serial.read();
right = right * 10 + (digit - '0');
}
right *= dir;
}
setMotors(left, right);
}
else if(cmd == 'd')
{
dumpLog();
}
}
void readProximitySensors(int& left, int& right)
{
left = digitalRead(LEFT_SENSOR_PIN) ^ 1;
right = digitalRead(RIGHT_SENSOR_PIN) ^ 1;
}
void getCommand()
{
static int left = 0;
static int right = 0;
static int last_left = 0;
static int last_right = 0;
static int command_counter = 0;
readProximitySensors(left, right);
if(robot_state == WAITING_FOR_COMMAND)
{
if(right)
{
if(left < last_left)
{
++command_counter;
Serial.print("Command counter: ");
Serial.println(command_counter);
}
}
else if(right < last_right)
{
if(left) command_counter = 42;
switch(command_counter)
{
case 0:
robot_state = PREPARE_TO_FIGHT;
prepare_micros = micros();
break;
case 1:
robot_state = RECALIBRATE;
position.calibrate();
plannarAcceleration.calibrate();
robot_state = WAITING_FOR_COMMAND;
break;
case 2:
robot_state = TEST;
setMotors(80, 80);
break;
}
command_counter = 0;
}
}
else if(left && right)
{
if(robot_state == PREPARE_TO_FIGHT)
{
robot_state = WAITING_FOR_COMMAND;
command_counter = 42;
}
else
{
robot_state = BRAINDEAD;
setMotors(0, 0);
}
}
last_left = left;
last_right = right;
}
void loop()
{
static uint32_t last_sample_micros = 0;
static uint32_t last_log_micros = 0;
static uint32_t last_blink_micros = 0;
uint32_t current_micros = micros();
{ // blink control
uint32_t full_cycle;
uint32_t high_cycle;
if(robot_state == BRAINDEAD)
{
full_cycle = MICROS_PER_SECOND * 2;
high_cycle = MICROS_PER_SECOND;
}
else if(robot_state == PREPARE_TO_FIGHT)
{
full_cycle = MICROS_PER_SECOND / 10;
high_cycle = MICROS_PER_SECOND / 20;
}
else
{
full_cycle = MICROS_PER_SECOND / 2;
high_cycle = MICROS_PER_SECOND / 3;
}
if(current_micros - last_blink_micros >= full_cycle)
{
digitalWrite(LED_PIN, HIGH);
last_blink_micros = current_micros;
}
else if(current_micros - last_blink_micros >= high_cycle)
{
digitalWrite(LED_PIN, LOW);
}
}
if(robot_state == BRAINDEAD)
{
setMotors(0, 0);
return;
}
if(robot_state == PREPARE_TO_FIGHT)
{
if(current_micros - prepare_micros >= MICROS_PER_SECOND * 5)
{
robot_state = IN_COMBAT;
}
}
// Read sensors
if(current_micros - last_sample_micros >= MICROS_PER_SECOND / SAMPLE_FREQUENCY)
{
position.read_sensors();
getCommand();
last_sample_micros = current_micros;
}
// Log data
if(current_micros - last_log_micros >= MICROS_PER_SECOND / LOG_FREQUENCY)
{
log_info();
last_log_micros = current_micros;
if(robot_state == TEST_MODE)
{
Serial.print(getLeftTireContactState()); Serial.print(" ");
Serial.print(getRightTireContactState()); Serial.print(" ");
Serial.print(getFrontLiftedState()); Serial.println("");
}
}
serialCommand();
}
<|endoftext|> |
<commit_before>#include "crt.h"
#include "parser.h"
#include "scanner.h"
#include "token.h"
#include "exceptions.h"
#include <sstream>
#include <cstdio>
namespace YAML
{
Parser::Parser()
{
}
Parser::Parser(std::istream& in)
{
Load(in);
}
Parser::~Parser()
{
}
Parser::operator bool() const
{
return m_pScanner.get() && !m_pScanner->empty();
}
void Parser::Load(std::istream& in)
{
m_pScanner.reset(new Scanner(in));
m_state.Reset();
}
// GetNextDocument
// . Reads the next document in the queue (of tokens).
// . Throws a ParserException on error.
bool Parser::GetNextDocument(Node& document)
{
// clear node
document.Clear();
// first read directives
ParseDirectives();
// we better have some tokens in the queue
if(m_pScanner->empty())
return false;
// first eat doc start (optional)
if(m_pScanner->peek().type == Token::DOC_START)
m_pScanner->pop();
// now parse our root node
document.Parse(m_pScanner.get(), m_state);
// and finally eat any doc ends we see
while(!m_pScanner->empty() && m_pScanner->peek().type == Token::DOC_END)
m_pScanner->pop();
// clear anchors from the scanner, which are no longer relevant
m_pScanner->ClearAnchors();
return true;
}
// ParseDirectives
// . Reads any directives that are next in the queue.
void Parser::ParseDirectives()
{
bool readDirective = false;
while(1) {
if(m_pScanner->empty())
break;
Token& token = m_pScanner->peek();
if(token.type != Token::DIRECTIVE)
break;
// we keep the directives from the last document if none are specified;
// but if any directives are specific, then we reset them
if(!readDirective)
m_state.Reset();
readDirective = true;
HandleDirective(&token);
m_pScanner->pop();
}
}
void Parser::HandleDirective(Token *pToken)
{
if(pToken->value == "YAML")
HandleYamlDirective(pToken);
else if(pToken->value == "TAG")
HandleTagDirective(pToken);
}
// HandleYamlDirective
// . Should be of the form 'major.minor' (like a version number)
void Parser::HandleYamlDirective(Token *pToken)
{
if(pToken->params.size() != 1)
throw ParserException(pToken->mark, ErrorMsg::YAML_DIRECTIVE_ARGS);
std::stringstream str(pToken->params[0]);
str >> m_state.version.major;
str.get();
str >> m_state.version.minor;
if(!str || str.peek() != EOF)
throw ParserException(pToken->mark, ErrorMsg::YAML_VERSION + pToken->params[0]);
if(m_state.version.major > 1)
throw ParserException(pToken->mark, ErrorMsg::YAML_MAJOR_VERSION);
// TODO: warning on major == 1, minor > 2?
}
// HandleTagDirective
// . Should be of the form 'handle prefix', where 'handle' is converted to 'prefix' in the file.
void Parser::HandleTagDirective(Token *pToken)
{
if(pToken->params.size() != 2)
throw ParserException(pToken->mark, ErrorMsg::TAG_DIRECTIVE_ARGS);
std::string handle = pToken->params[0], prefix = pToken->params[1];
m_state.tags[handle] = prefix;
}
void Parser::PrintTokens(std::ostream& out)
{
while(1) {
if(m_pScanner->empty())
break;
out << m_pScanner->peek() << "\n";
m_pScanner->pop();
}
}
}
<commit_msg>Fixed little bug in parser commit<commit_after>#include "crt.h"
#include "parser.h"
#include "scanner.h"
#include "token.h"
#include "exceptions.h"
#include <sstream>
#include <cstdio>
namespace YAML
{
Parser::Parser()
{
}
Parser::Parser(std::istream& in)
{
Load(in);
}
Parser::~Parser()
{
}
Parser::operator bool() const
{
return m_pScanner.get() && !m_pScanner->empty();
}
void Parser::Load(std::istream& in)
{
m_pScanner.reset(new Scanner(in));
m_state.Reset();
}
// GetNextDocument
// . Reads the next document in the queue (of tokens).
// . Throws a ParserException on error.
bool Parser::GetNextDocument(Node& document)
{
if(!m_pScanner.get())
return false;
// clear node
document.Clear();
// first read directives
ParseDirectives();
// we better have some tokens in the queue
if(m_pScanner->empty())
return false;
// first eat doc start (optional)
if(m_pScanner->peek().type == Token::DOC_START)
m_pScanner->pop();
// now parse our root node
document.Parse(m_pScanner.get(), m_state);
// and finally eat any doc ends we see
while(!m_pScanner->empty() && m_pScanner->peek().type == Token::DOC_END)
m_pScanner->pop();
// clear anchors from the scanner, which are no longer relevant
m_pScanner->ClearAnchors();
return true;
}
// ParseDirectives
// . Reads any directives that are next in the queue.
void Parser::ParseDirectives()
{
bool readDirective = false;
while(1) {
if(m_pScanner->empty())
break;
Token& token = m_pScanner->peek();
if(token.type != Token::DIRECTIVE)
break;
// we keep the directives from the last document if none are specified;
// but if any directives are specific, then we reset them
if(!readDirective)
m_state.Reset();
readDirective = true;
HandleDirective(&token);
m_pScanner->pop();
}
}
void Parser::HandleDirective(Token *pToken)
{
if(pToken->value == "YAML")
HandleYamlDirective(pToken);
else if(pToken->value == "TAG")
HandleTagDirective(pToken);
}
// HandleYamlDirective
// . Should be of the form 'major.minor' (like a version number)
void Parser::HandleYamlDirective(Token *pToken)
{
if(pToken->params.size() != 1)
throw ParserException(pToken->mark, ErrorMsg::YAML_DIRECTIVE_ARGS);
std::stringstream str(pToken->params[0]);
str >> m_state.version.major;
str.get();
str >> m_state.version.minor;
if(!str || str.peek() != EOF)
throw ParserException(pToken->mark, ErrorMsg::YAML_VERSION + pToken->params[0]);
if(m_state.version.major > 1)
throw ParserException(pToken->mark, ErrorMsg::YAML_MAJOR_VERSION);
// TODO: warning on major == 1, minor > 2?
}
// HandleTagDirective
// . Should be of the form 'handle prefix', where 'handle' is converted to 'prefix' in the file.
void Parser::HandleTagDirective(Token *pToken)
{
if(pToken->params.size() != 2)
throw ParserException(pToken->mark, ErrorMsg::TAG_DIRECTIVE_ARGS);
std::string handle = pToken->params[0], prefix = pToken->params[1];
m_state.tags[handle] = prefix;
}
void Parser::PrintTokens(std::ostream& out)
{
if(!m_pScanner.get())
return;
while(1) {
if(m_pScanner->empty())
break;
out << m_pScanner->peek() << "\n";
m_pScanner->pop();
}
}
}
<|endoftext|> |
<commit_before>#include "crt.h"
#include "parser.h"
#include "scanner.h"
#include "token.h"
#include "exceptions.h"
#include <sstream>
#include <cstdio>
namespace YAML
{
Parser::Parser()
{
}
Parser::Parser(std::istream& in)
{
Load(in);
}
Parser::~Parser()
{
}
Parser::operator bool() const
{
return m_pScanner.get() && !m_pScanner->empty();
}
void Parser::Load(std::istream& in)
{
m_pScanner.reset(new Scanner(in));
m_state.Reset();
}
// GetNextDocument
// . Reads the next document in the queue (of tokens).
// . Throws a ParserException on error.
bool Parser::GetNextDocument(Node& document)
{
// clear node
document.Clear();
// first read directives
ParseDirectives();
// we better have some tokens in the queue
if(m_pScanner->empty())
return false;
// first eat doc start (optional)
if(m_pScanner->peek().type == Token::DOC_START)
m_pScanner->pop();
// now parse our root node
document.Parse(m_pScanner.get(), m_state);
// and finally eat any doc ends we see
while(!m_pScanner->empty() && m_pScanner->peek().type == Token::DOC_END)
m_pScanner->pop();
// clear anchors from the scanner, which are no longer relevant
m_pScanner->ClearAnchors();
return true;
}
// ParseDirectives
// . Reads any directives that are next in the queue.
void Parser::ParseDirectives()
{
bool readDirective = false;
while(1) {
if(m_pScanner->empty())
break;
Token& token = m_pScanner->peek();
if(token.type != Token::DIRECTIVE)
break;
// we keep the directives from the last document if none are specified;
// but if any directives are specific, then we reset them
if(!readDirective)
m_state.Reset();
readDirective = true;
HandleDirective(&token);
m_pScanner->pop();
}
}
void Parser::HandleDirective(Token *pToken)
{
if(pToken->value == "YAML")
HandleYamlDirective(pToken);
else if(pToken->value == "TAG")
HandleTagDirective(pToken);
}
// HandleYamlDirective
// . Should be of the form 'major.minor' (like a version number)
void Parser::HandleYamlDirective(Token *pToken)
{
if(pToken->params.size() != 1)
throw ParserException(pToken->mark, ErrorMsg::YAML_DIRECTIVE_ARGS);
std::stringstream str(pToken->params[0]);
str >> m_state.version.major;
str.get();
str >> m_state.version.minor;
if(!str || str.peek() != EOF)
throw ParserException(pToken->mark, ErrorMsg::YAML_VERSION + pToken->params[0]);
if(m_state.version.major > 1)
throw ParserException(pToken->mark, ErrorMsg::YAML_MAJOR_VERSION);
// TODO: warning on major == 1, minor > 2?
}
// HandleTagDirective
// . Should be of the form 'handle prefix', where 'handle' is converted to 'prefix' in the file.
void Parser::HandleTagDirective(Token *pToken)
{
if(pToken->params.size() != 2)
throw ParserException(pToken->mark, ErrorMsg::TAG_DIRECTIVE_ARGS);
std::string handle = pToken->params[0], prefix = pToken->params[1];
m_state.tags[handle] = prefix;
}
void Parser::PrintTokens(std::ostream& out)
{
while(1) {
if(m_pScanner->empty())
break;
out << m_pScanner->peek() << "\n";
m_pScanner->pop();
}
}
}
<commit_msg>Fixed little bug in parser commit<commit_after>#include "crt.h"
#include "parser.h"
#include "scanner.h"
#include "token.h"
#include "exceptions.h"
#include <sstream>
#include <cstdio>
namespace YAML
{
Parser::Parser()
{
}
Parser::Parser(std::istream& in)
{
Load(in);
}
Parser::~Parser()
{
}
Parser::operator bool() const
{
return m_pScanner.get() && !m_pScanner->empty();
}
void Parser::Load(std::istream& in)
{
m_pScanner.reset(new Scanner(in));
m_state.Reset();
}
// GetNextDocument
// . Reads the next document in the queue (of tokens).
// . Throws a ParserException on error.
bool Parser::GetNextDocument(Node& document)
{
if(!m_pScanner.get())
return false;
// clear node
document.Clear();
// first read directives
ParseDirectives();
// we better have some tokens in the queue
if(m_pScanner->empty())
return false;
// first eat doc start (optional)
if(m_pScanner->peek().type == Token::DOC_START)
m_pScanner->pop();
// now parse our root node
document.Parse(m_pScanner.get(), m_state);
// and finally eat any doc ends we see
while(!m_pScanner->empty() && m_pScanner->peek().type == Token::DOC_END)
m_pScanner->pop();
// clear anchors from the scanner, which are no longer relevant
m_pScanner->ClearAnchors();
return true;
}
// ParseDirectives
// . Reads any directives that are next in the queue.
void Parser::ParseDirectives()
{
bool readDirective = false;
while(1) {
if(m_pScanner->empty())
break;
Token& token = m_pScanner->peek();
if(token.type != Token::DIRECTIVE)
break;
// we keep the directives from the last document if none are specified;
// but if any directives are specific, then we reset them
if(!readDirective)
m_state.Reset();
readDirective = true;
HandleDirective(&token);
m_pScanner->pop();
}
}
void Parser::HandleDirective(Token *pToken)
{
if(pToken->value == "YAML")
HandleYamlDirective(pToken);
else if(pToken->value == "TAG")
HandleTagDirective(pToken);
}
// HandleYamlDirective
// . Should be of the form 'major.minor' (like a version number)
void Parser::HandleYamlDirective(Token *pToken)
{
if(pToken->params.size() != 1)
throw ParserException(pToken->mark, ErrorMsg::YAML_DIRECTIVE_ARGS);
std::stringstream str(pToken->params[0]);
str >> m_state.version.major;
str.get();
str >> m_state.version.minor;
if(!str || str.peek() != EOF)
throw ParserException(pToken->mark, ErrorMsg::YAML_VERSION + pToken->params[0]);
if(m_state.version.major > 1)
throw ParserException(pToken->mark, ErrorMsg::YAML_MAJOR_VERSION);
// TODO: warning on major == 1, minor > 2?
}
// HandleTagDirective
// . Should be of the form 'handle prefix', where 'handle' is converted to 'prefix' in the file.
void Parser::HandleTagDirective(Token *pToken)
{
if(pToken->params.size() != 2)
throw ParserException(pToken->mark, ErrorMsg::TAG_DIRECTIVE_ARGS);
std::string handle = pToken->params[0], prefix = pToken->params[1];
m_state.tags[handle] = prefix;
}
void Parser::PrintTokens(std::ostream& out)
{
if(!m_pScanner.get())
return;
while(1) {
if(m_pScanner->empty())
break;
out << m_pScanner->peek() << "\n";
m_pScanner->pop();
}
}
}
<|endoftext|> |
<commit_before>#include <boost/test/unit_test.hpp>
#include <boost/thread/thread.hpp>
#include <iostream>
#include "NonblockingSignal.hpp"
#include "RandomSignal.hpp"
#include "Sample.hpp"
using namespace std;
uint8_t mac[RandomSignal::MAC_ADDRESS_SIZE] = { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6 };
BOOST_AUTO_TEST_SUITE(NonblockingSignalTest)
BOOST_AUTO_TEST_CASE(test_create_delete)
{
cout << "NonblockingSignalTest.test_create_delete" << endl;
ISignal* fbci = new RandomSignal();
NonblockingSignal* bci = new NonblockingSignal(fbci);
delete bci;
}
BOOST_AUTO_TEST_CASE(test_create_open_delete)
{
cout << "NonblockingSignalTest.test_create_open_delete" << endl;
RandomSignal* fbci = new RandomSignal();
NonblockingSignal* bci = new NonblockingSignal(fbci);
BOOST_CHECK(bci->open(mac));
for (int i=0; i < RandomSignal::MAC_ADDRESS_SIZE; i++)
BOOST_CHECK_EQUAL(mac[i], fbci->mLastMac[i]);
delete bci;
}
BOOST_AUTO_TEST_CASE(test_create_open_fail_delete)
{
cout << "NonblockingSignalTest.test_create_open_fail_delete" << endl;
RandomSignal* fbci = new RandomSignal();
NonblockingSignal* bci = new NonblockingSignal(fbci);
fbci->mOpenRet = false;
mac[0] = 0xff;
BOOST_CHECK(!bci->open(mac));
for (int i=0; i < RandomSignal::MAC_ADDRESS_SIZE; i++)
BOOST_CHECK_EQUAL(mac[i], fbci->mLastMac[i]);
delete bci;
}
BOOST_AUTO_TEST_CASE(test_open_start_stop)
{
cout << "NonblockingSignalTest.test_open_start_stop " << endl;
RandomSignal* fbci = new RandomSignal();
NonblockingSignal* bci = new NonblockingSignal(fbci);
BOOST_CHECK(bci->open(mac));
BOOST_CHECK(bci->start());
boost::this_thread::sleep(boost::posix_time::seconds(1));
BOOST_CHECK(bci->stop());
}
BOOST_AUTO_TEST_CASE(test_start_stop)
{
cout << "NonblockingSignalTest.test_start_stop " << endl;
RandomSignal* fbci = new RandomSignal();
NonblockingSignal* bci = new NonblockingSignal(fbci);
BOOST_CHECK(bci->start());
BOOST_CHECK(bci->stop());
}
BOOST_AUTO_TEST_CASE(test_start_acquire_stop)
{
cout << "NonblockingSignalTest.test_start_acquire_stop " << endl;
RandomSignal* fbci = new RandomSignal();
NonblockingSignal* bci = new NonblockingSignal(fbci);
BOOST_CHECK(bci->start());
boost::this_thread::sleep(boost::posix_time::seconds(1));
BOOST_CHECK_EQUAL(1, fbci->mStartCount);
BOOST_CHECK(fbci->mAcquireRet <= bci->acquire());
boost::this_thread::sleep(boost::posix_time::seconds(10));
BOOST_CHECK(1 <= fbci->mAcquireCount);
BOOST_CHECK(bci->stop());
}
BOOST_AUTO_TEST_CASE(test_start_3x_acquire_stop)
{
cout << "NonblockingSignalTest.test_start_3x_acquire_stop " << endl;
RandomSignal* fbci = new RandomSignal();
NonblockingSignal* bci = new NonblockingSignal(fbci);
BOOST_CHECK(bci->start());
boost::this_thread::sleep(boost::posix_time::seconds(1));
BOOST_CHECK_EQUAL(1, fbci->mStartCount);
BOOST_CHECK(fbci->mAcquireRet <= bci->acquire());
BOOST_CHECK(fbci->mAcquireRet <= bci->acquire());
BOOST_CHECK(fbci->mAcquireRet <= bci->acquire());
boost::this_thread::sleep(boost::posix_time::seconds(10));
BOOST_CHECK(1 <= fbci->mAcquireCount);
BOOST_CHECK(bci->stop());
}
BOOST_AUTO_TEST_CASE(test_start_3x_acquire_stop_stop)
{
cout << "NonblockingSignalTest.test_start_3x_acquire_stop " << endl;
RandomSignal* fbci = new RandomSignal();
NonblockingSignal* bci = new NonblockingSignal(fbci);
BOOST_CHECK(bci->start());
boost::this_thread::sleep(boost::posix_time::seconds(1));
BOOST_CHECK_EQUAL(1, fbci->mStartCount);
BOOST_CHECK(fbci->mAcquireRet <= bci->acquire());
BOOST_CHECK(fbci->mAcquireRet <= bci->acquire());
BOOST_CHECK(fbci->mAcquireRet <= bci->acquire());
boost::this_thread::sleep(boost::posix_time::seconds(10));
BOOST_CHECK(1 <= fbci->mAcquireCount);
BOOST_CHECK(bci->stop());
BOOST_CHECK(bci->stop());
}
BOOST_AUTO_TEST_CASE(test_start_delete)
{
cout << "NonblockingSignalTest.test_start_delete " << endl;
ISignal* fbci = new RandomSignal();
NonblockingSignal* bci = new NonblockingSignal(fbci);
BOOST_CHECK(bci->start());
delete bci;
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Temporarily exclude NonblockingSignalTests - no time to maintain them.<commit_after>#include <boost/test/unit_test.hpp>
#include <boost/thread/thread.hpp>
#include <iostream>
#include "NonblockingSignal.hpp"
#include "RandomSignal.hpp"
#include "Sample.hpp"
using namespace std;
uint8_t mac[RandomSignal::MAC_ADDRESS_SIZE] = { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6 };
BOOST_AUTO_TEST_SUITE(NonblockingSignalTest)
#if 0
BOOST_AUTO_TEST_CASE(test_create_delete)
{
cout << "NonblockingSignalTest.test_create_delete" << endl;
ISignal* fbci = new RandomSignal();
NonblockingSignal* bci = new NonblockingSignal(fbci);
delete bci;
}
BOOST_AUTO_TEST_CASE(test_create_open_delete)
{
cout << "NonblockingSignalTest.test_create_open_delete" << endl;
RandomSignal* fbci = new RandomSignal();
NonblockingSignal* bci = new NonblockingSignal(fbci);
BOOST_CHECK(bci->open(mac));
for (int i=0; i < RandomSignal::MAC_ADDRESS_SIZE; i++)
BOOST_CHECK_EQUAL(mac[i], fbci->mLastMac[i]);
delete bci;
}
BOOST_AUTO_TEST_CASE(test_create_open_fail_delete)
{
cout << "NonblockingSignalTest.test_create_open_fail_delete" << endl;
RandomSignal* fbci = new RandomSignal();
NonblockingSignal* bci = new NonblockingSignal(fbci);
fbci->mOpenRet = false;
mac[0] = 0xff;
BOOST_CHECK(!bci->open(mac));
for (int i=0; i < RandomSignal::MAC_ADDRESS_SIZE; i++)
BOOST_CHECK_EQUAL(mac[i], fbci->mLastMac[i]);
delete bci;
}
BOOST_AUTO_TEST_CASE(test_open_start_stop)
{
cout << "NonblockingSignalTest.test_open_start_stop " << endl;
RandomSignal* fbci = new RandomSignal();
NonblockingSignal* bci = new NonblockingSignal(fbci);
BOOST_CHECK(bci->open(mac));
BOOST_CHECK(bci->start());
boost::this_thread::sleep(boost::posix_time::seconds(1));
BOOST_CHECK(bci->stop());
}
BOOST_AUTO_TEST_CASE(test_start_stop)
{
cout << "NonblockingSignalTest.test_start_stop " << endl;
RandomSignal* fbci = new RandomSignal();
NonblockingSignal* bci = new NonblockingSignal(fbci);
BOOST_CHECK(bci->start());
BOOST_CHECK(bci->stop());
}
BOOST_AUTO_TEST_CASE(test_start_acquire_stop)
{
cout << "NonblockingSignalTest.test_start_acquire_stop " << endl;
RandomSignal* fbci = new RandomSignal();
NonblockingSignal* bci = new NonblockingSignal(fbci);
BOOST_CHECK(bci->start());
boost::this_thread::sleep(boost::posix_time::seconds(1));
BOOST_CHECK_EQUAL(1, fbci->mStartCount);
BOOST_CHECK(fbci->mAcquireRet <= bci->acquire());
boost::this_thread::sleep(boost::posix_time::seconds(10));
BOOST_CHECK(1 <= fbci->mAcquireCount);
BOOST_CHECK(bci->stop());
}
BOOST_AUTO_TEST_CASE(test_start_3x_acquire_stop)
{
cout << "NonblockingSignalTest.test_start_3x_acquire_stop " << endl;
RandomSignal* fbci = new RandomSignal();
NonblockingSignal* bci = new NonblockingSignal(fbci);
BOOST_CHECK(bci->start());
boost::this_thread::sleep(boost::posix_time::seconds(1));
BOOST_CHECK_EQUAL(1, fbci->mStartCount);
BOOST_CHECK(fbci->mAcquireRet <= bci->acquire());
BOOST_CHECK(fbci->mAcquireRet <= bci->acquire());
BOOST_CHECK(fbci->mAcquireRet <= bci->acquire());
boost::this_thread::sleep(boost::posix_time::seconds(10));
BOOST_CHECK(1 <= fbci->mAcquireCount);
BOOST_CHECK(bci->stop());
}
BOOST_AUTO_TEST_CASE(test_start_3x_acquire_stop_stop)
{
cout << "NonblockingSignalTest.test_start_3x_acquire_stop " << endl;
RandomSignal* fbci = new RandomSignal();
NonblockingSignal* bci = new NonblockingSignal(fbci);
BOOST_CHECK(bci->start());
boost::this_thread::sleep(boost::posix_time::seconds(1));
BOOST_CHECK_EQUAL(1, fbci->mStartCount);
BOOST_CHECK(fbci->mAcquireRet <= bci->acquire());
BOOST_CHECK(fbci->mAcquireRet <= bci->acquire());
BOOST_CHECK(fbci->mAcquireRet <= bci->acquire());
boost::this_thread::sleep(boost::posix_time::seconds(10));
BOOST_CHECK(1 <= fbci->mAcquireCount);
BOOST_CHECK(bci->stop());
BOOST_CHECK(bci->stop());
}
BOOST_AUTO_TEST_CASE(test_start_delete)
{
cout << "NonblockingSignalTest.test_start_delete " << endl;
ISignal* fbci = new RandomSignal();
NonblockingSignal* bci = new NonblockingSignal(fbci);
BOOST_CHECK(bci->start());
delete bci;
}
#endif
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include <stdexcept>
#include "Person.h"
Person::Person(std::string name) {
if(name.empty()){
throw std::invalid_argument("Name can not be empty.");
}
this->name = name;
};
<commit_msg>Add verification to Person constructor<commit_after>#include <stdexcept>
#include "Person.h"
Person::Person(std::string name) {
if(name.empty()){
throw std::invalid_argument("Name cannot be empty.");
}
this->name = name;
};
<|endoftext|> |
<commit_before>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <limits.h>
#include <errno.h>
#include <cstdio>
#include <sys/time.h>
#include <mist/dtsc.h>
#include "player.h"
namespace Player{
///\todo Make getNowMS available in a library
/// Gets the current system time in milliseconds.
long long int getNowMS(){
timeval t;
gettimeofday(&t, 0);
return t.tv_sec * 1000 + t.tv_usec/1000;
}//getNowMS
void setBlocking(int fd, bool blocking){
int flags = fcntl(fd, F_GETFL);
if (blocking){
flags &= ~O_NONBLOCK;
}else{
flags |= O_NONBLOCK;
}
fcntl(fd, F_SETFL, flags);
}
File::File(std::string filename){
stream = new DTSC::Stream(5);
ring = NULL;// ring will be initialized when necessary
fileSrc.open(filename.c_str(), std::ifstream::in | std::ifstream::binary);
setBlocking(STDIN_FILENO, false);//prevent reading from stdin from blocking
std::cout.setf(std::ios::unitbuf);//do not choke
fileSrc.seekg(0, std::ios::end);
fileSize = fileSrc.tellg();
fileSrc.seekg(0);
nextPacket();// initial read always returns nothing
if (!nextPacket()){//parse metadata
std::cout << stream->outHeader();
} else {
std::cerr << "Error: Expected metadata!" << std::endl;
}
};
File::~File() {
if (ring) {
stream->dropRing(ring);
ring = NULL;
}
delete stream;
}
/// \returns Number of read bytes or -1 on EOF
int File::fillBuffer(std::string & buffer){
char buff[1024 * 10];
if (fileSrc.good()){
fileSrc.read(buff, sizeof(buff));
if (fileSrc.eof()) return -1;
buffer.append(buff, fileSrc.gcount());
return fileSrc.gcount();
}
return -1;
}
// \returns True if there is a packet available for pull.
bool File::nextPacket(){
if (stream->parsePacket(inBuffer)){
return true;
} else {
fillBuffer(inBuffer);
}
return false;
}
void File::seek(unsigned int miliseconds){
DTSC::Stream * tmpStream = new DTSC::Stream(1);
unsigned long leftByte = 1, rightByte = fileSize;
unsigned int leftMS = 0, rightMS = INT_MAX;
/// \todo set last packet as last byte, consider metadata
while (rightMS - leftMS >= 100 && leftMS + 100 <= miliseconds){
std::string buffer;
// binary search: pick the first packet on the right
unsigned long medByte = leftByte + (rightByte - leftByte) / 2;
fileSrc.clear();// clear previous IO errors
fileSrc.seekg(medByte);
do{ // find first occurrence of packet
int read_bytes = fillBuffer(buffer);
if (read_bytes < 0){// EOF? O noes! EOF!
goto seekDone;
}
unsigned long header_pos = buffer.find(DTSC::Magic_Packet);
if (header_pos == std::string::npos){
// it is possible that the magic packet is partially shown, e.g. "DTP"
if ((unsigned)read_bytes > strlen(DTSC::Magic_Packet) - 1){
read_bytes -= strlen(DTSC::Magic_Packet) - 1;
buffer.erase(0, read_bytes);
medByte += read_bytes;
}
continue;// continue filling the buffer without parsing packet
}
}while (!tmpStream->parsePacket(buffer));
JSON::Value & medPacket = tmpStream->getPacket(0);
/// \todo What if time does not exist? Currently it just crashes.
// assumes that the time does not get over 49 days (on a 32-bit system)
unsigned int medMS = (unsigned int)medPacket["time"].asInt();
if (medMS > miliseconds){
rightByte = medByte;
rightMS = medMS;
}else if (medMS < miliseconds){
leftByte = medByte;
leftMS = medMS;
}
}
seekDone:
// clear the buffer and adjust file pointer
inBuffer.clear();
fileSrc.seekg(leftByte);
delete tmpStream;
};
std::string & File::getPacket(){
static std::string emptystring;
if (ring->waiting){
return emptystring;
}//still waiting for next buffer?
if (ring->starved){
//if corrupt data, warn and get new DTSC::Ring
std::cerr << "Warning: User was send corrupt video data and send to the next keyframe!" << std::endl;
stream->dropRing(ring);
ring = stream->getRing();
return emptystring;
}
//switch to next buffer
if (ring->b < 0){
ring->waiting = true;
return emptystring;
}//no next buffer? go in waiting mode.
// get current packet
std::string & packet = stream->outPacket(ring->b);
// make next request take a different packet
ring->b--;
return packet;
}
/// Reads a command from stdin. Returns true if a command was read.
bool File::readCommand() {
char line[512];
size_t line_len;
if (fgets(line, sizeof(line), stdin) == NULL){
return false;
}
line_len = strlen(line);
if (line[line_len - 1] == '\n'){
line[--line_len] = 0;
}
{
int position = INT_MAX;// special value that says "invalid"
if (!strncmp("seek ", line, sizeof("seek ") - 1)){
position = atoi(line + sizeof("seek ") - 1);
}
if (!strncmp("relseek ", line, sizeof("relseek " - 1))){
/// \todo implement relseek in a smart way
//position = atoi(line + sizeof("relseek "));
}
if (position != INT_MAX){
File::seek(position);
return true;
}
}
if (!strcmp("play", line)){
playing = true;
}
return false;
}
void File::Play() {
long long now, timeDiff = 0, lastTime = 0;
while (fileSrc.good()) {
if (readCommand()) {
continue;
}
if (!playing){
setBlocking(STDIN_FILENO, true);
continue;
}else{
setBlocking(STDIN_FILENO, false);
}
now = getNowMS();
if (now - timeDiff >= lastTime || lastTime - (now - timeDiff) > 5000) {
if (nextPacket()) {
if (!ring){ring = stream->getRing();}//get ring after reading first non-metadata
std::string & packet = getPacket();
if (packet.empty()){
continue;
}
lastTime = stream->getTime();
if (std::abs(now - timeDiff - lastTime) > 5000) {
timeDiff = now - lastTime;
}
std::cout.write(packet.c_str(), packet.length());
}
} else {
usleep(std::min(999LL, lastTime - (now - timeDiff)) * 1000);
}
}
}
};
int main(int argc, char** argv){
if (argc < 2){
std::cerr << "Usage: " << argv[0] << " filename.dtsc" << std::endl;
return 1;
}
std::string filename = argv[1];
#if DEBUG >= 3
std::cerr << "VoD " << filename << std::endl;
#endif
Player::File file(filename);
file.Play();
return 0;
}
<commit_msg>player: do not drop trailing packets<commit_after>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <limits.h>
#include <errno.h>
#include <cstdio>
#include <sys/time.h>
#include <mist/dtsc.h>
#include "player.h"
namespace Player{
///\todo Make getNowMS available in a library
/// Gets the current system time in milliseconds.
long long int getNowMS(){
timeval t;
gettimeofday(&t, 0);
return t.tv_sec * 1000 + t.tv_usec/1000;
}//getNowMS
void setBlocking(int fd, bool blocking){
int flags = fcntl(fd, F_GETFL);
if (blocking){
flags &= ~O_NONBLOCK;
}else{
flags |= O_NONBLOCK;
}
fcntl(fd, F_SETFL, flags);
}
File::File(std::string filename){
stream = new DTSC::Stream(5);
ring = NULL;// ring will be initialized when necessary
fileSrc.open(filename.c_str(), std::ifstream::in | std::ifstream::binary);
setBlocking(STDIN_FILENO, false);//prevent reading from stdin from blocking
std::cout.setf(std::ios::unitbuf);//do not choke
fileSrc.seekg(0, std::ios::end);
fileSize = fileSrc.tellg();
fileSrc.seekg(0);
nextPacket();// initial read always returns nothing
if (!nextPacket()){//parse metadata
std::cout << stream->outHeader();
} else {
std::cerr << "Error: Expected metadata!" << std::endl;
}
};
File::~File() {
if (ring) {
stream->dropRing(ring);
ring = NULL;
}
delete stream;
}
/// \returns Number of read bytes or -1 on EOF
int File::fillBuffer(std::string & buffer){
char buff[1024 * 10];
if (fileSrc.good()){
fileSrc.read(buff, sizeof(buff));
buffer.append(buff, fileSrc.gcount());
return fileSrc.gcount();
}
return -1;
}
// \returns True if there is a packet available for pull.
bool File::nextPacket(){
if (stream->parsePacket(inBuffer)){
return true;
} else {
fillBuffer(inBuffer);
}
return false;
}
void File::seek(unsigned int miliseconds){
DTSC::Stream * tmpStream = new DTSC::Stream(1);
unsigned long leftByte = 1, rightByte = fileSize;
unsigned int leftMS = 0, rightMS = INT_MAX;
/// \todo set last packet as last byte, consider metadata
while (rightMS - leftMS >= 100 && leftMS + 100 <= miliseconds){
std::string buffer;
// binary search: pick the first packet on the right
unsigned long medByte = leftByte + (rightByte - leftByte) / 2;
fileSrc.clear();// clear previous IO errors
fileSrc.seekg(medByte);
do{ // find first occurrence of packet
int read_bytes = fillBuffer(buffer);
if (read_bytes < 0){// EOF? O noes! EOF!
goto seekDone;
}
unsigned long header_pos = buffer.find(DTSC::Magic_Packet);
if (header_pos == std::string::npos){
// it is possible that the magic packet is partially shown, e.g. "DTP"
if ((unsigned)read_bytes > strlen(DTSC::Magic_Packet) - 1){
read_bytes -= strlen(DTSC::Magic_Packet) - 1;
buffer.erase(0, read_bytes);
medByte += read_bytes;
}
continue;// continue filling the buffer without parsing packet
}
}while (!tmpStream->parsePacket(buffer));
JSON::Value & medPacket = tmpStream->getPacket(0);
/// \todo What if time does not exist? Currently it just crashes.
// assumes that the time does not get over 49 days (on a 32-bit system)
unsigned int medMS = (unsigned int)medPacket["time"].asInt();
if (medMS > miliseconds){
rightByte = medByte;
rightMS = medMS;
}else if (medMS < miliseconds){
leftByte = medByte;
leftMS = medMS;
}
}
seekDone:
// clear the buffer and adjust file pointer
inBuffer.clear();
fileSrc.seekg(leftByte);
delete tmpStream;
};
std::string & File::getPacket(){
static std::string emptystring;
if (ring->waiting){
return emptystring;
}//still waiting for next buffer?
if (ring->starved){
//if corrupt data, warn and get new DTSC::Ring
std::cerr << "Warning: User was send corrupt video data and send to the next keyframe!" << std::endl;
stream->dropRing(ring);
ring = stream->getRing();
return emptystring;
}
//switch to next buffer
if (ring->b < 0){
ring->waiting = true;
return emptystring;
}//no next buffer? go in waiting mode.
// get current packet
std::string & packet = stream->outPacket(ring->b);
// make next request take a different packet
ring->b--;
return packet;
}
/// Reads a command from stdin. Returns true if a command was read.
bool File::readCommand() {
char line[512];
size_t line_len;
if (fgets(line, sizeof(line), stdin) == NULL){
return false;
}
line_len = strlen(line);
if (line[line_len - 1] == '\n'){
line[--line_len] = 0;
}
{
int position = INT_MAX;// special value that says "invalid"
if (!strncmp("seek ", line, sizeof("seek ") - 1)){
position = atoi(line + sizeof("seek ") - 1);
}
if (!strncmp("relseek ", line, sizeof("relseek " - 1))){
/// \todo implement relseek in a smart way
//position = atoi(line + sizeof("relseek "));
}
if (position != INT_MAX){
File::seek(position);
return true;
}
}
if (!strcmp("play", line)){
playing = true;
}
return false;
}
void File::Play() {
long long now, timeDiff = 0, lastTime = 0;
while (fileSrc.good() || !inBuffer.empty()) {
if (readCommand()) {
continue;
}
if (!playing){
setBlocking(STDIN_FILENO, true);
continue;
}else{
setBlocking(STDIN_FILENO, false);
}
now = getNowMS();
if (now - timeDiff >= lastTime || lastTime - (now - timeDiff) > 5000) {
if (nextPacket()) {
if (!ring){ring = stream->getRing();}//get ring after reading first non-metadata
std::string & packet = getPacket();
if (packet.empty()){
continue;
}
lastTime = stream->getTime();
if (std::abs(now - timeDiff - lastTime) > 5000) {
timeDiff = now - lastTime;
}
std::cout.write(packet.c_str(), packet.length());
}
} else {
usleep(std::min(999LL, lastTime - (now - timeDiff)) * 1000);
}
}
}
};
int main(int argc, char** argv){
if (argc < 2){
std::cerr << "Usage: " << argv[0] << " filename.dtsc" << std::endl;
return 1;
}
std::string filename = argv[1];
#if DEBUG >= 3
std::cerr << "VoD " << filename << std::endl;
#endif
Player::File file(filename);
file.Play();
return 0;
}
<|endoftext|> |
<commit_before>#include "FaultState.h"
#include "utilConstants.h"
#include <sstream>
using std::string;
using std::stringstream;
using std::auto_ptr;
using acsalarm::FaultState;
/**
* Default Constructor
*/
FaultState::FaultState()
{
auto_ptr<Timestamp> tstamp(new Timestamp());
setUserTimestamp(tstamp);
}
/**
* Constructor for initializing a fault state with values
*/
FaultState::FaultState(string theFamily, string theMember, int theCode)
{
setFamily(theFamily);
setMember(theMember);
setCode(theCode);
auto_ptr<Timestamp> tstamp(new Timestamp());
setUserTimestamp(tstamp);
}
/**
* Copy constructor.
*/
FaultState::FaultState(const FaultState & fltState)
{
*this = fltState;
}
/**
* Destructor
*/
FaultState::~FaultState()
{
}
/*
* Assignment operator
*/
FaultState & FaultState::operator=(const FaultState & rhs)
{
setFamily(rhs.getFamily());
setCode(rhs.getCode());
setMember(rhs.getMember());
setDescriptor(rhs.getDescriptor());
setActivatedByBackup(rhs.getActivatedByBackup());
setTerminatedByBackup(rhs.getTerminatedByBackup());
if(NULL != rhs.userTimestamp.get())
{
Timestamp * tstampPtr = new Timestamp(*(rhs.userTimestamp));
auto_ptr<Timestamp> tstampAptr(tstampPtr);
setUserTimestamp(tstampAptr);
}
if(NULL != rhs.userProperties.get())
{
Properties * propsPtr = new Properties(*(rhs.userProperties));
auto_ptr<Properties> propsAptr(propsPtr);
setUserProperties(propsAptr);
}
return *this;
}
/**
* Returns an XML representation of the fault state. NOTE: this
* will not be a complete XML document, but just a fragment.
*
* @param amountToIndent the amount (in spaces) to indent for readability
*
* For example:
*
* <fault-state family="AlarmSource" member="ALARM_SOURCE_ANTENNA" code="1">
* <descriptor>TERMINATE</descriptor>
* <user-properties>
* <property name="ASI_PREFIX" value="prefix"/>
* <property name="TEST_PROPERTY" value="TEST_VALUE"/>
* <property name="ASI_SUFFIX" value="suffix"/>
* </user-properties>
* <user-timestamp seconds="1129902763" microseconds="105000"/>
* </fault-state>
*/
string FaultState::toXML(int amountToIndent)
{
string retVal;
// generate the fault-state opening element
// e.g. <fault-state family="AlarmSource" member="ALARM_SOURCE_ANTENNA" code="1">
for(int x = 0; x < amountToIndent; x++)
{
retVal += SPACE;
}
retVal += LESS_THAN_SIGN;
retVal += FAULT_STATE_ELEMENT_NAME;
retVal += SPACE;
// output the fault's family
retVal += FAULT_STATE_FAMILY_ATTRIBUTE_NAME;
retVal += EQUALS_SIGN;
retVal += DOUBLE_QUOTE;
retVal += getFamily();
retVal += DOUBLE_QUOTE;
retVal += SPACE;
// output the fault's member
retVal += FAULT_STATE_MEMBER_ATTRIBUTE_NAME;
retVal += EQUALS_SIGN;
retVal += DOUBLE_QUOTE;
retVal += getMember();
retVal += DOUBLE_QUOTE;
retVal += SPACE;
// output the fault's code
retVal += FAULT_STATE_CODE_ATTRIBUTE_NAME;
retVal += EQUALS_SIGN;
retVal += DOUBLE_QUOTE;
stringstream strStream;
strStream << getCode();
retVal.append(strStream.str());
retVal += DOUBLE_QUOTE;
retVal += GREATER_THAN_SIGN;
retVal += NEWLINE;
// indent for readability
for(int x = 0; x < amountToIndent+3; x++)
{
retVal += SPACE;
}
// generate the descriptor element
// e.g. <descriptor>TERMINATE</descriptor>
retVal += LESS_THAN_SIGN;
retVal += FAULT_STATE_DESCRIPTOR_ELEMENT_NAME;
retVal += GREATER_THAN_SIGN;
retVal += getDescriptor();
retVal += LESS_THAN_SIGN;
retVal += FORWARD_SLASH;
retVal += FAULT_STATE_DESCRIPTOR_ELEMENT_NAME;
retVal += GREATER_THAN_SIGN;
retVal += NEWLINE;
// generate the properties element
// e.g.
//
// <user-properties>
// <property name="ASI_PREFIX" value="prefix"/>
// <property name="TEST_PROPERTY" value="TEST_VALUE"/>
// <property name="ASI_SUFFIX" value="suffix"/>
// </user-properties>
if(NULL == userProperties.get()) {
// TODO: throw an exception or log an error
}
else {
retVal += userProperties->toXML(amountToIndent+3);
}
// generate the user timestamp element
// e.g. <user-timestamp seconds="1129902763" microseconds="105000"/>
if(NULL == userTimestamp.get()) {
// TODO: throw an exception or log an error
}
else {
retVal += userTimestamp->toXML(USER_TIMESTAMP_ELEMENT_NAME, amountToIndent+3);
}
// generate the fault-state closing element
// e.g. </fault-state>
for(int x = 0; x < amountToIndent; x++)
{
retVal += SPACE;
}
retVal += LESS_THAN_SIGN;
retVal += FORWARD_SLASH;
retVal += FAULT_STATE_ELEMENT_NAME;
retVal += GREATER_THAN_SIGN;
retVal += NEWLINE;
return retVal;
}
/**
* Fault family accessor method.
* @param faultFamily the fault family.
*/
void FaultState::setFamily(const string & faultFamily) {
size_t pos;
string nonConstFaultFamily(faultFamily);
do
{
pos = nonConstFaultFamily.find(":");
if (pos != string::npos)
{
nonConstFaultFamily.replace(pos,1,"#");
}
}
while(pos != string::npos);
family = nonConstFaultFamily;
}
/**
* Fault member accessor method.
* @param member the fault member.
*/
void FaultState::setMember(const string & newFaultMember) {
size_t pos;
string nonConstFaultMember(newFaultMember);
do
{
pos = nonConstFaultMember.find(":");
if (pos != string::npos)
{
nonConstFaultMember.replace(pos,1,"#");
}
}
while(pos != string::npos);
member = nonConstFaultMember;
}
<commit_msg>Initisaliza the user proprties to an empty map to avoid having a null pointer around. In particular, avoiding the initialization, a call to getUserProperties() caused a segmentation fault due to a null pointer.<commit_after>#include "FaultState.h"
#include "utilConstants.h"
#include <sstream>
using std::string;
using std::stringstream;
using std::auto_ptr;
using acsalarm::FaultState;
/**
* Default Constructor
*/
FaultState::FaultState():
userTimestamp(new Timestamp()),
userProperties(new Properties())
{
}
/**
* Constructor for initializing a fault state with values
*/
FaultState::FaultState(string theFamily, string theMember, int theCode):
userTimestamp(new Timestamp()),
userProperties(new Properties())
{
setFamily(theFamily);
setMember(theMember);
setCode(theCode);
}
/**
* Copy constructor.
*/
FaultState::FaultState(const FaultState & fltState)
{
*this = fltState;
}
/**
* Destructor
*/
FaultState::~FaultState()
{
}
/*
* Assignment operator
*/
FaultState & FaultState::operator=(const FaultState & rhs)
{
setFamily(rhs.getFamily());
setCode(rhs.getCode());
setMember(rhs.getMember());
setDescriptor(rhs.getDescriptor());
setActivatedByBackup(rhs.getActivatedByBackup());
setTerminatedByBackup(rhs.getTerminatedByBackup());
if(NULL != rhs.userTimestamp.get())
{
Timestamp * tstampPtr = new Timestamp(*(rhs.userTimestamp));
auto_ptr<Timestamp> tstampAptr(tstampPtr);
setUserTimestamp(tstampAptr);
}
if(NULL != rhs.userProperties.get())
{
Properties * propsPtr = new Properties(*(rhs.userProperties));
auto_ptr<Properties> propsAptr(propsPtr);
setUserProperties(propsAptr);
}
return *this;
}
/**
* Returns an XML representation of the fault state. NOTE: this
* will not be a complete XML document, but just a fragment.
*
* @param amountToIndent the amount (in spaces) to indent for readability
*
* For example:
*
* <fault-state family="AlarmSource" member="ALARM_SOURCE_ANTENNA" code="1">
* <descriptor>TERMINATE</descriptor>
* <user-properties>
* <property name="ASI_PREFIX" value="prefix"/>
* <property name="TEST_PROPERTY" value="TEST_VALUE"/>
* <property name="ASI_SUFFIX" value="suffix"/>
* </user-properties>
* <user-timestamp seconds="1129902763" microseconds="105000"/>
* </fault-state>
*/
string FaultState::toXML(int amountToIndent)
{
string retVal;
// generate the fault-state opening element
// e.g. <fault-state family="AlarmSource" member="ALARM_SOURCE_ANTENNA" code="1">
for(int x = 0; x < amountToIndent; x++)
{
retVal += SPACE;
}
retVal += LESS_THAN_SIGN;
retVal += FAULT_STATE_ELEMENT_NAME;
retVal += SPACE;
// output the fault's family
retVal += FAULT_STATE_FAMILY_ATTRIBUTE_NAME;
retVal += EQUALS_SIGN;
retVal += DOUBLE_QUOTE;
retVal += getFamily();
retVal += DOUBLE_QUOTE;
retVal += SPACE;
// output the fault's member
retVal += FAULT_STATE_MEMBER_ATTRIBUTE_NAME;
retVal += EQUALS_SIGN;
retVal += DOUBLE_QUOTE;
retVal += getMember();
retVal += DOUBLE_QUOTE;
retVal += SPACE;
// output the fault's code
retVal += FAULT_STATE_CODE_ATTRIBUTE_NAME;
retVal += EQUALS_SIGN;
retVal += DOUBLE_QUOTE;
stringstream strStream;
strStream << getCode();
retVal.append(strStream.str());
retVal += DOUBLE_QUOTE;
retVal += GREATER_THAN_SIGN;
retVal += NEWLINE;
// indent for readability
for(int x = 0; x < amountToIndent+3; x++)
{
retVal += SPACE;
}
// generate the descriptor element
// e.g. <descriptor>TERMINATE</descriptor>
retVal += LESS_THAN_SIGN;
retVal += FAULT_STATE_DESCRIPTOR_ELEMENT_NAME;
retVal += GREATER_THAN_SIGN;
retVal += getDescriptor();
retVal += LESS_THAN_SIGN;
retVal += FORWARD_SLASH;
retVal += FAULT_STATE_DESCRIPTOR_ELEMENT_NAME;
retVal += GREATER_THAN_SIGN;
retVal += NEWLINE;
// generate the properties element
// e.g.
//
// <user-properties>
// <property name="ASI_PREFIX" value="prefix"/>
// <property name="TEST_PROPERTY" value="TEST_VALUE"/>
// <property name="ASI_SUFFIX" value="suffix"/>
// </user-properties>
if(NULL == userProperties.get()) {
// TODO: throw an exception or log an error
}
else {
retVal += userProperties->toXML(amountToIndent+3);
}
// generate the user timestamp element
// e.g. <user-timestamp seconds="1129902763" microseconds="105000"/>
if(NULL == userTimestamp.get()) {
// TODO: throw an exception or log an error
}
else {
retVal += userTimestamp->toXML(USER_TIMESTAMP_ELEMENT_NAME, amountToIndent+3);
}
// generate the fault-state closing element
// e.g. </fault-state>
for(int x = 0; x < amountToIndent; x++)
{
retVal += SPACE;
}
retVal += LESS_THAN_SIGN;
retVal += FORWARD_SLASH;
retVal += FAULT_STATE_ELEMENT_NAME;
retVal += GREATER_THAN_SIGN;
retVal += NEWLINE;
return retVal;
}
/**
* Fault family accessor method.
* @param faultFamily the fault family.
*/
void FaultState::setFamily(const string & faultFamily) {
size_t pos;
string nonConstFaultFamily(faultFamily);
do
{
pos = nonConstFaultFamily.find(":");
if (pos != string::npos)
{
nonConstFaultFamily.replace(pos,1,"#");
}
}
while(pos != string::npos);
family = nonConstFaultFamily;
}
/**
* Fault member accessor method.
* @param member the fault member.
*/
void FaultState::setMember(const string & newFaultMember) {
size_t pos;
string nonConstFaultMember(newFaultMember);
do
{
pos = nonConstFaultMember.find(":");
if (pos != string::npos)
{
nonConstFaultMember.replace(pos,1,"#");
}
}
while(pos != string::npos);
member = nonConstFaultMember;
}
<|endoftext|> |
<commit_before>/**
* REXUS PIOneERS - Pi_1
* raspi1.cpp
* Purpose: Main logic control of the REXUS PIOneERS experiment handling data
* communication and transfer as well as the boom and antenna sub-systems.
*
* @author David Amison
* @version 2.2 12/10/2017
*/
#include <stdio.h>
#include <cstdint>
#include <unistd.h> //For sleep
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <signal.h> // For catching signals!
#include "RPi_IMU/RPi_IMU.h"
#include "camera/camera.h"
#include "UART/UART.h"
#include "Ethernet/Ethernet.h"
#include "comms/pipes.h"
#include "comms/protocol.h"
#include "comms/packet.h"
#include <wiringPi.h>
#include "pins1.h"
#include "timing/timer.h"
#include "logger/logger.h"
Logger Log("/Docs/Logs/raspi1");
// Main inputs for experiment control
bool flight_mode = false;
// Motor Setup
int encoder_count = 0;
int encoder_rate = 100;
/**
* Advances the encoder_count variable by one.
*/
void count_encoder() {
piLock(1);
encoder_count++;
piUnlock(1);
}
/**
* Checks whether input is activated
* @param pin: GPIO to be checked
* @return true or false
*/
bool poll_input(int pin) {
int count = 0;
for (int i = 0; i < 5; i++) {
count += digitalRead(pin);
delayMicroseconds(200);
}
return (count < 3) ? true : false;
}
// Global variable for the Camera and IMU
PiCamera Cam;
RPi_IMU IMU; // Not initialised yet to prevent damage during lift off
comms::Pipe IMU_stream;
// Setup for the UART communications
int baud = 38400; // TODO find right value for RXSM
RXSM REXUS(baud);
comms::Pipe rxsm_stream;
// Ethernet communication setup and variables (we are acting as client)
int port_no = 31415; // Random unused port for communication
std::string server_name = "raspi2.local";
comms::Pipe ethernet_stream; // 0 = read, 1 = write
Client raspi1(port_no, server_name);
/**
* Handles any SIGINT signals received by the program (i.e. ctrl^c), making sure
* we end all child processes cleanly and reset the gpio pins.
* @param s: Signal received
*/
void signal_handler(int s) {
Log("FATAL") << "Exiting program after signal " << s;
REXUS.sendMsg("Ending Program");
REXUS.end_buffer();
// TODO send exit signal to Pi 2!
if (Cam.is_running()) {
Cam.stopVideo();
Log("INFO") << "Stopping camera process";
} else {
Log("ERROR") << "Camera process died prematurely or did not start";
}
if (ðernet_stream != NULL) {
ethernet_stream.close_pipes();
Log("INFO") << "Closed Ethernet communication";
} else {
Log("ERROR") << "Ethernet process died prematurely or did not start";
}
if (&IMU_stream != NULL) {
IMU_stream.close_pipes();
Log("INFO") << "Closed IMU communication";
} else {
Log("ERROR") << "IMU process died prematurely or did not start";
}
digitalWrite(MOTOR_CW, 0);
digitalWrite(MOTOR_ACW, 0);
// TODO copy data to a further backup directory
Log("INFO") << "Ending program, Pi rebooting";
REXUS.sendMsg("Pi Rebooting");
system("sudo reboot");
exit(1); // This was an unexpected end so we will exit with an error!
}
/**
* When the 'Start of Data Storage' signal is received all data recording
* is stopped (IMU and Camera) and power to the camera is cut off to stop
* shorting due to melting on re-entry. All data is copied into a backup
* directory.
* @return 0 for success, otherwise for failure
*/
int SODS_SIGNAL() {
Log("INFO") << "SODS signal received";
std::cout << "SODS received" << std::endl;
REXUS.sendMsg("SODS received");
if (Cam.is_running()) {
Cam.stopVideo();
Log("INFO") << "Stopping camera process";
} else {
Log("ERROR") << "Camera process died prematurely or did not start";
}
if (ðernet_stream != NULL) {
ethernet_stream.close_pipes();
Log("INFO") << "Closed Ethernet communication";
} else {
Log("ERROR") << "Ethernet process died prematurely or did not start";
}
if (&IMU_stream != NULL) {
IMU_stream.close_pipes();
Log("INFO") << "Closed IMU communication";
} else {
Log("ERROR") << "IMU process died prematurely or did not start";
}
digitalWrite(MOTOR_CW, 0);
digitalWrite(MOTOR_ACW, 0);
// TODO copy data to a further backup directory
Log("INFO") << "Ending program, Pi rebooting";
REXUS.sendMsg("Pi rebooting");
system("sudo reboot");
return 0;
}
/**
* When the 'Start of Experiment' signal is received the boom needs to be
* deployed and the ImP and IMU to start taking measurements. For boom
* deployment is there is no increase in the encoder count or ?? seconds
* have passed since start of deployment then it is assumed that either the
* boom has reached it's full length or something has gone wrong and the
* count of the encoder is sent to ground.
* @return 0 for success, otherwise for failure
*/
int SOE_SIGNAL() {
Log("INFO") << "SOE signal received";
std::cout << "SOE received" << std::endl;
REXUS.sendMsg("SOE received");
// Setup the IMU and start recording
// TODO ensure IMU setup register values are as desired
IMU.setupAcc();
IMU.setupGyr();
IMU.setupMag();
Log("INFO") << "IMU setup";
// Start data collection and store the stream where data is coming through
IMU_stream = IMU.startDataCollection("Docs/Data/Pi1/test");
Log("INFO") << "IMU collecting data";
//comms::byte1_t buf[20]; // Buffer for storing data
comms::Packet p;
if (flight_mode) {
REXUS.sendMsg("Extending boom");
// Extend the boom!
int count = encoder_count;
int diff = encoder_rate;
Timer tmr;
wiringPiISR(MOTOR_IN, INT_EDGE_RISING, count_encoder);
digitalWrite(MOTOR_CW, 1);
digitalWrite(MOTOR_ACW, 0);
Log("INFO") << "Motor triggered, boom deploying";
// Keep checking the encoder count till it reaches the required amount.
while (count < 10000) {
// Lock is used to keep everything thread safe
piLock(1);
diff = encoder_count - count;
count = encoder_count;
piUnlock(1);
Log("INFO") << "Encoder count- " << encoder_count;
Log("INFO") << "Encoder rate- " << diff * 10 << " counts/sec";
// Check the boom is actually deploying
if ((tmr.elapsed() > 20000) && (diff < 10)) {
Log("ERROR") << "Boom not deploying as expected";
break;
}
// Read data from IMU_data_stream and echo it to Ethernet
int n = IMU_stream.binread(&p, sizeof (p));
if (n > 0) {
Log("DATA (IMU1)") << p;
REXUS.sendPacket(p);
ethernet_stream.binwrite(&p, sizeof (p));
Log("INFO") << "Data sent to Ethernet Communications";
}
n = ethernet_stream.binread(&p, sizeof (p));
if (n > 0) {
Log("DATA (PI2)") << p;
REXUS.sendPacket(p);
}
delay(100);
}
digitalWrite(MOTOR_CW, 0); // Stops the motor.
double dist = 0.1256 * (count / 600);
Log("INFO") << "Boom deployed to " << dist << " m";
std::stringstream ss;
ss << "Boom deployed to " << dist << " m";
REXUS.sendMsg(ss.str());
}
Log("INFO") << "Waiting for SODS";
// Wait for the next signal to continue the program
bool signal_received = false;
while (!signal_received) {
// Implements a loop to ensure SOE signal has actually been received
signal_received = poll_input(SODS);
// Read data from IMU_data_stream and echo it to Ethernet
int n = IMU_stream.binread(&p, sizeof (p));
if (n > 0) {
Log("DATA (IMU1)") << p;
REXUS.sendPacket(p);
ethernet_stream.binwrite(&p, sizeof (p));
Log("INFO") << "Data sent to Ethernet Communications";
}
n = ethernet_stream.binread(&p, sizeof (p));
if (n > 0) {
Log("DATA (PI2)") << p;
REXUS.sendPacket(p);
}
delay(10);
}
return SODS_SIGNAL();
}
/**
* When the 'Lift Off' signal is received from the REXUS Module the cameras
* are set to start recording video and we then wait to receive the 'Start
* of Experiment' signal (when the nose-cone is ejected)
*/
int LO_SIGNAL() {
std::cout << "LO Recevied" << std::endl;
Log("INFO") << "LO signal received";
REXUS.sendMsg("LO received");
Cam.startVideo("Docs/Video/rexus_video");
Log("INFO") << "Camera recording";
REXUS.sendMsg("Recording Video");
// Poll the SOE pin until signal is received
// TODO implement check to make sure no false signals!
Log("INFO") << "Waiting for SOE";
REXUS.sendMsg("Waiting for SOE");
bool signal_received = false;
while (!signal_received) {
delay(10);
// Implements a loop to ensure SOE signal has actually been received
signal_received = poll_input(SOE);
// TODO Implement communications with RXSM
}
return SOE_SIGNAL();
}
/**
* This part of the program is run before the Lift-Off. In effect it
* continually listens for commands from the ground station and runs any
* required tests, regularly reporting status until the LO Signal is
* received.
*/
int main(int argc, char* argv[]) {
// Create necessary directories for saving files
signal(SIGINT, signal_handler);
system("mkdir -p Docs/Data/Pi1 Docs/Data/Pi2 Docs/Data/test Docs/Video Docs/Logs");
Log.start_log();
REXUS.buffer();
Log("INFO") << "Pi 1 is running";
std::cout << "Pi 1 is running";
REXUS.sendMsg("Pi 1 Alive");
// Setup wiringpi
wiringPiSetup();
// Setup main signal pins
pinMode(LO, INPUT);
pullUpDnControl(LO, PUD_UP);
pinMode(SOE, INPUT);
pullUpDnControl(SOE, PUD_UP);
pinMode(SODS, INPUT);
pullUpDnControl(SODS, PUD_UP);
pinMode(ALIVE, INPUT);
pullUpDnControl(ALIVE, PUD_DOWN);
Log("INFO") << "Main signal pins setup" << std::endl;
// Setup pins and check whether we are in flight mode
pinMode(LAUNCH_MODE, INPUT);
pullUpDnControl(LAUNCH_MODE, PUD_UP);
flight_mode = digitalRead(LAUNCH_MODE);
Log("INFO") << (flight_mode ? "flight mode enabled" : "test mode enabled");
if (flight_mode)
REXUS.sendMsg("WARNING: Flight mode enabled");
else
REXUS.sendMsg("Entering test mode");
// Setup Motor Pins
pinMode(MOTOR_CW, OUTPUT);
pinMode(MOTOR_ACW, OUTPUT);
digitalWrite(MOTOR_CW, 0);
digitalWrite(MOTOR_ACW, 0);
Log("INFO") << "Pins for motor control setup";
// Wait for GPIO to go high signalling that Pi2 is ready to communicate
while (!digitalRead(ALIVE))
Timer::sleep_ms(10);
Log("INFO") << "INFO: Trying to establish Ethernet connection with " << server_name;
// Try to connect to Pi 2
try {
ethernet_stream = raspi1.run("Docs/Data/Pi2/backup.txt");
} catch (EthernetException e) {
Log("FATAL") << "FATAL: Ethernet connection failed with error\n\t\"" << e.what()
<< "\"";
signal_handler(-5);
}
std::cout << "Ethernet connected" << std::endl;
// TODO handle error where we can't connect to the server
Log("INFO") << "Ethernet connection successful";
Log("INFO") << "Waiting for LO";
REXUS.sendMsg("Ethernet connected");
REXUS.sendMsg("Waiting for LO");
std::cout << "Waiting for LO" << std::endl;
// Wait for LO signal
bool signal_received = false;
while (!signal_received) {
Timer::sleep_ms(10);
// Implements a loop to ensure LO signal has actually been received
signal_received = poll_input(LO);
// TODO Implement communications with RXSM
}
LO_SIGNAL();
return 0;
}
<commit_msg>Fix Signal Handlers<commit_after>/**
* REXUS PIOneERS - Pi_1
* raspi1.cpp
* Purpose: Main logic control of the REXUS PIOneERS experiment handling data
* communication and transfer as well as the boom and antenna sub-systems.
*
* @author David Amison
* @version 2.2 12/10/2017
*/
#include <stdio.h>
#include <cstdint>
#include <unistd.h> //For sleep
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <signal.h> // For catching signals!
#include "RPi_IMU/RPi_IMU.h"
#include "camera/camera.h"
#include "UART/UART.h"
#include "Ethernet/Ethernet.h"
#include "comms/pipes.h"
#include "comms/protocol.h"
#include "comms/packet.h"
#include <wiringPi.h>
#include "pins1.h"
#include "timing/timer.h"
#include "logger/logger.h"
Logger Log("/Docs/Logs/raspi1");
// Main inputs for experiment control
bool flight_mode = false;
// Motor Setup
int encoder_count = 0;
int encoder_rate = 100;
/**
* Advances the encoder_count variable by one.
*/
void count_encoder() {
piLock(1);
encoder_count++;
piUnlock(1);
}
/**
* Checks whether input is activated
* @param pin: GPIO to be checked
* @return true or false
*/
bool poll_input(int pin) {
int count = 0;
for (int i = 0; i < 5; i++) {
count += digitalRead(pin);
delayMicroseconds(200);
}
return (count > 2) ? true : false;
}
// Global variable for the Camera and IMU
PiCamera Cam;
RPi_IMU IMU; // Not initialised yet to prevent damage during lift off
comms::Pipe IMU_stream;
// Setup for the UART communications
int baud = 38400; // TODO find right value for RXSM
RXSM REXUS(baud);
comms::Pipe rxsm_stream;
// Ethernet communication setup and variables (we are acting as client)
int port_no = 31415; // Random unused port for communication
std::string server_name = "raspi2.local";
comms::Pipe ethernet_stream; // 0 = read, 1 = write
Client raspi1(port_no, server_name);
/**
* Handles any SIGINT signals received by the program (i.e. ctrl^c), making sure
* we end all child processes cleanly and reset the gpio pins.
* @param s: Signal received
*/
void signal_handler(int s) {
Log("FATAL") << "Exiting program after signal " << s;
REXUS.sendMsg("Ending Program");
REXUS.end_buffer();
// TODO send exit signal to Pi 2!
if (Cam.is_running()) {
Cam.stopVideo();
Log("INFO") << "Stopping camera process";
} else {
Log("ERROR") << "Camera process died prematurely or did not start";
}
if (ðernet_stream != NULL) {
ethernet_stream.close_pipes();
Log("INFO") << "Closed Ethernet communication";
} else {
Log("ERROR") << "Ethernet process died prematurely or did not start";
}
if (&IMU_stream != NULL) {
IMU_stream.close_pipes();
Log("INFO") << "Closed IMU communication";
} else {
Log("ERROR") << "IMU process died prematurely or did not start";
}
digitalWrite(MOTOR_CW, 0);
digitalWrite(MOTOR_ACW, 0);
// TODO copy data to a further backup directory
Log("INFO") << "Ending program, Pi rebooting";
REXUS.sendMsg("Pi Rebooting");
system("sudo reboot");
exit(1); // This was an unexpected end so we will exit with an error!
}
/**
* When the 'Start of Data Storage' signal is received all data recording
* is stopped (IMU and Camera) and power to the camera is cut off to stop
* shorting due to melting on re-entry. All data is copied into a backup
* directory.
* @return 0 for success, otherwise for failure
*/
int SODS_SIGNAL() {
Log("INFO") << "SODS signal received";
std::cout << "SODS received" << std::endl;
REXUS.sendMsg("SODS received");
if (Cam.is_running()) {
Cam.stopVideo();
Log("INFO") << "Stopping camera process";
} else {
Log("ERROR") << "Camera process died prematurely or did not start";
}
if (ðernet_stream != NULL) {
ethernet_stream.close_pipes();
Log("INFO") << "Closed Ethernet communication";
} else {
Log("ERROR") << "Ethernet process died prematurely or did not start";
}
if (&IMU_stream != NULL) {
IMU_stream.close_pipes();
Log("INFO") << "Closed IMU communication";
} else {
Log("ERROR") << "IMU process died prematurely or did not start";
}
digitalWrite(MOTOR_CW, 0);
digitalWrite(MOTOR_ACW, 0);
// TODO copy data to a further backup directory
Log("INFO") << "Ending program, Pi rebooting";
REXUS.sendMsg("Pi rebooting");
system("sudo reboot");
return 0;
}
/**
* When the 'Start of Experiment' signal is received the boom needs to be
* deployed and the ImP and IMU to start taking measurements. For boom
* deployment is there is no increase in the encoder count or ?? seconds
* have passed since start of deployment then it is assumed that either the
* boom has reached it's full length or something has gone wrong and the
* count of the encoder is sent to ground.
* @return 0 for success, otherwise for failure
*/
int SOE_SIGNAL() {
Log("INFO") << "SOE signal received";
std::cout << "SOE received" << std::endl;
REXUS.sendMsg("SOE received");
// Setup the IMU and start recording
// TODO ensure IMU setup register values are as desired
IMU.setupAcc();
IMU.setupGyr();
IMU.setupMag();
Log("INFO") << "IMU setup";
// Start data collection and store the stream where data is coming through
IMU_stream = IMU.startDataCollection("Docs/Data/Pi1/test");
Log("INFO") << "IMU collecting data";
//comms::byte1_t buf[20]; // Buffer for storing data
comms::Packet p;
if (flight_mode) {
REXUS.sendMsg("Extending boom");
// Extend the boom!
int count = encoder_count;
int diff = encoder_rate;
Timer tmr;
wiringPiISR(MOTOR_IN, INT_EDGE_RISING, count_encoder);
digitalWrite(MOTOR_CW, 1);
digitalWrite(MOTOR_ACW, 0);
Log("INFO") << "Motor triggered, boom deploying";
// Keep checking the encoder count till it reaches the required amount.
while (count < 10000) {
// Lock is used to keep everything thread safe
piLock(1);
diff = encoder_count - count;
count = encoder_count;
piUnlock(1);
Log("INFO") << "Encoder count- " << encoder_count;
Log("INFO") << "Encoder rate- " << diff * 10 << " counts/sec";
// Check the boom is actually deploying
if ((tmr.elapsed() > 20000) && (diff < 10)) {
Log("ERROR") << "Boom not deploying as expected";
break;
}
// Read data from IMU_data_stream and echo it to Ethernet
int n = IMU_stream.binread(&p, sizeof (p));
if (n > 0) {
Log("DATA (IMU1)") << p;
REXUS.sendPacket(p);
ethernet_stream.binwrite(&p, sizeof (p));
Log("INFO") << "Data sent to Ethernet Communications";
}
n = ethernet_stream.binread(&p, sizeof (p));
if (n > 0) {
Log("DATA (PI2)") << p;
REXUS.sendPacket(p);
}
delay(100);
}
digitalWrite(MOTOR_CW, 0); // Stops the motor.
double dist = 0.1256 * (count / 600);
Log("INFO") << "Boom deployed to " << dist << " m";
std::stringstream ss;
ss << "Boom deployed to " << dist << " m";
REXUS.sendMsg(ss.str());
}
Log("INFO") << "Waiting for SODS";
// Wait for the next signal to continue the program
bool signal_received = false;
while (!signal_received) {
// Implements a loop to ensure SOE signal has actually been received
signal_received = poll_input(SODS);
// Read data from IMU_data_stream and echo it to Ethernet
int n = IMU_stream.binread(&p, sizeof (p));
if (n > 0) {
Log("DATA (IMU1)") << p;
REXUS.sendPacket(p);
ethernet_stream.binwrite(&p, sizeof (p));
Log("INFO") << "Data sent to Ethernet Communications";
}
n = ethernet_stream.binread(&p, sizeof (p));
if (n > 0) {
Log("DATA (PI2)") << p;
REXUS.sendPacket(p);
}
delay(10);
}
return SODS_SIGNAL();
}
/**
* When the 'Lift Off' signal is received from the REXUS Module the cameras
* are set to start recording video and we then wait to receive the 'Start
* of Experiment' signal (when the nose-cone is ejected)
*/
int LO_SIGNAL() {
std::cout << "LO Recevied" << std::endl;
Log("INFO") << "LO signal received";
REXUS.sendMsg("LO received");
Cam.startVideo("Docs/Video/rexus_video");
Log("INFO") << "Camera recording";
REXUS.sendMsg("Recording Video");
// Poll the SOE pin until signal is received
// TODO implement check to make sure no false signals!
Log("INFO") << "Waiting for SOE";
REXUS.sendMsg("Waiting for SOE");
bool signal_received = false;
while (!signal_received) {
delay(10);
// Implements a loop to ensure SOE signal has actually been received
signal_received = poll_input(SOE);
// TODO Implement communications with RXSM
}
return SOE_SIGNAL();
}
/**
* This part of the program is run before the Lift-Off. In effect it
* continually listens for commands from the ground station and runs any
* required tests, regularly reporting status until the LO Signal is
* received.
*/
int main(int argc, char* argv[]) {
// Create necessary directories for saving files
signal(SIGINT, signal_handler);
system("mkdir -p Docs/Data/Pi1 Docs/Data/Pi2 Docs/Data/test Docs/Video Docs/Logs");
Log.start_log();
REXUS.buffer();
Log("INFO") << "Pi 1 is running";
std::cout << "Pi 1 is running" << std::endl;
REXUS.sendMsg("Pi 1 Alive");
// Setup wiringpi
wiringPiSetup();
// Setup main signal pins
pinMode(LO, INPUT);
pullUpDnControl(LO, PUD_UP);
pinMode(SOE, INPUT);
pullUpDnControl(SOE, PUD_UP);
pinMode(SODS, INPUT);
pullUpDnControl(SODS, PUD_UP);
pinMode(ALIVE, INPUT);
pullUpDnControl(ALIVE, PUD_DOWN);
Log("INFO") << "Main signal pins setup" << std::endl;
// Setup pins and check whether we are in flight mode
pinMode(LAUNCH_MODE, INPUT);
pullUpDnControl(LAUNCH_MODE, PUD_UP);
flight_mode = digitalRead(LAUNCH_MODE);
Log("INFO") << (flight_mode ? "flight mode enabled" : "test mode enabled");
if (flight_mode)
REXUS.sendMsg("WARNING: Flight mode enabled");
else
REXUS.sendMsg("Entering test mode");
// Setup Motor Pins
pinMode(MOTOR_CW, OUTPUT);
pinMode(MOTOR_ACW, OUTPUT);
digitalWrite(MOTOR_CW, 0);
digitalWrite(MOTOR_ACW, 0);
Log("INFO") << "Pins for motor control setup";
// Wait for GPIO to go high signalling that Pi2 is ready to communicate
while (!digitalRead(ALIVE))
Timer::sleep_ms(10);
Log("INFO") << "INFO: Trying to establish Ethernet connection with " << server_name;
// Try to connect to Pi 2
try {
ethernet_stream = raspi1.run("Docs/Data/Pi2/backup.txt");
} catch (EthernetException e) {
Log("FATAL") << "FATAL: Ethernet connection failed with error\n\t\"" << e.what()
<< "\"";
signal_handler(-5);
}
std::cout << "Ethernet connected" << std::endl;
// TODO handle error where we can't connect to the server
Log("INFO") << "Ethernet connection successful";
Log("INFO") << "Waiting for LO";
REXUS.sendMsg("Ethernet connected");
REXUS.sendMsg("Waiting for LO");
std::cout << "Waiting for LO" << std::endl;
// Wait for LO signal
bool signal_received = false;
while (!signal_received) {
Timer::sleep_ms(10);
// Implements a loop to ensure LO signal has actually been received
signal_received = poll_input(LO);
// TODO Implement communications with RXSM
}
LO_SIGNAL();
return 0;
}
<|endoftext|> |
<commit_before>#include <string>
#include <Spark/Spmv.hpp>
#include <Spark/SimpleSpmv.hpp>
#include <Spark/Utils.hpp>
#include <Eigen/Sparse>
#include <Spark/io.hpp>
#include <dfesnippets/Timing.hpp>
#include <chrono>
#include <boost/program_options.hpp>
using namespace spark::spmv;
using namespace spark::utils;
// returns the best architecture
std::shared_ptr<SpmvArchitecture> dse(
std::string basename,
SpmvArchitectureSpace* af,
Eigen::SparseMatrix<double, Eigen::RowMajor> mat) {
int it = 0;
std::shared_ptr<SpmvArchitecture> bestArchitecture, a;
std::cout << "bestArchitecture === nul " << (bestArchitecture == nullptr) << std::endl;
while (a = af->next()) {
auto start = std::chrono::high_resolution_clock::now();
a->preprocess(mat); // do spmv?
std::cout << "Matrix: " << basename << " " << a->to_string() << std::endl;
std::cout << " ResourceUsage: " << a->getResourceUsage().to_string() << std::endl;
dfesnippets::timing::print_clock_diff("Took: ", start);
if (bestArchitecture == nullptr ||
a->getEstimatedGFlops() > bestArchitecture->getEstimatedGFlops()) {
std::cout << "Setting best architecture" << std::endl;
bestArchitecture = a;
}
}
std::cout << "Best architecture ";
std::cout << *bestArchitecture << std::endl;
return bestArchitecture;
}
int run (std::string path, Range numPipesRange, Range inputWidthRange, Range cacheSizeRange) {
std::size_t pos = path.find_last_of("/");
std::string basename(path.substr(pos, path.size() - pos));
std::cout << basename << std::endl;
spark::io::MmReader<double> m(path);
auto start = std::chrono::high_resolution_clock::now();
auto eigenMatrix = spark::converters::tripletToEigen(m.mmreadMatrix(path));
dfesnippets::timing::print_clock_diff("Reading took: ", start);
// XXX memory leak
std::vector<SpmvArchitectureSpace*> factories{
new SimpleSpmvArchitectureSpace<SimpleSpmvArchitecture>(numPipesRange, inputWidthRange, cacheSizeRange),
new FstSpmvArchitectureSpace(numPipesRange, inputWidthRange, cacheSizeRange)
};
for (auto sas : factories) {
dse(basename, sas, *eigenMatrix);
}
delete(factories[0]);
delete(factories[1]);
}
int main(int argc, char** argv) {
namespace po = boost::program_options;
std::string numPipes = "numPipes";
std::string cacheSize = "cacheSize";
std::string inputWidth = "inputWidth";
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
(numPipes.c_str(), po::value<std::string>(), "range for number of pipes: start,end,step")
(cacheSize.c_str(), po::value<std::string>(), "range for cache size")
(inputWidth.c_str(), po::value<std::string>(), "range for input width")
("filePath", po::value<std::string>(), "path to matrix")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << "\n";
return 1;
}
std::string path;
if (vm.count("filePath")) {
path = vm["filePath"].as<std::string>();
} else {
std::cout << "Matrix path was not set.\n";
return 1;
}
Range numPipesRange{1, 6, 1}, inputWidthRange{8, 96, 8}, cacheSizeRange{1024, 4096, 1024};
if (vm.count(numPipes)) {
numPipesRange = Range(vm[numPipes].as<std::string>());
}
if (vm.count(inputWidth)) {
inputWidthRange = Range(vm[inputWidth].as<std::string>());
}
if (vm.count(cacheSize)) {
cacheSizeRange = Range(vm[cacheSize].as<std::string>());
}
auto start = std::chrono::high_resolution_clock::now();
int status = run(path, numPipesRange, inputWidthRange, cacheSizeRange);
dfesnippets::timing::print_clock_diff("Test took: ", start);
if (status == 0)
std::cout << "All tests passed!" << std::endl;
else
std::cout << "Tests failed!" << std::endl;
return status;
}
<commit_msg>Cleanups<commit_after>#include <string>
#include <Spark/Spmv.hpp>
#include <Spark/SimpleSpmv.hpp>
#include <Spark/Utils.hpp>
#include <Eigen/Sparse>
#include <Spark/io.hpp>
#include <dfesnippets/Timing.hpp>
#include <chrono>
#include <boost/program_options.hpp>
using namespace spark::spmv;
using namespace spark::utils;
// returns the best architecture
std::shared_ptr<SpmvArchitecture> dse(
std::string basename,
SpmvArchitectureSpace* af,
Eigen::SparseMatrix<double, Eigen::RowMajor> mat) {
int it = 0;
std::shared_ptr<SpmvArchitecture> bestArchitecture, a;
while (a = af->next()) {
auto start = std::chrono::high_resolution_clock::now();
a->preprocess(mat); // do spmv?
std::cout << "Matrix: " << basename << " " << a->to_string() << std::endl;
std::cout << " ResourceUsage: " << a->getResourceUsage().to_string() << std::endl;
dfesnippets::timing::print_clock_diff("Took: ", start);
if (bestArchitecture == nullptr ||
a->getEstimatedGFlops() > bestArchitecture->getEstimatedGFlops()) {
bestArchitecture = a;
}
}
std::cout << "Best architecture ";
std::cout << *bestArchitecture << std::endl;
return bestArchitecture;
}
int run (std::string path, Range numPipesRange, Range inputWidthRange, Range cacheSizeRange) {
std::size_t pos = path.find_last_of("/");
std::string basename(path.substr(pos, path.size() - pos));
std::cout << basename << std::endl;
spark::io::MmReader<double> m(path);
auto start = std::chrono::high_resolution_clock::now();
auto eigenMatrix = spark::converters::tripletToEigen(m.mmreadMatrix(path));
dfesnippets::timing::print_clock_diff("Reading took: ", start);
// XXX memory leak
std::vector<SpmvArchitectureSpace*> factories{
new SimpleSpmvArchitectureSpace<SimpleSpmvArchitecture>(numPipesRange, inputWidthRange, cacheSizeRange),
new FstSpmvArchitectureSpace(numPipesRange, inputWidthRange, cacheSizeRange)
};
for (auto sas : factories) {
dse(basename, sas, *eigenMatrix);
}
delete(factories[0]);
delete(factories[1]);
}
int main(int argc, char** argv) {
namespace po = boost::program_options;
std::string numPipes = "numPipes";
std::string cacheSize = "cacheSize";
std::string inputWidth = "inputWidth";
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
(numPipes.c_str(), po::value<std::string>(), "range for number of pipes: start,end,step")
(cacheSize.c_str(), po::value<std::string>(), "range for cache size")
(inputWidth.c_str(), po::value<std::string>(), "range for input width")
("filePath", po::value<std::string>(), "path to matrix")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << "\n";
return 1;
}
std::string path;
if (vm.count("filePath")) {
path = vm["filePath"].as<std::string>();
} else {
std::cout << "Matrix path was not set.\n";
return 1;
}
Range numPipesRange{1, 6, 1}, inputWidthRange{8, 96, 8}, cacheSizeRange{1024, 4096, 1024};
if (vm.count(numPipes)) {
numPipesRange = Range(vm[numPipes].as<std::string>());
}
if (vm.count(inputWidth)) {
inputWidthRange = Range(vm[inputWidth].as<std::string>());
}
if (vm.count(cacheSize)) {
cacheSizeRange = Range(vm[cacheSize].as<std::string>());
}
auto start = std::chrono::high_resolution_clock::now();
int status = run(path, numPipesRange, inputWidthRange, cacheSizeRange);
dfesnippets::timing::print_clock_diff("Test took: ", start);
if (status == 0)
std::cout << "All tests passed!" << std::endl;
else
std::cout << "Tests failed!" << std::endl;
return status;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <boost/tokenizer.hpp> //Boost tokenizer
#include <unistd.h> // Fork()
#include <sys/types.h> // Wait()
#include <sys/wait.h> // Wait()
#include <vector>
#include <stdio.h> //Perror()
#include <errno.h> // Perror()
#include <algorithm>
using namespace std;
using namespace boost;
// Chose to write function comparing c-strings rather than copy to string then compare
// Used for checking exit command
bool cStringEqual(char* c1, char* c2)
{
int i;
for(i = 0; c1[i] != '\0' && c2[i] != '\0'; ++i)
{
if(c1[i] != c2[i])
{
return false;
}
}
if(c1[i] != '\0' || c2[i] != '\0')
{
return false;
}
return true;
}
int main()
{
while(true) //Shell runs until the exit command
{
cout << "$ "; // Prints command prompt
string commandLine;
getline(cin, commandLine);
// Accounts for comments by removing parts that are comments
// TODO: Account for escape character + comment (\#)
if(commandLine.find(" #") != string::npos)
{
commandLine = commandLine.substr(commandLine.find(" #"));
}
// Finds locations of connectors; a && b, && has a location of 3
vector<unsigned int> connectorLocs;
unsigned int marker = 0; // Marks location to start find() from
while(commandLine.find("&&", marker) != string::npos)//loc != string::npos)
{
connectorLocs.push_back(commandLine.find("&&", marker));
marker = commandLine.find("&&", marker) + 2;//loc + 2; // Starts searching after "&&"
}
marker = 0;
while(commandLine.find("||", marker) != string::npos)
{
connectorLocs.push_back(commandLine.find("||", marker));
marker = commandLine.find("||", marker) + 2; // Starts searching after "||"
}
marker = 0;
while(commandLine.find(";", marker) != string::npos)
{
connectorLocs.push_back(commandLine.find(";", marker));
marker = commandLine.find(";", marker)+ 1; // Starts searching after ";"
}
connectorLocs.push_back(0); // Will be sorted and put in beginning
sort(connectorLocs.begin(), connectorLocs.end()); // Sorted to find each subcommand substring
connectorLocs.push_back(commandLine.size()); // One past end index will act like connector
// Runs through subcommands and runs each one
// Works for connectors with nothing between them (tokenizer will have "" => syntax error, which is expected)
for(unsigned int i = 0; i < connectorLocs.size() - 1; ++i) // # of subcommands == # of connectors - 1 (including 0, one-past-end)
{
// For parsing line of commands; delimiter is whitespace, each token will be a command or an argument
vector<char*> args;
char_separator<char> delim(" ");
tokenizer<char_separator<char>> tok(commandLine.substr(connectorLocs.at(i), connectorLocs.at(i+1) - connectorLocs.at(i)), delim);
// First token is the command, other tokens are the arguments
for(auto iter = tok.begin(); iter != tok.end(); ++iter)
{
args.push_back(const_cast<char*> (iter->c_str()));
}
char* exitCString = const_cast<char*> ("exit");
//cout << cStringEqual(args.at(0), exitCString) << endl;
if(cStringEqual(args.at(0), exitCString)) // if command is exit, exit shell
{
exit(0);
}
// Executes commands/takes care of errors
int pid = fork();
if(pid == -1) // If fork fails
{
perror("Fork error");
exit(1);
}
else
{
if(pid == 0) // Child process
{
execvp(args.at(0), &args.at(0));
// Following don't run if execvp succeeds
perror("Command execution error");
_exit(1);
}
else // Parent process
{
int status; // Status isn't used but might use in future?
if(wait(&status) == -1) // If child process has error
{
perror("Child process error");
// exits if next connector is && or one-past-end element
// continues if next connector is ; or ||
if(connectorLocs.at(i+1) == commandLine.size() || commandLine.at(connectorLocs.at(i+1)) == '&')
{
break;
}
}
}
}
}
}
return 0;
}
<commit_msg>Fixed line lengths<commit_after>#include <iostream>
#include <string>
#include <boost/tokenizer.hpp> //Boost tokenizer
#include <unistd.h> // Fork()
#include <sys/types.h> // Wait()
#include <sys/wait.h> // Wait()
#include <vector>
#include <stdio.h> //Perror()
#include <errno.h> // Perror()
#include <algorithm>
using namespace std;
using namespace boost;
// Chose to write function comparing c-strings rather than copy to string then compare
// Used for checking exit command
bool cStringEqual(char* c1, char* c2)
{
int i;
for(i = 0; c1[i] != '\0' && c2[i] != '\0'; ++i)
{
if(c1[i] != c2[i])
{
return false;
}
}
if(c1[i] != '\0' || c2[i] != '\0')
{
return false;
}
return true;
}
int main()
{
while(true) //Shell runs until the exit command
{
cout << "$ "; // Prints command prompt
string commandLine;
getline(cin, commandLine);
// Accounts for comments by removing parts that are comments
// TODO: Account for escape character + comment (\#)
if(commandLine.find(" #") != string::npos)
{
commandLine = commandLine.substr(commandLine.find(" #"));
}
// Finds locations of connectors; a && b, && has a location of 3
vector<unsigned int> connectorLocs;
unsigned int marker = 0; // Marks location to start find() from
while(commandLine.find("&&", marker) != string::npos)//loc != string::npos)
{
connectorLocs.push_back(commandLine.find("&&", marker));
marker = commandLine.find("&&", marker) + 2;//loc + 2; // Starts searching after "&&"
}
marker = 0;
while(commandLine.find("||", marker) != string::npos)
{
connectorLocs.push_back(commandLine.find("||", marker));
marker = commandLine.find("||", marker) + 2; // Starts searching after "||"
}
marker = 0;
while(commandLine.find(";", marker) != string::npos)
{
connectorLocs.push_back(commandLine.find(";", marker));
marker = commandLine.find(";", marker)+ 1; // Starts searching after ";"
}
connectorLocs.push_back(0); // Will be sorted and put in beginning
sort(connectorLocs.begin(), connectorLocs.end()); // Sorted to find each subcommand substring
connectorLocs.push_back(commandLine.size()); // One past end index will act like connector
// Runs through subcommands and runs each one
// Works for connectors with nothing between them (tokenizer will have "" => syntax error, which is expected)
// # of subcommands == # of connectors - 1 (including 0, one-past-end)
for(unsigned int i = 0; i < connectorLocs.size() - 1; ++i)
{
// For parsing line of commands; delimiter is whitespace, each token will be a command or an argument
vector<char*> args;
char_separator<char> delim(" ");
tokenizer<char_separator<char>> tok(commandLine.substr(connectorLocs.at(i),
connectorLocs.at(i+1) - connectorLocs.at(i)), delim);
// First token is the command, other tokens are the arguments
for(auto iter = tok.begin(); iter != tok.end(); ++iter)
{
args.push_back(const_cast<char*> (iter->c_str()));
}
char* exitCString = const_cast<char*> ("exit");
//cout << cStringEqual(args.at(0), exitCString) << endl;
if(cStringEqual(args.at(0), exitCString)) // if command is exit, exit shell
{
exit(0);
}
// Executes commands/takes care of errors
int pid = fork();
if(pid == -1) // If fork fails
{
perror("Fork error");
exit(1);
}
else
{
if(pid == 0) // Child process
{
execvp(args.at(0), &args.at(0));
// Following don't run if execvp succeeds
perror("Command execution error");
_exit(1);
}
else // Parent process
{
int status; // Status isn't used but might use in future?
if(wait(&status) == -1) // If child process has error
{
perror("Child process error");
// exits if next connector is && or one-past-end element
// continues if next connector is ; or ||
if(connectorLocs.at(i+1) == commandLine.size() ||
commandLine.at(connectorLocs.at(i+1)) == '&')
{
break;
}
}
}
}
}
}
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2016 PaddlePaddle 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 <unistd.h>
#include <string>
#include <thread> // NOLINT
#include "gtest/gtest.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/fluid/operators/detail/grpc_client.h"
#include "paddle/fluid/operators/listen_and_serv_op.h"
#include "paddle/fluid/operators/math/math_function.h"
#include "paddle/fluid/operators/math/selected_rows_functor.h"
#include "paddle/fluid/string/printf.h"
USE_NO_KERNEL_OP(listen_and_serv);
namespace f = paddle::framework;
namespace p = paddle::platform;
namespace m = paddle::operators::math;
namespace detail = paddle::operators::detail;
namespace string = paddle::string;
std::unique_ptr<detail::AsyncGRPCServer> rpc_service;
void StartServer() {
f::Scope scope;
p::CPUPlace place;
scope.Var(NCCL_ID_VARNAME);
p::DeviceContextPool& pool = p::DeviceContextPool::Instance();
auto& dev_ctx = *pool.Get(p::CPUPlace());
rpc_service.reset(new detail::AsyncGRPCServer("127.0.0.1:0", true));
f::ProgramDesc empty_program;
f::Executor executor(dev_ctx.GetPlace());
rpc_service->SetScope(&scope);
rpc_service->SetDevCtx(&dev_ctx);
rpc_service->SetProgram(&empty_program);
rpc_service->SetExecutor(&executor);
std::thread server_thread(
std::bind(&detail::AsyncGRPCServer::RunSyncUpdate, rpc_service.get()));
rpc_service->SetCond(0);
auto recv = rpc_service->Get();
LOG(INFO) << "got nccl id and stop server...";
rpc_service->ShutDown();
server_thread.join();
}
TEST(SendNcclId, Normal) {
std::thread server_thread(StartServer);
// wait server to start
rpc_service.WaitServerReady();
f::Scope scope;
p::CPUPlace place;
p::DeviceContextPool& pool = p::DeviceContextPool::Instance();
auto& dev_ctx = *pool.Get(p::CPUPlace());
auto var = scope.Var(NCCL_ID_VARNAME);
// var->SetType(f::proto::VarType_Type_RAW);
auto id = var->GetMutable<ncclUniqueId>();
p::dynload::ncclGetUniqueId(id);
int port = rpc_service->GetSelectedPort();
std::string ep = string::Sprintf("127.0.0.1:%d", port);
detail::RPCClient client;
client.AsyncSendVariable(ep, dev_ctx, scope, NCCL_ID_VARNAME);
client.Wait();
server_thread.join();
auto* ptr = rpc_service.release();
delete ptr;
}
<commit_msg>fix build and merge develop<commit_after>/* Copyright (c) 2016 PaddlePaddle 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 <unistd.h>
#include <string>
#include <thread> // NOLINT
#include "gtest/gtest.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/fluid/operators/detail/grpc_client.h"
#include "paddle/fluid/operators/listen_and_serv_op.h"
#include "paddle/fluid/operators/math/math_function.h"
#include "paddle/fluid/operators/math/selected_rows_functor.h"
#include "paddle/fluid/platform/nccl_helper.h"
#include "paddle/fluid/string/printf.h"
USE_NO_KERNEL_OP(listen_and_serv);
namespace f = paddle::framework;
namespace p = paddle::platform;
namespace m = paddle::operators::math;
namespace detail = paddle::operators::detail;
namespace string = paddle::string;
std::unique_ptr<detail::AsyncGRPCServer> rpc_service;
void StartServer(std::atomic<bool>* initialized) {
f::Scope scope;
p::CPUPlace place;
scope.Var(NCCL_ID_VARNAME);
p::DeviceContextPool& pool = p::DeviceContextPool::Instance();
auto& dev_ctx = *pool.Get(p::CPUPlace());
rpc_service.reset(new detail::AsyncGRPCServer("127.0.0.1:0", true));
f::ProgramDesc empty_program;
f::Executor executor(dev_ctx.GetPlace());
rpc_service->SetScope(&scope);
rpc_service->SetDevCtx(&dev_ctx);
rpc_service->SetProgram(&empty_program);
rpc_service->SetExecutor(&executor);
std::thread server_thread(
std::bind(&detail::AsyncGRPCServer::RunSyncUpdate, rpc_service.get()));
*initialized = true;
rpc_service->SetCond(0);
auto recv = rpc_service->Get();
LOG(INFO) << "got nccl id and stop server...";
rpc_service->ShutDown();
server_thread.join();
}
TEST(SendNcclId, Normal) {
std::atomic<bool> initialized{false};
std::thread server_thread(StartServer, &initialized);
while (!initialized) {
}
// wait server to start
// sleep(2);
rpc_service->WaitServerReady();
f::Scope scope;
p::CPUPlace place;
p::DeviceContextPool& pool = p::DeviceContextPool::Instance();
auto& dev_ctx = *pool.Get(p::CPUPlace());
auto var = scope.Var(NCCL_ID_VARNAME);
// var->SetType(f::proto::VarType_Type_RAW);
auto id = var->GetMutable<ncclUniqueId>();
p::dynload::ncclGetUniqueId(id);
int port = rpc_service->GetSelectedPort();
std::string ep = string::Sprintf("127.0.0.1:%d", port);
detail::RPCClient client;
client.AsyncSendVariable(ep, dev_ctx, scope, NCCL_ID_VARNAME);
client.Wait();
server_thread.join();
auto* ptr = rpc_service.release();
delete ptr;
}
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "sdd/values/bitset.hh"
typedef sdd::values::bitset<64> bitset;
/*-------------------------------------------------------------------------------------------*/
TEST(bitset_test, empty)
{
bitset b;
ASSERT_TRUE(b.empty());
}
/*-------------------------------------------------------------------------------------------*/
TEST(bitset_test, insertion)
{
bitset b;
ASSERT_TRUE(b.empty());
b.insert(1);
b.insert(2);
b.insert(10);
ASSERT_EQ(bitset({1,2,10}), b);
}
/*-------------------------------------------------------------------------------------------*/
TEST(bitset_test, size)
{
ASSERT_EQ(0, bitset({}).size());
ASSERT_EQ(3, bitset({1,2,10}).size());
}
/*-------------------------------------------------------------------------------------------*/
TEST(bitset_test, swap)
{
bitset b1 {0,1,2};
bitset b2 {0};
swap(b1, b2);
ASSERT_EQ(bitset {0}, b1);
ASSERT_EQ(bitset({0,1,2}), b2);
}
/*-------------------------------------------------------------------------------------------*/
TEST(bitset_test, left_shit)
{
ASSERT_EQ(bitset({1,2,3}), bitset({0,1,2}).operator<<(1));
}
/*-------------------------------------------------------------------------------------------*/
TEST(bitset_test, right_shit)
{
ASSERT_EQ(bitset({0,1}), bitset({0,1,2}).operator>>(1));
}
/*-------------------------------------------------------------------------------------------*/
TEST(bitset_test, sum)
{
ASSERT_EQ(bitset(), sum(bitset(), bitset()));
ASSERT_EQ(bitset({0}), sum(bitset({0}), bitset()));
ASSERT_EQ(bitset({0}), sum(bitset({0}), bitset({0})));
ASSERT_EQ(bitset({0,1}), sum(bitset({0}), bitset({1})));
ASSERT_EQ(bitset({0,1}), sum(bitset({0}), bitset({0,1})));
}
/*-------------------------------------------------------------------------------------------*/
TEST(bitset_test, intersection)
{
ASSERT_EQ(bitset(), intersection(bitset(), bitset()));
ASSERT_EQ(bitset(), intersection(bitset({0}), bitset()));
ASSERT_EQ(bitset({0}), intersection(bitset({0}), bitset({0})));
ASSERT_EQ(bitset(), intersection(bitset({0}), bitset({1})));
ASSERT_EQ(bitset({0}), intersection(bitset({0}), bitset({0,1})));
ASSERT_EQ(bitset({0}), intersection(bitset({0,2}), bitset({0,1})));
ASSERT_EQ(bitset({0,1}), intersection(bitset({0,1,2}), bitset({0,1,3})));
}
/*-------------------------------------------------------------------------------------------*/
TEST(bitset_test, difference)
{
ASSERT_EQ(bitset(), difference(bitset(), bitset()));
ASSERT_EQ(bitset({0}), difference(bitset({0}), bitset()));
ASSERT_EQ(bitset(), difference(bitset({0}), bitset({0})));
ASSERT_EQ(bitset({0}), difference(bitset({0}), bitset({1})));
ASSERT_EQ(bitset(), difference(bitset({0}), bitset({0,1})));
ASSERT_EQ(bitset({2}), difference(bitset({0,2}), bitset({0,1})));
ASSERT_EQ(bitset({2}), difference(bitset({0,1,2}), bitset({0,1,3})));
}
/*-------------------------------------------------------------------------------------------*/
<commit_msg>Renaming.<commit_after>#include "gtest/gtest.h"
#include "sdd/values/bitset.hh"
typedef sdd::values::bitset<64> bitset;
/*-------------------------------------------------------------------------------------------*/
TEST(bitset_test, empty)
{
bitset b;
ASSERT_TRUE(b.empty());
}
/*-------------------------------------------------------------------------------------------*/
TEST(bitset_test, insertion)
{
bitset b;
ASSERT_TRUE(b.empty());
b.insert(1);
b.insert(2);
b.insert(10);
ASSERT_EQ(bitset({1,2,10}), b);
}
/*-------------------------------------------------------------------------------------------*/
TEST(bitset_test, size)
{
ASSERT_EQ(0, bitset({}).size());
ASSERT_EQ(3, bitset({1,2,10}).size());
}
/*-------------------------------------------------------------------------------------------*/
TEST(bitset_test, swap)
{
bitset b1 {0,1,2};
bitset b2 {0};
swap(b1, b2);
ASSERT_EQ(bitset {0}, b1);
ASSERT_EQ(bitset({0,1,2}), b2);
}
/*-------------------------------------------------------------------------------------------*/
TEST(bitset_test, left_shift)
{
ASSERT_EQ(bitset({1,2,3}), bitset({0,1,2}).operator<<(1));
}
/*-------------------------------------------------------------------------------------------*/
TEST(bitset_test, right_shift)
{
ASSERT_EQ(bitset({0,1}), bitset({0,1,2}).operator>>(1));
}
/*-------------------------------------------------------------------------------------------*/
TEST(bitset_test, sum)
{
ASSERT_EQ(bitset(), sum(bitset(), bitset()));
ASSERT_EQ(bitset({0}), sum(bitset({0}), bitset()));
ASSERT_EQ(bitset({0}), sum(bitset({0}), bitset({0})));
ASSERT_EQ(bitset({0,1}), sum(bitset({0}), bitset({1})));
ASSERT_EQ(bitset({0,1}), sum(bitset({0}), bitset({0,1})));
}
/*-------------------------------------------------------------------------------------------*/
TEST(bitset_test, intersection)
{
ASSERT_EQ(bitset(), intersection(bitset(), bitset()));
ASSERT_EQ(bitset(), intersection(bitset({0}), bitset()));
ASSERT_EQ(bitset({0}), intersection(bitset({0}), bitset({0})));
ASSERT_EQ(bitset(), intersection(bitset({0}), bitset({1})));
ASSERT_EQ(bitset({0}), intersection(bitset({0}), bitset({0,1})));
ASSERT_EQ(bitset({0}), intersection(bitset({0,2}), bitset({0,1})));
ASSERT_EQ(bitset({0,1}), intersection(bitset({0,1,2}), bitset({0,1,3})));
}
/*-------------------------------------------------------------------------------------------*/
TEST(bitset_test, difference)
{
ASSERT_EQ(bitset(), difference(bitset(), bitset()));
ASSERT_EQ(bitset({0}), difference(bitset({0}), bitset()));
ASSERT_EQ(bitset(), difference(bitset({0}), bitset({0})));
ASSERT_EQ(bitset({0}), difference(bitset({0}), bitset({1})));
ASSERT_EQ(bitset(), difference(bitset({0}), bitset({0,1})));
ASSERT_EQ(bitset({2}), difference(bitset({0,2}), bitset({0,1})));
ASSERT_EQ(bitset({2}), difference(bitset({0,1,2}), bitset({0,1,3})));
}
/*-------------------------------------------------------------------------------------------*/
<|endoftext|> |
<commit_before>// Copyright 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////
#include <assert.h>
#include <openssl/pem.h>
#include <stdio.h>
#include <time.h>
#include <cstdint>
#include "libsxg.h"
namespace {
sxg_signer_list_t MakeSignerList() {
char passwd[] = "";
FILE* keyfile = fopen("testdata/priv256.key", "r");
assert(keyfile != nullptr);
EVP_PKEY* priv_key = PEM_read_PrivateKey(keyfile, nullptr, nullptr, nullptr);
fclose(keyfile);
FILE* certfile = fopen("testdata/cert256.pem", "r");
assert(certfile != nullptr);
X509* cert = PEM_read_X509(certfile, 0, 0, passwd);
fclose(certfile);
const time_t now = 1234567890;
sxg_signer_list_t signers = sxg_empty_signer_list();
bool success = sxg_add_ecdsa_signer(
"my_signer", now, now + 60 * 60 * 24,
"https://original.example.com/resource.validity.msg", priv_key, cert,
"https://yourcdn.example.test/cert.cbor", &signers);
assert(success);
return signers;
}
bool MakeSxg(std::uint8_t const* data, std::size_t size) {
static const sxg_signer_list_t signers = MakeSignerList();
sxg_raw_response_t content = sxg_empty_raw_response();
sxg_encoded_response_t encoded = sxg_empty_encoded_response();
sxg_buffer_t result = sxg_empty_buffer();
bool success = sxg_write_bytes(data, size, &content.payload);
success = success && sxg_encode_response(4096, &content, &encoded);
success = success && sxg_generate("https://original.example.com/index.html",
&signers, &encoded, &result);
sxg_raw_response_release(&content);
sxg_encoded_response_release(&encoded);
sxg_buffer_release(&result);
return success;
}
} // namespace
extern "C" int LLVMFuzzerTestOneInput(std::uint8_t const* data,
std::size_t size) {
if (!MakeSxg(data, size)) {
fprintf(stderr, "Failed to generate sxg.\n");
abort();
}
return 0;
}
<commit_msg>remove extra blank line (#27)<commit_after>// Copyright 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////
#include <assert.h>
#include <openssl/pem.h>
#include <stdio.h>
#include <time.h>
#include <cstdint>
#include "libsxg.h"
namespace {
sxg_signer_list_t MakeSignerList() {
char passwd[] = "";
FILE* keyfile = fopen("testdata/priv256.key", "r");
assert(keyfile != nullptr);
EVP_PKEY* priv_key = PEM_read_PrivateKey(keyfile, nullptr, nullptr, nullptr);
fclose(keyfile);
FILE* certfile = fopen("testdata/cert256.pem", "r");
assert(certfile != nullptr);
X509* cert = PEM_read_X509(certfile, 0, 0, passwd);
fclose(certfile);
const time_t now = 1234567890;
sxg_signer_list_t signers = sxg_empty_signer_list();
bool success = sxg_add_ecdsa_signer(
"my_signer", now, now + 60 * 60 * 24,
"https://original.example.com/resource.validity.msg", priv_key, cert,
"https://yourcdn.example.test/cert.cbor", &signers);
assert(success);
return signers;
}
bool MakeSxg(std::uint8_t const* data, std::size_t size) {
static const sxg_signer_list_t signers = MakeSignerList();
sxg_raw_response_t content = sxg_empty_raw_response();
sxg_encoded_response_t encoded = sxg_empty_encoded_response();
sxg_buffer_t result = sxg_empty_buffer();
bool success = sxg_write_bytes(data, size, &content.payload);
success = success && sxg_encode_response(4096, &content, &encoded);
success = success && sxg_generate("https://original.example.com/index.html",
&signers, &encoded, &result);
sxg_raw_response_release(&content);
sxg_encoded_response_release(&encoded);
sxg_buffer_release(&result);
return success;
}
} // namespace
extern "C" int LLVMFuzzerTestOneInput(std::uint8_t const* data,
std::size_t size) {
if (!MakeSxg(data, size)) {
fprintf(stderr, "Failed to generate sxg.\n");
abort();
}
return 0;
}
<|endoftext|> |
<commit_before>#include "multiverso/server.h"
#include <algorithm>
#include <sstream>
#include <string>
#include <vector>
#include "multiverso/actor.h"
#include "multiverso/dashboard.h"
#include "multiverso/multiverso.h"
#include "multiverso/table_interface.h"
#include "multiverso/io/io.h"
#include "multiverso/util/configure.h"
#include "multiverso/util/mt_queue.h"
#include "multiverso/zoo.h"
namespace multiverso {
MV_DEFINE_bool(sync, false, "sync or async");
MV_DEFINE_int(backup_worker_ratio, 0, "ratio% of backup workers, set 20 means 20%");
Server::Server() : Actor(actor::kServer) {
RegisterHandler(MsgType::Request_Get, std::bind(
&Server::ProcessGet, this, std::placeholders::_1));
RegisterHandler(MsgType::Request_Add, std::bind(
&Server::ProcessAdd, this, std::placeholders::_1));
}
int Server::RegisterTable(ServerTable* server_table) {
int id = static_cast<int>(store_.size());
store_.push_back(server_table);
return id;
}
void Server::ProcessGet(MessagePtr& msg) {
MONITOR_BEGIN(SERVER_PROCESS_GET);
MessagePtr reply(msg->CreateReplyMessage());
int table_id = msg->table_id();
CHECK(table_id >= 0 && table_id < store_.size());
store_[table_id]->ProcessGet(msg->data(), &reply->data());
SendTo(actor::kCommunicator, reply);
MONITOR_END(SERVER_PROCESS_GET);
}
void Server::ProcessAdd(MessagePtr& msg) {
MONITOR_BEGIN(SERVER_PROCESS_ADD)
MessagePtr reply(msg->CreateReplyMessage());
int table_id = msg->table_id();
CHECK(table_id >= 0 && table_id < store_.size());
store_[table_id]->ProcessAdd(msg->data());
SendTo(actor::kCommunicator, reply);
MONITOR_END(SERVER_PROCESS_ADD)
}
// The Sync Server implement logic to support Sync SGD training
// The implementation assumes all the workers will call same number
// of Add and/or Get requests
// The server promise all workers i-th Get will get the same parameters
// If worker k has add delta to server j times when its i-th Get
// then the server will return the parameter after all K
// workers finished their j-th update
class SyncServer : public Server {
public:
SyncServer() : Server() {
int num_worker = Zoo::Get()->num_workers();
worker_get_clocks_.reset(new VectorClock(num_worker));
worker_add_clocks_.reset(new VectorClock(num_worker));
}
// make some modification to suit to the sync server
// please not use in other place, may different with the general vector clock
class VectorClock {
public:
explicit VectorClock(int n) :
local_clock_(n, 0), global_clock_(0), size_(0) {}
// Return true when all clock reach a same number
virtual bool Update(int i) {
++local_clock_[i];
if (global_clock_ < *(std::min_element(std::begin(local_clock_),
std::end(local_clock_)))) {
++global_clock_;
if (global_clock_ == *(std::max_element(std::begin(local_clock_),
std::end(local_clock_)))) {
return true;
}
}
return false;
}
std::string DebugString() {
std::string os = "global ";
os += std::to_string(global_clock_) + " local: ";
for (auto i : local_clock_) os += std::to_string(i) + " ";
return os;
}
int local_clock(int i) const { return local_clock_[i]; }
int global_clock() const { return global_clock_; }
protected:
std::vector<int> local_clock_;
int global_clock_;
int size_;
};
protected:
void ProcessAdd(MessagePtr& msg) override {
// 1. Before add: cache faster worker
int worker = Zoo::Get()->rank_to_worker_id(msg->src());
if (worker_get_clocks_->local_clock(worker) >
worker_get_clocks_->global_clock()) {
msg_add_cache_.Push(msg);
return;
}
// 2. Process Add
Server::ProcessAdd(msg);
// 3. After add: process cached process get if necessary
if (worker_add_clocks_->Update(worker)) {
CHECK(msg_add_cache_.Empty());
while (!msg_get_cache_.Empty()) {
MessagePtr get_msg;
CHECK(msg_get_cache_.TryPop(get_msg));
int get_worker = Zoo::Get()->rank_to_worker_id(get_msg->src());
Server::ProcessGet(get_msg);
worker_get_clocks_->Update(get_worker);
}
}
}
void ProcessGet(MessagePtr& msg) override {
// 1. Before get: cache faster worker
int worker = Zoo::Get()->rank_to_worker_id(msg->src());
if (worker_add_clocks_->local_clock(worker) >
worker_add_clocks_->global_clock()) {
// Will wait for other worker finished Add
msg_get_cache_.Push(msg);
return;
}
// 2. Process Get
Server::ProcessGet(msg);
// 3. After get: process cached process add if necessary
if (worker_get_clocks_->Update(worker)) {
CHECK(msg_get_cache_.Empty());
while (!msg_add_cache_.Empty()) {
MessagePtr add_msg;
CHECK(msg_add_cache_.TryPop(add_msg));
int add_worker = Zoo::Get()->rank_to_worker_id(add_msg->src());
Server::ProcessAdd(add_msg);
worker_add_clocks_->Update(add_worker);
}
}
}
private:
std::unique_ptr<VectorClock> worker_get_clocks_;
std::unique_ptr<VectorClock> worker_add_clocks_;
MtQueue<MessagePtr> msg_add_cache_;
MtQueue<MessagePtr> msg_get_cache_;
};
class WithBackupSyncServer : public Server {
public:
WithBackupSyncServer() : Server() {
num_worker_ = Zoo::Get()->num_workers();
double backup_ratio = (double)MV_CONFIG_backup_worker_ratio / 100;
num_sync_worker_ = num_worker_ -
static_cast<int>(backup_ratio * num_worker_);
CHECK(num_sync_worker_ > 0 && num_sync_worker_ <= num_worker_);
if (num_sync_worker_ == num_worker_) {
Log::Info("No backup worker, using the sync mode\n");
}
Log::Info("Sync with backup worker start: num_sync_worker = %d,"
"num_total_worker = %d\n", num_sync_worker_, num_worker_);
worker_get_clocks_.reset(new SyncServer::VectorClock(num_worker_));
worker_add_clocks_.reset(new VectorClock(num_worker_, num_sync_worker_));
}
// make some modification to suit to the sync server
// please not use in other place, may different with the general vector clock
class VectorClock {
public:
VectorClock(int num_worker, int num_sync_worker) :
local_clock_(num_worker, 0), global_clock_(0), num_worker_(num_worker),
num_sync_worker_(num_sync_worker), progress_(0) {}
// Return true when all clock reach a same number
virtual bool Update(int i) {
if (local_clock_[i]++ == global_clock_) {
++progress_;
}
if (progress_ >= num_sync_worker_) {
++global_clock_;
progress_ = 0;
for (auto i : local_clock_) {
if (i > global_clock_) ++progress_;
}
if (global_clock_ == *(std::max_element(std::begin(local_clock_),
std::end(local_clock_)))) {
return true;
}
}
return false;
}
std::string DebugString() {
std::string os = "global ";
os += std::to_string(global_clock_) + " local: ";
for (auto i : local_clock_) os += std::to_string(i) + " ";
return os;
}
int local_clock(int i) const { return local_clock_[i]; }
int global_clock() const { return global_clock_; }
protected:
std::vector<int> local_clock_;
int global_clock_;
int num_worker_;
int num_sync_worker_;
int progress_;
};
protected:
void ProcessAdd(MessagePtr& msg) override {
// 1. Before add: cache faster worker
int worker = Zoo::Get()->rank_to_worker_id(msg->src());
if (worker_get_clocks_->local_clock(worker) >
worker_get_clocks_->global_clock()) {
msg_add_cache_.Push(msg);
return;
}
// 2. Process Add
if (worker_add_clocks_->local_clock(worker) >=
worker_add_clocks_->global_clock()) {
Server::ProcessAdd(msg);
}
// 3. After add: process cached process get if necessary
if (worker_add_clocks_->Update(worker)) {
CHECK(msg_add_cache_.Empty());
while (!msg_get_cache_.Empty()) {
MessagePtr get_msg;
CHECK(msg_get_cache_.TryPop(get_msg));
int get_worker = Zoo::Get()->rank_to_worker_id(get_msg->src());
Server::ProcessGet(get_msg);
worker_get_clocks_->Update(get_worker);
}
}
}
void ProcessGet(MessagePtr& msg) override {
// 1. Before get: cache faster worker
int worker = Zoo::Get()->rank_to_worker_id(msg->src());
if (worker_add_clocks_->local_clock(worker) >
worker_add_clocks_->global_clock()) {
// Will wait for other worker finished Add
msg_get_cache_.Push(msg);
return;
}
// 2. Process Get
Server::ProcessGet(msg);
// 3. After get: process cached process add if necessary
if (worker_get_clocks_->Update(worker)) {
CHECK(msg_get_cache_.Empty());
while (!msg_add_cache_.Empty()) {
MessagePtr add_msg;
CHECK(msg_add_cache_.TryPop(add_msg));
int add_worker = Zoo::Get()->rank_to_worker_id(add_msg->src());
if (worker_add_clocks_->local_clock(add_worker) >=
worker_add_clocks_->global_clock()) {
Server::ProcessAdd(msg);
};
worker_add_clocks_->Update(add_worker);
}
}
}
private:
std::unique_ptr<SyncServer::VectorClock> worker_get_clocks_;
std::unique_ptr<VectorClock> worker_add_clocks_;
MtQueue<MessagePtr> msg_add_cache_;
MtQueue<MessagePtr> msg_get_cache_;
// num_worker_ - num_sync_worker_ = num_backup_worker_
int num_sync_worker_;
int num_worker_;
};
Server* Server::GetServer() {
if (!MV_CONFIG_sync) {
Log::Info("Create a async server\n");
return new Server();
}
if (MV_CONFIG_backup_worker_ratio > 0.0) {
Log::Info("Create a sync server with backup worker\n");
return new WithBackupSyncServer();
}
Log::Info("Create a sync server\n");
return new SyncServer();
}
} // namespace multiverso
<commit_msg>remove sync server since it's a special case of backup sync server when backup worker num = 0<commit_after>#include "multiverso/server.h"
#include <algorithm>
#include <sstream>
#include <string>
#include <vector>
#include "multiverso/actor.h"
#include "multiverso/dashboard.h"
#include "multiverso/multiverso.h"
#include "multiverso/table_interface.h"
#include "multiverso/io/io.h"
#include "multiverso/util/configure.h"
#include "multiverso/util/mt_queue.h"
#include "multiverso/zoo.h"
namespace multiverso {
MV_DEFINE_bool(sync, false, "sync or async");
MV_DEFINE_int(backup_worker_ratio, 0, "ratio% of backup workers, set 20 means 20%");
Server::Server() : Actor(actor::kServer) {
RegisterHandler(MsgType::Request_Get, std::bind(
&Server::ProcessGet, this, std::placeholders::_1));
RegisterHandler(MsgType::Request_Add, std::bind(
&Server::ProcessAdd, this, std::placeholders::_1));
}
int Server::RegisterTable(ServerTable* server_table) {
int id = static_cast<int>(store_.size());
store_.push_back(server_table);
return id;
}
void Server::ProcessGet(MessagePtr& msg) {
MONITOR_BEGIN(SERVER_PROCESS_GET);
MessagePtr reply(msg->CreateReplyMessage());
int table_id = msg->table_id();
CHECK(table_id >= 0 && table_id < store_.size());
store_[table_id]->ProcessGet(msg->data(), &reply->data());
SendTo(actor::kCommunicator, reply);
MONITOR_END(SERVER_PROCESS_GET);
}
void Server::ProcessAdd(MessagePtr& msg) {
MONITOR_BEGIN(SERVER_PROCESS_ADD)
MessagePtr reply(msg->CreateReplyMessage());
int table_id = msg->table_id();
CHECK(table_id >= 0 && table_id < store_.size());
store_[table_id]->ProcessAdd(msg->data());
SendTo(actor::kCommunicator, reply);
MONITOR_END(SERVER_PROCESS_ADD)
}
// The Sync Server implement logic to support Sync SGD training
// The implementation assumes all the workers will call same number
// of Add and/or Get requests
// The server promise all workers i-th Get will get the same parameters
// If worker k has add delta to server j times when its i-th Get
// then the server will return the parameter after all K
// workers finished their j-th update
// TODO(feiga): to delete this, SyncServer is a special case for
// BackupWorkerSyncServer
//class SyncServer : public Server {
//public:
// SyncServer() : Server() {
// int num_worker = Zoo::Get()->num_workers();
// worker_get_clocks_.reset(new VectorClock(num_worker));
// worker_add_clocks_.reset(new VectorClock(num_worker));
// }
//
// // make some modification to suit to the sync server
// // please not use in other place, may different with the general vector clock
// class VectorClock {
// public:
// explicit VectorClock(int n) :
// local_clock_(n, 0), global_clock_(0), size_(0) {}
//
// // Return true when all clock reach a same number
// virtual bool Update(int i) {
// ++local_clock_[i];
// if (global_clock_ < *(std::min_element(std::begin(local_clock_),
// std::end(local_clock_)))) {
// ++global_clock_;
// if (global_clock_ == *(std::max_element(std::begin(local_clock_),
// std::end(local_clock_)))) {
// return true;
// }
// }
// return false;
// }
//
// std::string DebugString() {
// std::string os = "global ";
// os += std::to_string(global_clock_) + " local: ";
// for (auto i : local_clock_) os += std::to_string(i) + " ";
// return os;
// }
//
// int local_clock(int i) const { return local_clock_[i]; }
// int global_clock() const { return global_clock_; }
//
// protected:
// std::vector<int> local_clock_;
// int global_clock_;
// int size_;
// };
//protected:
// void ProcessAdd(MessagePtr& msg) override {
// // 1. Before add: cache faster worker
// int worker = Zoo::Get()->rank_to_worker_id(msg->src());
// if (worker_get_clocks_->local_clock(worker) >
// worker_get_clocks_->global_clock()) {
// msg_add_cache_.Push(msg);
// return;
// }
// // 2. Process Add
// Server::ProcessAdd(msg);
// // 3. After add: process cached process get if necessary
// if (worker_add_clocks_->Update(worker)) {
// CHECK(msg_add_cache_.Empty());
// while (!msg_get_cache_.Empty()) {
// MessagePtr get_msg;
// CHECK(msg_get_cache_.TryPop(get_msg));
// int get_worker = Zoo::Get()->rank_to_worker_id(get_msg->src());
// Server::ProcessGet(get_msg);
// worker_get_clocks_->Update(get_worker);
// }
// }
// }
//
// void ProcessGet(MessagePtr& msg) override {
// // 1. Before get: cache faster worker
// int worker = Zoo::Get()->rank_to_worker_id(msg->src());
// if (worker_add_clocks_->local_clock(worker) >
// worker_add_clocks_->global_clock()) {
// // Will wait for other worker finished Add
// msg_get_cache_.Push(msg);
// return;
// }
// // 2. Process Get
// Server::ProcessGet(msg);
// // 3. After get: process cached process add if necessary
// if (worker_get_clocks_->Update(worker)) {
// CHECK(msg_get_cache_.Empty());
// while (!msg_add_cache_.Empty()) {
// MessagePtr add_msg;
// CHECK(msg_add_cache_.TryPop(add_msg));
// int add_worker = Zoo::Get()->rank_to_worker_id(add_msg->src());
// Server::ProcessAdd(add_msg);
// worker_add_clocks_->Update(add_worker);
// }
// }
// }
//
//private:
// std::unique_ptr<VectorClock> worker_get_clocks_;
// std::unique_ptr<VectorClock> worker_add_clocks_;
//
// MtQueue<MessagePtr> msg_add_cache_;
// MtQueue<MessagePtr> msg_get_cache_;
//};
class WithBackupSyncServer : public Server {
public:
WithBackupSyncServer() : Server() {
num_worker_ = Zoo::Get()->num_workers();
double backup_ratio = (double)MV_CONFIG_backup_worker_ratio / 100;
num_sync_worker_ = num_worker_ -
static_cast<int>(backup_ratio * num_worker_);
CHECK(num_sync_worker_ > 0 && num_sync_worker_ <= num_worker_);
if (num_sync_worker_ == num_worker_) {
Log::Info("No backup worker, using the sync mode\n");
}
Log::Info("Sync with backup worker start: num_sync_worker = %d,"
"num_total_worker = %d\n", num_sync_worker_, num_worker_);
worker_get_clocks_.reset(new VectorClock(num_worker_));
worker_add_clocks_.reset(new VectorClock(
num_worker_, num_worker_ - num_sync_worker_));
}
// make some modification to suit to the sync server
// please not use in other place, may different with the general vector clock
class VectorClock {
public:
VectorClock(int num_worker, int num_backup_worker = 0) :
local_clock_(num_worker, 0), global_clock_(0), num_worker_(num_worker),
num_sync_worker_(num_worker - num_backup_worker), progress_(0) {}
// Return true when global clock meet the sync condition
// sync: all worker reach the same clock
// backup-worker-sync: sync-workers reach the same clock
virtual bool Update(int i) {
if (local_clock_[i]++ == global_clock_) {
++progress_;
}
if (progress_ >= num_sync_worker_) {
++global_clock_;
progress_ = 0;
for (auto i : local_clock_) {
if (i > global_clock_) ++progress_;
}
if (global_clock_ == *(std::max_element(std::begin(local_clock_),
std::end(local_clock_)))) {
return true;
}
}
return false;
}
std::string DebugString() {
std::string os = "global ";
os += std::to_string(global_clock_) + " local: ";
for (auto i : local_clock_) os += std::to_string(i) + " ";
return os;
}
int local_clock(int i) const { return local_clock_[i]; }
int global_clock() const { return global_clock_; }
protected:
std::vector<int> local_clock_;
int global_clock_;
int num_worker_;
int num_sync_worker_;
int progress_;
};
protected:
void ProcessAdd(MessagePtr& msg) override {
// 1. Before add: cache faster worker
int worker = Zoo::Get()->rank_to_worker_id(msg->src());
if (worker_get_clocks_->local_clock(worker) >
worker_get_clocks_->global_clock()) {
msg_add_cache_.Push(msg);
return;
}
// 2. Process Add
if (worker_add_clocks_->local_clock(worker) >=
worker_add_clocks_->global_clock()) {
Server::ProcessAdd(msg);
}
// 3. After add: process cached process get if necessary
if (worker_add_clocks_->Update(worker)) {
CHECK(msg_add_cache_.Empty());
while (!msg_get_cache_.Empty()) {
MessagePtr get_msg;
CHECK(msg_get_cache_.TryPop(get_msg));
int get_worker = Zoo::Get()->rank_to_worker_id(get_msg->src());
Server::ProcessGet(get_msg);
worker_get_clocks_->Update(get_worker);
}
}
}
void ProcessGet(MessagePtr& msg) override {
// 1. Before get: cache faster worker
int worker = Zoo::Get()->rank_to_worker_id(msg->src());
if (worker_add_clocks_->local_clock(worker) >
worker_add_clocks_->global_clock()) {
// Will wait for other worker finished Add
msg_get_cache_.Push(msg);
return;
}
// 2. Process Get
Server::ProcessGet(msg);
// 3. After get: process cached process add if necessary
if (worker_get_clocks_->Update(worker)) {
CHECK(msg_get_cache_.Empty());
while (!msg_add_cache_.Empty()) {
MessagePtr add_msg;
CHECK(msg_add_cache_.TryPop(add_msg));
int add_worker = Zoo::Get()->rank_to_worker_id(add_msg->src());
if (worker_add_clocks_->local_clock(add_worker) >=
worker_add_clocks_->global_clock()) {
Server::ProcessAdd(msg);
};
worker_add_clocks_->Update(add_worker);
}
}
}
private:
std::unique_ptr<VectorClock> worker_get_clocks_;
std::unique_ptr<VectorClock> worker_add_clocks_;
MtQueue<MessagePtr> msg_add_cache_;
MtQueue<MessagePtr> msg_get_cache_;
// num_worker_ - num_sync_worker_ = num_backup_worker_
int num_sync_worker_;
int num_worker_;
};
Server* Server::GetServer() {
if (!MV_CONFIG_sync) {
Log::Info("Create a async server\n");
return new Server();
}
// if (MV_CONFIG_backup_worker_ratio > 0.0) {
Log::Info("Create a sync server\n");
return new WithBackupSyncServer();
// }
}
} // namespace multiverso
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <set>
#include <thread>
#include "cpp_utils/assert.hpp"
#include "server.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "accounts.hpp"
#include "assets.hpp"
#include "config.hpp"
#include "objectives.hpp"
#include "wishes.hpp"
#include "fortune.hpp"
#include "recurring.hpp"
#include "debts.hpp"
#include "currency.hpp"
#include "share.hpp"
#include "http.hpp"
#include "api/server_api.hpp"
#include "pages/server_pages.hpp"
using namespace budget;
namespace {
bool server_running = false;
void start_server(){
httplib::Server server;
load_pages(server);
load_api(server);
std::string listen = "localhost";
size_t port = 8080;
if(config_contains("server_port")){
port = to_number<size_t>(config_value("server_port"));
}
if(config_contains("server_listen")){
listen = config_value("server_listen");
}
// Listen
server.listen(listen.c_str(), port);
}
void start_cron_loop(){
size_t hours = 0;
while(true){
using namespace std::chrono_literals;
std::this_thread::sleep_for(1h);
++hours;
check_for_recurrings();
// We save the cache once per day
if (hours % 24 == 0) {
save_currency_cache();
save_share_price_cache();
}
// Every four hours, we refresh the currency cache
// Only current day rates are refreshed
if (hours % 4 == 0) {
std::cout << "Refresh the currency cache" << std::endl;
budget::refresh_currency_cache();
}
}
}
} //end of anonymous namespace
void budget::set_server_running(){
// Indicates to the system that it's running in server mode
server_running = true;
}
void budget::server_module::load(){
load_accounts();
load_expenses();
load_earnings();
load_assets();
load_objectives();
load_wishes();
load_fortunes();
load_recurrings();
load_debts();
load_wishes();
}
void budget::server_module::handle(const std::vector<std::string>& args){
cpp_unused(args);
std::cout << "Starting the server" << std::endl;
std::thread server_thread([](){ start_server(); });
std::thread cron_thread([](){ start_cron_loop(); });
server_thread.join();
cron_thread.join();
}
bool budget::is_server_running(){
return server_running;
}
<commit_msg>Exit the server more gracefully<commit_after>//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <set>
#include <thread>
#include "cpp_utils/assert.hpp"
#include "server.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "accounts.hpp"
#include "assets.hpp"
#include "config.hpp"
#include "objectives.hpp"
#include "wishes.hpp"
#include "fortune.hpp"
#include "recurring.hpp"
#include "debts.hpp"
#include "currency.hpp"
#include "share.hpp"
#include "http.hpp"
#include "api/server_api.hpp"
#include "pages/server_pages.hpp"
using namespace budget;
namespace {
bool server_running = false;
httplib::Server * server_ptr = nullptr;
void signal_handler(int /*signum*/) {
// Save the caches
save_currency_cache();
save_share_price_cache();
save_config();
if (server_ptr) {
server_ptr->stop();
}
};
void start_server(){
httplib::Server server;
load_pages(server);
load_api(server);
struct sigaction action;
memset(&action, 0, sizeof(struct sigaction));
action.sa_handler = signal_handler;
sigaction(SIGTERM, &action, NULL);
std::string listen = "localhost";
size_t port = 8080;
if(config_contains("server_port")){
port = to_number<size_t>(config_value("server_port"));
}
if(config_contains("server_listen")){
listen = config_value("server_listen");
}
server_ptr = &server;
// Listen
server.listen(listen.c_str(), port);
}
void start_cron_loop(){
size_t hours = 0;
while(true){
using namespace std::chrono_literals;
std::this_thread::sleep_for(1h);
++hours;
check_for_recurrings();
// We save the cache once per day
if (hours % 24 == 0) {
save_currency_cache();
save_share_price_cache();
}
// Every four hours, we refresh the currency cache
// Only current day rates are refreshed
if (hours % 4 == 0) {
std::cout << "Refresh the currency cache" << std::endl;
budget::refresh_currency_cache();
}
}
}
} //end of anonymous namespace
void budget::set_server_running(){
// Indicates to the system that it's running in server mode
server_running = true;
}
void budget::server_module::load(){
load_accounts();
load_expenses();
load_earnings();
load_assets();
load_objectives();
load_wishes();
load_fortunes();
load_recurrings();
load_debts();
load_wishes();
}
void budget::server_module::handle(const std::vector<std::string>& args){
cpp_unused(args);
std::cout << "Starting the server" << std::endl;
std::thread server_thread([](){ start_server(); });
std::thread cron_thread([](){ start_cron_loop(); });
server_thread.join();
cron_thread.join();
}
bool budget::is_server_running(){
return server_running;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
Copyright (c) 2014, Jan Koester jan.koester@gmx.net
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 <organization> 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 <COPYRIGHT HOLDER> 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 "socket.h"
#ifndef Windows
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/fcntl.h>
#else
#include <Windows.h>
#endif
#include <sys/types.h>
#include <algorithm>
#include <config.h>
#include <errno.h>
using namespace libhttppp;
ClientSocket::ClientSocket(){
_Socket=0;
_SSL=0;
}
ClientSocket::~ClientSocket(){
shutdown(_Socket,
#ifndef Windows
SHUT_RDWR
#else
SD_BOTH
#endif
);
}
void ClientSocket::setnonblocking(){
#ifndef Windows
fcntl(_Socket, F_SETFL, O_NONBLOCK);
#else
u_long bmode=1;
ioctlsocket(_Socket,FIONBIO,&bmode);
#endif
}
#ifndef Windows
int ClientSocket::getSocket(){
#else
SOCKET ClientSocket::getSocket(){
#endif
return _Socket;
}
#ifndef Windows
ServerSocket::ServerSocket(const char* uxsocket,int maxconnections){
int optval = 1;
_Maxconnections=maxconnections;
_UXSocketAddr.sun_family = AF_UNIX;
try {
std::copy(uxsocket,uxsocket+strlen(uxsocket),_UXSocketAddr.sun_path);
}catch(...){
_httpexception.Cirtical("Can't create Server Socket");
throw _httpexception;
}
if ((_Socket = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0){
_httpexception.Cirtical("Can't create Server Socket");
throw _httpexception;
}
setsockopt(_Socket,SOL_SOCKET,SO_REUSEADDR,&optval, sizeof(optval));
if (bind(_Socket, (struct sockaddr *)&_UXSocketAddr, sizeof(struct sockaddr)) < 0){
_httpexception.Cirtical("Can't create Server Socket");
throw _httpexception;
}
}
#endif
ServerSocket::ServerSocket(const char* addr, int port,int maxconnections){
_Maxconnections=maxconnections;
_SockAddr.sin_family = AF_INET;
_SockAddr.sin_port = htons(port);
if(addr==NULL)
_SockAddr.sin_addr.s_addr = INADDR_ANY;
else
_SockAddr.sin_addr.s_addr = inet_addr(addr);
if ((_Socket = socket(AF_INET, SOCK_STREAM, 0)) < 0){
_httpexception.Cirtical("Can't create Server Socket");
throw _httpexception;
}
#ifndef Windows
int optval = 1;
setsockopt(_Socket,SOL_SOCKET,SO_REUSEADDR,&optval, sizeof(optval));
#else
BOOL bOptVal = TRUE;
int bOptLen = sizeof (BOOL);
setsockopt(_Socket,SOL_SOCKET,SO_REUSEADDR,(char *)&bOptVal, bOptLen);
#endif
if (bind(_Socket, (struct sockaddr *)&_SockAddr, sizeof(struct sockaddr)) < 0){
_httpexception.Cirtical("Can't create Server Socket");
throw _httpexception;
}
}
ServerSocket::~ServerSocket(){
}
void ServerSocket::setnonblocking(){
#ifndef Windows
fcntl(_Socket, F_SETFL, O_NONBLOCK);
#else
u_long bmode=1;
ioctlsocket(_Socket,FIONBIO,&bmode);
#endif
}
void ServerSocket::listenSocket(){
if(listen(_Socket, _Maxconnections) < 0){
_httpexception.Cirtical("Can't create Server Socket");
throw _httpexception;
}
}
#ifndef Windows
int ServerSocket::getSocket(){
return _Socket;
}
#else
SOCKET ServerSocket::getSocket(){
return _Socket;
}
#endif
int ServerSocket::getMaxconnections(){
return _Maxconnections;
}
#ifndef Windows
int ServerSocket::acceptEvent(ClientSocket *clientsocket){
#else
SOCKET ServerSocket::acceptEvent(ClientSocket *clientsocket){
#endif
clientsocket->_ClientAddrLen=sizeof(clientsocket);
#ifndef Windows
int socket = accept(_Socket,(struct sockaddr *)&clientsocket->_ClientAddr, &clientsocket->_ClientAddrLen);
#else
SOCKET socket = accept(_Socket,(struct sockaddr *)&clientsocket->_ClientAddr, &clientsocket->_ClientAddrLen);
#endif
if(socket==-1){
char errbuf[255];
strerror_r(errno,errbuf,255);
_httpexception.Error(errbuf);
}
clientsocket->_Socket=socket;
return socket;
}
ssize_t ServerSocket::sendData(ClientSocket* socket, void* data, size_t size){
return sendData(socket,data,size,0);
}
ssize_t ServerSocket::sendData(ClientSocket* socket, void* data, size_t size,int flags){
#ifndef Windows
ssize_t rval=sendto(socket->getSocket(),data, size,flags,&socket->_ClientAddr, socket->_ClientAddrLen);
#else
int rval=sendto(socket->getSocket(),(const char*) data, (int)size,flags,&socket->_ClientAddr, socket->_ClientAddrLen);
#endif
if(rval==-1){
#ifdef Linux
char errbuf[255];
_httpexception.Error(strerror_r(errno,errbuf,255));
#else
char errbuf[255];
strerror_r(errno,errbuf,255);
_httpexception.Error(errbuf);
#endif
if(errno != EAGAIN)
throw _httpexception;
}
return rval;
}
ssize_t ServerSocket::recvData(ClientSocket* socket, void* data, size_t size){
return recvData(socket,data,size,0);
}
ssize_t ServerSocket::recvData(ClientSocket* socket, void* data, size_t size,int flags){
#ifndef Windows
ssize_t recvsize=recvfrom(socket->getSocket(),data, size,flags,
&socket->_ClientAddr, &socket->_ClientAddrLen);
#else
ssize_t recvsize=recvfrom(socket->getSocket(), (char*)data,(int)size,flags,
&socket->_ClientAddr, &socket->_ClientAddrLen);
#endif
if(recvsize==-1){
#ifdef Linux
char errbuf[255];
_httpexception.Error(strerror_r(errno,errbuf,255));
#else
char errbuf[255];
strerror_r(errno,errbuf,255);
_httpexception.Error(errbuf);
#endif
throw _httpexception;
}
return recvsize;
}
<commit_msg>removed using namespace in socket,cpp<commit_after>/*******************************************************************************
Copyright (c) 2014, Jan Koester jan.koester@gmx.net
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 <organization> 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 <COPYRIGHT HOLDER> 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 "socket.h"
#ifndef Windows
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/fcntl.h>
#else
#include <Windows.h>
#endif
#include <sys/types.h>
#include <algorithm>
#include <config.h>
#include <errno.h>
libhttppp::ClientSocket::ClientSocket(){
_Socket=0;
_SSL=0;
}
libhttppp::ClientSocket::~ClientSocket(){
shutdown(_Socket,
#ifndef Windows
SHUT_RDWR
#else
SD_BOTH
#endif
);
}
void libhttppp::ClientSocket::setnonblocking(){
#ifndef Windows
fcntl(_Socket, F_SETFL, O_NONBLOCK);
#else
u_long bmode=1;
ioctlsocket(_Socket,FIONBIO,&bmode);
#endif
}
#ifndef Windows
int libhttppp::ClientSocket::getSocket(){
#else
SOCKET libhttppp::ClientSocket::getSocket(){
#endif
return _Socket;
}
#ifndef Windows
libhttppp::ServerSocket::ServerSocket(const char* uxsocket,int maxconnections){
int optval = 1;
_Maxconnections=maxconnections;
_UXSocketAddr.sun_family = AF_UNIX;
try {
std::copy(uxsocket,uxsocket+strlen(uxsocket),_UXSocketAddr.sun_path);
}catch(...){
_httpexception.Cirtical("Can't create Server Socket");
throw _httpexception;
}
if ((_Socket = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0){
_httpexception.Cirtical("Can't create Server Socket");
throw _httpexception;
}
setsockopt(_Socket,SOL_SOCKET,SO_REUSEADDR,&optval, sizeof(optval));
if (bind(_Socket, (struct sockaddr *)&_UXSocketAddr, sizeof(struct sockaddr)) < 0){
_httpexception.Cirtical("Can't create Server Socket");
throw _httpexception;
}
}
#endif
libhttppp::ServerSocket::ServerSocket(const char* addr, int port,int maxconnections){
_Maxconnections=maxconnections;
_SockAddr.sin_family = AF_INET;
_SockAddr.sin_port = htons(port);
if(addr==NULL)
_SockAddr.sin_addr.s_addr = INADDR_ANY;
else
_SockAddr.sin_addr.s_addr = inet_addr(addr);
if ((_Socket = socket(AF_INET, SOCK_STREAM, 0)) < 0){
_httpexception.Cirtical("Can't create Server Socket");
throw _httpexception;
}
#ifndef Windows
int optval = 1;
setsockopt(_Socket,SOL_SOCKET,SO_REUSEADDR,&optval, sizeof(optval));
#else
BOOL bOptVal = TRUE;
int bOptLen = sizeof (BOOL);
setsockopt(_Socket,SOL_SOCKET,SO_REUSEADDR,(char *)&bOptVal, bOptLen);
#endif
if (bind(_Socket, (struct sockaddr *)&_SockAddr, sizeof(struct sockaddr)) < 0){
_httpexception.Cirtical("Can't create Server Socket");
throw _httpexception;
}
}
libhttppp::ServerSocket::~ServerSocket(){
}
void libhttppp::ServerSocket::setnonblocking(){
#ifndef Windows
fcntl(_Socket, F_SETFL, O_NONBLOCK);
#else
u_long bmode=1;
ioctlsocket(_Socket,FIONBIO,&bmode);
#endif
}
void libhttppp::ServerSocket::listenSocket(){
if(listen(_Socket, _Maxconnections) < 0){
_httpexception.Cirtical("Can't create Server Socket");
throw _httpexception;
}
}
#ifndef Windows
int libhttppp::ServerSocket::getSocket(){
return _Socket;
}
#else
SOCKET libhttppp::ServerSocket::getSocket(){
return _Socket;
}
#endif
int libhttppp::ServerSocket::getMaxconnections(){
return _Maxconnections;
}
#ifndef Windows
int libhttppp::ServerSocket::acceptEvent(ClientSocket *clientsocket){
#else
SOCKET libhttppp::ServerSocket::acceptEvent(ClientSocket *clientsocket){
#endif
clientsocket->_ClientAddrLen=sizeof(clientsocket);
#ifndef Windows
int socket = accept(_Socket,(struct sockaddr *)&clientsocket->_ClientAddr, &clientsocket->_ClientAddrLen);
#else
SOCKET socket = accept(_Socket,(struct sockaddr *)&clientsocket->_ClientAddr, &clientsocket->_ClientAddrLen);
#endif
if(socket==-1){
char errbuf[255];
strerror_r(errno,errbuf,255);
_httpexception.Error(errbuf);
}
clientsocket->_Socket=socket;
return socket;
}
ssize_t libhttppp::ServerSocket::sendData(ClientSocket* socket, void* data, size_t size){
return sendData(socket,data,size,0);
}
ssize_t libhttppp::ServerSocket::sendData(ClientSocket* socket, void* data, size_t size,int flags){
#ifndef Windows
ssize_t rval=sendto(socket->getSocket(),data, size,flags,&socket->_ClientAddr, socket->_ClientAddrLen);
#else
int rval=sendto(socket->getSocket(),(const char*) data, (int)size,flags,&socket->_ClientAddr, socket->_ClientAddrLen);
#endif
if(rval==-1){
#ifdef Linux
char errbuf[255];
_httpexception.Error(strerror_r(errno,errbuf,255));
#else
char errbuf[255];
strerror_r(errno,errbuf,255);
_httpexception.Error(errbuf);
#endif
if(errno != EAGAIN)
throw _httpexception;
}
return rval;
}
ssize_t libhttppp::ServerSocket::recvData(ClientSocket* socket, void* data, size_t size){
return recvData(socket,data,size,0);
}
ssize_t libhttppp::ServerSocket::recvData(ClientSocket* socket, void* data, size_t size,int flags){
#ifndef Windows
ssize_t recvsize=recvfrom(socket->getSocket(),data, size,flags,
&socket->_ClientAddr, &socket->_ClientAddrLen);
#else
ssize_t recvsize=recvfrom(socket->getSocket(), (char*)data,(int)size,flags,
&socket->_ClientAddr, &socket->_ClientAddrLen);
#endif
if(recvsize==-1){
#ifdef Linux
char errbuf[255];
_httpexception.Error(strerror_r(errno,errbuf,255));
#else
char errbuf[255];
strerror_r(errno,errbuf,255);
_httpexception.Error(errbuf);
#endif
throw _httpexception;
}
return recvsize;
}
<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Devices/TrackIR/TrackIRScaffold.h"
#include <algorithm>
#include <list>
#include <memory>
#include <boost/thread/locks.hpp>
#include <boost/thread/mutex.hpp>
#include <linuxtrack.h>
#include "SurgSim/Devices/TrackIR/TrackIRDevice.h"
#include "SurgSim/Devices/TrackIR/TrackIRThread.h"
#include "SurgSim/Framework/Assert.h"
#include "SurgSim/Framework/Log.h"
#include "SurgSim/Framework/SharedInstance.h"
#include "SurgSim/DataStructures/DataGroup.h"
#include "SurgSim/DataStructures/DataGroupBuilder.h"
#include "SurgSim/Math/Matrix.h"
#include "SurgSim/Math/RigidTransform.h"
#include "SurgSim/Math/Vector.h"
using SurgSim::DataStructures::DataGroupBuilder;
using SurgSim::Math::makeRotationMatrix;
using SurgSim::Math::Matrix33d;
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::Vector3d;
namespace SurgSim
{
namespace Device
{
struct TrackIRScaffold::DeviceData
{
/// Constructor
/// \param device Device to be wrapped
explicit DeviceData(TrackIRDevice* device) :
deviceObject(device),
thread(),
positionScale(TrackIRDevice::defaultPositionScale()),
orientationScale(TrackIRDevice::defaultOrientationScale())
{
}
/// The corresponding device object.
SurgSim::Device::TrackIRDevice* const deviceObject;
/// Processing thread.
std::unique_ptr<SurgSim::Device::TrackIRThread> thread;
/// Scale factor for the position axes; stored locally before the device is initialized.
double positionScale;
/// Scale factor for the orientation axes; stored locally before the device is initialized.
double orientationScale;
/// The mutex that protects the externally modifiable parameters.
boost::mutex parametersMutex;
private:
// Prevent copy construction and copy assignment. (VS2012 does not support "= delete" yet.)
DeviceData(const DeviceData&) /*= delete*/;
DeviceData& operator=(const DeviceData&) /*= delete*/;
};
struct TrackIRScaffold::StateData
{
public:
/// Initialize the state.
StateData() : isApiInitialized(false)
{
}
/// True if the API has been initialized (and not finalized).
bool isApiInitialized;
/// The list of known devices.
std::list<std::unique_ptr<TrackIRScaffold::DeviceData>> activeDeviceList;
/// The mutex that protects the list of known devices.
boost::mutex mutex;
private:
// Prevent copy construction and copy assignment. (VS2012 does not support "= delete" yet.)
StateData(const StateData&) /*= delete*/;
StateData& operator=(const StateData&) /*= delete*/;
};
TrackIRScaffold::TrackIRScaffold(std::shared_ptr<SurgSim::Framework::Logger> logger) :
m_logger(logger),
m_state(new StateData)
{
if (!m_logger)
{
m_logger = SurgSim::Framework::Logger::getLogger("TrackIR device");
m_logger->setThreshold(m_defaultLogLevel);
}
SURGSIM_LOG_DEBUG(m_logger) << "TrackIR: Shared scaffold created.";
}
TrackIRScaffold::~TrackIRScaffold()
{
// The following block controls the duration of the mutex being locked.
{
boost::lock_guard<boost::mutex> lock(m_state->mutex);
if (!m_state->activeDeviceList.empty())
{
SURGSIM_LOG_SEVERE(m_logger) << "TrackIR: Destroying scaffold while devices are active!?!";
for (auto it = std::begin(m_state->activeDeviceList); it != std::end(m_state->activeDeviceList); ++it)
{
stopCamera((*it).get());
if ((*it)->thread)
{
destroyPerDeviceThread(it->get());
}
}
m_state->activeDeviceList.clear();
}
if (m_state->isApiInitialized)
{
if (!finalizeSdk())
{
SURGSIM_LOG_SEVERE(m_logger) << "Finalizing TrackIR SDK failed.";
}
}
}
SURGSIM_LOG_DEBUG(m_logger) << "TrackIR: Shared scaffold destroyed.";
}
std::shared_ptr<SurgSim::Framework::Logger> TrackIRScaffold::getLogger() const
{
return m_logger;
}
bool TrackIRScaffold::registerDevice(TrackIRDevice* device)
{
boost::lock_guard<boost::mutex> lock(m_state->mutex);
if (!m_state->isApiInitialized)
{
if (!initializeSdk())
{
SURGSIM_LOG_SEVERE(m_logger) << "Failed to initialize TrackIR SDK in TrackIRScaffold::registerDevice(). "
<< "Continuing without the TrackIR device.";
}
}
// Only proceed when initializationSdk() is successful.
if (m_state->isApiInitialized)
{
// Make sure the object is unique.
auto sameObject = std::find_if(m_state->activeDeviceList.cbegin(), m_state->activeDeviceList.cend(),
[device](const std::unique_ptr<DeviceData>& info) { return info->deviceObject == device; });
SURGSIM_ASSERT(sameObject == m_state->activeDeviceList.end()) << "TrackIR: Tried to register a device" <<
" which is already registered!";
// Make sure the name is unique.
const std::string name = device->getName();
auto sameName = std::find_if(m_state->activeDeviceList.cbegin(), m_state->activeDeviceList.cend(),
[&name](const std::unique_ptr<DeviceData>& info) { return info->deviceObject->getName() == name; });
SURGSIM_ASSERT(sameName == m_state->activeDeviceList.end()) << "TrackIR: Tried to register a device" <<
" when the same name is already present!";
// The handling of multiple cameras could be done in different ways, each with trade-offs.
// Instead of choosing an approach now, we assert on attempting to use more than one camera.
SURGSIM_ASSERT(m_state->activeDeviceList.size() < 1) << "There is already an active TrackIR camera."
<< " TrackIRScaffold only supports one TrackIR camera right now.";
std::unique_ptr<DeviceData> info(new DeviceData(device));
createPerDeviceThread(info.get());
SURGSIM_ASSERT(info->thread) << "Failed to create a per-device thread for TrackIR device: " <<
info->deviceObject->getName();
startCamera(info.get());
m_state->activeDeviceList.emplace_back(std::move(info));
}
return m_state->isApiInitialized;
}
bool TrackIRScaffold::unregisterDevice(const TrackIRDevice* const device)
{
bool found = false;
{
boost::lock_guard<boost::mutex> lock(m_state->mutex);
auto matching = std::find_if(m_state->activeDeviceList.begin(), m_state->activeDeviceList.end(),
[device](const std::unique_ptr<DeviceData>& info) { return info->deviceObject == device; });
if (matching != m_state->activeDeviceList.end())
{
stopCamera((*matching).get());
if ((*matching)->thread)
{
destroyPerDeviceThread(matching->get());
}
m_state->activeDeviceList.erase(matching);
// the iterator is now invalid but that's OK
found = true;
}
}
if (!found)
{
SURGSIM_LOG_WARNING(m_logger) << "TrackIR: Attempted to release a non-registered device.";
}
return found;
}
void TrackIRScaffold::setPositionScale(const TrackIRDevice* device, double scale)
{
boost::lock_guard<boost::mutex> lock(m_state->mutex);
auto matching = std::find_if(m_state->activeDeviceList.begin(), m_state->activeDeviceList.end(),
[device](const std::unique_ptr<DeviceData>& info) { return info->deviceObject == device; });
if (matching != m_state->activeDeviceList.end())
{
boost::lock_guard<boost::mutex> lock((*matching)->parametersMutex);
(*matching)->positionScale = scale;
}
}
void TrackIRScaffold::setOrientationScale(const TrackIRDevice* device, double scale)
{
boost::lock_guard<boost::mutex> lock(m_state->mutex);
auto matching = std::find_if(m_state->activeDeviceList.begin(), m_state->activeDeviceList.end(),
[device](const std::unique_ptr<DeviceData>& info) { return info->deviceObject == device; });
if (matching != m_state->activeDeviceList.end())
{
boost::lock_guard<boost::mutex> lock((*matching)->parametersMutex);
(*matching)->orientationScale = scale;
}
}
bool TrackIRScaffold::runInputFrame(TrackIRScaffold::DeviceData* info)
{
if (!updateDevice(info))
{
return false;
}
info->deviceObject->pushInput();
return true;
}
bool TrackIRScaffold::updateDevice(TrackIRScaffold::DeviceData* info)
{
SurgSim::DataStructures::DataGroup& inputData = info->deviceObject->getInputData();
boost::lock_guard<boost::mutex> lock(info->parametersMutex);
float x = 0.0, y = 0.0, z = 0.0, yaw = 0.0, pitch = 0.0, roll = 0.0;
unsigned counter = 0; // Current camera frame number
// roll: rotation around X-axis
// yaw: rotation around Y-axis
// pitch: rotation around Z-axis
// Positions are reported in millimeters.
// Angles are in radians.
ltr_get_pose(&yaw, &pitch, &roll, &x, &y, &z, &counter);
Vector3d position(static_cast<double>(x) / 1000.0,
static_cast<double>(y) / 1000.0,
static_cast<double>(z) / 1000.0); // Convert millimeter to meter
// Scale Position
position *= info->positionScale;
Matrix33d rotationX = makeRotationMatrix(static_cast<double>(-roll), Vector3d(Vector3d::UnitX()));
Matrix33d rotationY = makeRotationMatrix(static_cast<double>(yaw), Vector3d(Vector3d::UnitY()));
Matrix33d rotationZ = makeRotationMatrix(static_cast<double>(pitch), Vector3d(Vector3d::UnitZ()));
// Rotation order is extrinsic XYZ
Matrix33d orientation = rotationZ * rotationY * rotationX;
// Scale Orientation
orientation *= info->orientationScale;
RigidTransform3d pose;
pose.linear() = orientation;
pose.translation() = position;
inputData.poses().set("pose", pose);
return true;
}
bool TrackIRScaffold::initializeSdk()
{
SURGSIM_ASSERT(!m_state->isApiInitialized) << "TrackIR API already initialized.";
//Initialize the tracking using Default profile
ltr_init(NULL);
//Wait for TrackIR initialization
ltr_state_type state;
int timeout = 100; // Wait for 10 seconds before quit
while(timeout > 0)
{
state = ltr_get_tracking_state();
if(state != RUNNING)
{
usleep(100000); //sleep 0.1s
}
else
{
m_state->isApiInitialized = true;
break;
}
--timeout;
};
return m_state->isApiInitialized;
}
bool TrackIRScaffold::finalizeSdk()
{
SURGSIM_ASSERT(m_state->isApiInitialized) << "TrackIR API already finalized.";
ltr_shutdown();
ltr_state_type state;
state = ltr_get_tracking_state();
if (state == STOPPED)
{
m_state->isApiInitialized = false;
}
return !m_state->isApiInitialized;
}
bool TrackIRScaffold::createPerDeviceThread(DeviceData* deviceData)
{
SURGSIM_ASSERT(!deviceData->thread) << "Device " << deviceData->deviceObject->getName() << " already has a thread.";
std::unique_ptr<TrackIRThread> thread(new TrackIRThread(this, deviceData));
thread->start();
deviceData->thread = std::move(thread);
return true;
}
bool TrackIRScaffold::destroyPerDeviceThread(DeviceData* deviceData)
{
SURGSIM_ASSERT(deviceData->thread) << "No thread attached to device " << deviceData->deviceObject->getName();
std::unique_ptr<TrackIRThread> thread = std::move(deviceData->thread);
thread->stop();
thread.reset();
return true;
}
bool TrackIRScaffold::startCamera(DeviceData* info)
{
return true;
}
bool TrackIRScaffold::stopCamera(DeviceData* info)
{
return true;
}
SurgSim::DataStructures::DataGroup TrackIRScaffold::buildDeviceInputData()
{
DataGroupBuilder builder;
builder.addPose("pose");
return builder.createData();
}
std::shared_ptr<TrackIRScaffold> TrackIRScaffold::getOrCreateSharedInstance()
{
static SurgSim::Framework::SharedInstance<TrackIRScaffold> sharedInstance;
return sharedInstance.get();
}
void TrackIRScaffold::setDefaultLogLevel(SurgSim::Framework::LogLevel logLevel)
{
m_defaultLogLevel = logLevel;
}
SurgSim::Framework::LogLevel TrackIRScaffold::m_defaultLogLevel = SurgSim::Framework::LOG_LEVEL_INFO;
}; // namespace Device
}; // namespace SurgSim
<commit_msg>Revise the way rotation matrix is calculated for linux TrackIRScaffold.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Devices/TrackIR/TrackIRScaffold.h"
#include <algorithm>
#include <list>
#include <memory>
#include <boost/thread/locks.hpp>
#include <boost/thread/mutex.hpp>
#include <linuxtrack.h>
#include "SurgSim/Devices/TrackIR/TrackIRDevice.h"
#include "SurgSim/Devices/TrackIR/TrackIRThread.h"
#include "SurgSim/Framework/Assert.h"
#include "SurgSim/Framework/Log.h"
#include "SurgSim/Framework/SharedInstance.h"
#include "SurgSim/DataStructures/DataGroup.h"
#include "SurgSim/DataStructures/DataGroupBuilder.h"
#include "SurgSim/Math/Matrix.h"
#include "SurgSim/Math/RigidTransform.h"
#include "SurgSim/Math/Vector.h"
using SurgSim::DataStructures::DataGroupBuilder;
using SurgSim::Math::makeRotationMatrix;
using SurgSim::Math::Matrix33d;
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::Vector3d;
namespace SurgSim
{
namespace Device
{
struct TrackIRScaffold::DeviceData
{
/// Constructor
/// \param device Device to be wrapped
explicit DeviceData(TrackIRDevice* device) :
deviceObject(device),
thread(),
positionScale(TrackIRDevice::defaultPositionScale()),
orientationScale(TrackIRDevice::defaultOrientationScale())
{
}
/// The corresponding device object.
SurgSim::Device::TrackIRDevice* const deviceObject;
/// Processing thread.
std::unique_ptr<SurgSim::Device::TrackIRThread> thread;
/// Scale factor for the position axes; stored locally before the device is initialized.
double positionScale;
/// Scale factor for the orientation axes; stored locally before the device is initialized.
double orientationScale;
/// The mutex that protects the externally modifiable parameters.
boost::mutex parametersMutex;
private:
// Prevent copy construction and copy assignment. (VS2012 does not support "= delete" yet.)
DeviceData(const DeviceData&) /*= delete*/;
DeviceData& operator=(const DeviceData&) /*= delete*/;
};
struct TrackIRScaffold::StateData
{
public:
/// Initialize the state.
StateData() : isApiInitialized(false)
{
}
/// True if the API has been initialized (and not finalized).
bool isApiInitialized;
/// The list of known devices.
std::list<std::unique_ptr<TrackIRScaffold::DeviceData>> activeDeviceList;
/// The mutex that protects the list of known devices.
boost::mutex mutex;
private:
// Prevent copy construction and copy assignment. (VS2012 does not support "= delete" yet.)
StateData(const StateData&) /*= delete*/;
StateData& operator=(const StateData&) /*= delete*/;
};
TrackIRScaffold::TrackIRScaffold(std::shared_ptr<SurgSim::Framework::Logger> logger) :
m_logger(logger),
m_state(new StateData)
{
if (!m_logger)
{
m_logger = SurgSim::Framework::Logger::getLogger("TrackIR device");
m_logger->setThreshold(m_defaultLogLevel);
}
SURGSIM_LOG_DEBUG(m_logger) << "TrackIR: Shared scaffold created.";
}
TrackIRScaffold::~TrackIRScaffold()
{
// The following block controls the duration of the mutex being locked.
{
boost::lock_guard<boost::mutex> lock(m_state->mutex);
if (!m_state->activeDeviceList.empty())
{
SURGSIM_LOG_SEVERE(m_logger) << "TrackIR: Destroying scaffold while devices are active!?!";
for (auto it = std::begin(m_state->activeDeviceList); it != std::end(m_state->activeDeviceList); ++it)
{
stopCamera((*it).get());
if ((*it)->thread)
{
destroyPerDeviceThread(it->get());
}
}
m_state->activeDeviceList.clear();
}
if (m_state->isApiInitialized)
{
if (!finalizeSdk())
{
SURGSIM_LOG_SEVERE(m_logger) << "Finalizing TrackIR SDK failed.";
}
}
}
SURGSIM_LOG_DEBUG(m_logger) << "TrackIR: Shared scaffold destroyed.";
}
std::shared_ptr<SurgSim::Framework::Logger> TrackIRScaffold::getLogger() const
{
return m_logger;
}
bool TrackIRScaffold::registerDevice(TrackIRDevice* device)
{
boost::lock_guard<boost::mutex> lock(m_state->mutex);
if (!m_state->isApiInitialized)
{
if (!initializeSdk())
{
SURGSIM_LOG_SEVERE(m_logger) << "Failed to initialize TrackIR SDK in TrackIRScaffold::registerDevice(). "
<< "Continuing without the TrackIR device.";
}
}
// Only proceed when initializationSdk() is successful.
if (m_state->isApiInitialized)
{
// Make sure the object is unique.
auto sameObject = std::find_if(m_state->activeDeviceList.cbegin(), m_state->activeDeviceList.cend(),
[device](const std::unique_ptr<DeviceData>& info) { return info->deviceObject == device; });
SURGSIM_ASSERT(sameObject == m_state->activeDeviceList.end()) << "TrackIR: Tried to register a device" <<
" which is already registered!";
// Make sure the name is unique.
const std::string name = device->getName();
auto sameName = std::find_if(m_state->activeDeviceList.cbegin(), m_state->activeDeviceList.cend(),
[&name](const std::unique_ptr<DeviceData>& info) { return info->deviceObject->getName() == name; });
SURGSIM_ASSERT(sameName == m_state->activeDeviceList.end()) << "TrackIR: Tried to register a device" <<
" when the same name is already present!";
// The handling of multiple cameras could be done in different ways, each with trade-offs.
// Instead of choosing an approach now, we assert on attempting to use more than one camera.
SURGSIM_ASSERT(m_state->activeDeviceList.size() < 1) << "There is already an active TrackIR camera."
<< " TrackIRScaffold only supports one TrackIR camera right now.";
std::unique_ptr<DeviceData> info(new DeviceData(device));
createPerDeviceThread(info.get());
SURGSIM_ASSERT(info->thread) << "Failed to create a per-device thread for TrackIR device: " <<
info->deviceObject->getName();
startCamera(info.get());
m_state->activeDeviceList.emplace_back(std::move(info));
}
return m_state->isApiInitialized;
}
bool TrackIRScaffold::unregisterDevice(const TrackIRDevice* const device)
{
bool found = false;
{
boost::lock_guard<boost::mutex> lock(m_state->mutex);
auto matching = std::find_if(m_state->activeDeviceList.begin(), m_state->activeDeviceList.end(),
[device](const std::unique_ptr<DeviceData>& info) { return info->deviceObject == device; });
if (matching != m_state->activeDeviceList.end())
{
stopCamera((*matching).get());
if ((*matching)->thread)
{
destroyPerDeviceThread(matching->get());
}
m_state->activeDeviceList.erase(matching);
// the iterator is now invalid but that's OK
found = true;
}
}
if (!found)
{
SURGSIM_LOG_WARNING(m_logger) << "TrackIR: Attempted to release a non-registered device.";
}
return found;
}
void TrackIRScaffold::setPositionScale(const TrackIRDevice* device, double scale)
{
boost::lock_guard<boost::mutex> lock(m_state->mutex);
auto matching = std::find_if(m_state->activeDeviceList.begin(), m_state->activeDeviceList.end(),
[device](const std::unique_ptr<DeviceData>& info) { return info->deviceObject == device; });
if (matching != m_state->activeDeviceList.end())
{
boost::lock_guard<boost::mutex> lock((*matching)->parametersMutex);
(*matching)->positionScale = scale;
}
}
void TrackIRScaffold::setOrientationScale(const TrackIRDevice* device, double scale)
{
boost::lock_guard<boost::mutex> lock(m_state->mutex);
auto matching = std::find_if(m_state->activeDeviceList.begin(), m_state->activeDeviceList.end(),
[device](const std::unique_ptr<DeviceData>& info) { return info->deviceObject == device; });
if (matching != m_state->activeDeviceList.end())
{
boost::lock_guard<boost::mutex> lock((*matching)->parametersMutex);
(*matching)->orientationScale = scale;
}
}
bool TrackIRScaffold::runInputFrame(TrackIRScaffold::DeviceData* info)
{
if (!updateDevice(info))
{
return false;
}
info->deviceObject->pushInput();
return true;
}
bool TrackIRScaffold::updateDevice(TrackIRScaffold::DeviceData* info)
{
SurgSim::DataStructures::DataGroup& inputData = info->deviceObject->getInputData();
boost::lock_guard<boost::mutex> lock(info->parametersMutex);
float x = 0.0, y = 0.0, z = 0.0, yaw = 0.0, pitch = 0.0, roll = 0.0;
unsigned counter = 0; // Current camera frame number
// roll: rotation around X-axis
// yaw: rotation around Y-axis
// pitch: rotation around Z-axis
// Positions are reported in millimeters.
// Angles are in radians.
ltr_get_pose(&yaw, &pitch, &roll, &x, &y, &z, &counter);
Vector3d position(static_cast<double>(x) / 1000.0,
static_cast<double>(y) / 1000.0,
static_cast<double>(z) / 1000.0); // Convert millimeter to meter
// Scale Position
position *= info->positionScale;
Matrix33d rotationX = makeRotationMatrix(static_cast<double>(-roll), Vector3d(Vector3d::UnitX()));
Matrix33d rotationY = makeRotationMatrix(static_cast<double>(yaw), Vector3d(Vector3d::UnitY()));
Matrix33d rotationZ = makeRotationMatrix(static_cast<double>(pitch), Vector3d(Vector3d::UnitZ()));
// Rotation order is intrinsic/local XYZ
Matrix33d orientation = rotationX * rotationY * rotationZ;
// Scale Orientation
orientation *= info->orientationScale;
RigidTransform3d pose;
pose.linear() = orientation;
pose.translation() = position;
inputData.poses().set("pose", pose);
return true;
}
bool TrackIRScaffold::initializeSdk()
{
SURGSIM_ASSERT(!m_state->isApiInitialized) << "TrackIR API already initialized.";
//Initialize the tracking using Default profile
ltr_init(NULL);
//Wait for TrackIR initialization
ltr_state_type state;
int timeout = 100; // Wait for 10 seconds before quit
while(timeout > 0)
{
state = ltr_get_tracking_state();
if(state != RUNNING)
{
usleep(100000); //sleep 0.1s
}
else
{
m_state->isApiInitialized = true;
break;
}
--timeout;
};
return m_state->isApiInitialized;
}
bool TrackIRScaffold::finalizeSdk()
{
SURGSIM_ASSERT(m_state->isApiInitialized) << "TrackIR API already finalized.";
ltr_shutdown();
ltr_state_type state;
state = ltr_get_tracking_state();
if (state == STOPPED)
{
m_state->isApiInitialized = false;
}
return !m_state->isApiInitialized;
}
bool TrackIRScaffold::createPerDeviceThread(DeviceData* deviceData)
{
SURGSIM_ASSERT(!deviceData->thread) << "Device " << deviceData->deviceObject->getName() << " already has a thread.";
std::unique_ptr<TrackIRThread> thread(new TrackIRThread(this, deviceData));
thread->start();
deviceData->thread = std::move(thread);
return true;
}
bool TrackIRScaffold::destroyPerDeviceThread(DeviceData* deviceData)
{
SURGSIM_ASSERT(deviceData->thread) << "No thread attached to device " << deviceData->deviceObject->getName();
std::unique_ptr<TrackIRThread> thread = std::move(deviceData->thread);
thread->stop();
thread.reset();
return true;
}
bool TrackIRScaffold::startCamera(DeviceData* info)
{
return true;
}
bool TrackIRScaffold::stopCamera(DeviceData* info)
{
return true;
}
SurgSim::DataStructures::DataGroup TrackIRScaffold::buildDeviceInputData()
{
DataGroupBuilder builder;
builder.addPose("pose");
return builder.createData();
}
std::shared_ptr<TrackIRScaffold> TrackIRScaffold::getOrCreateSharedInstance()
{
static SurgSim::Framework::SharedInstance<TrackIRScaffold> sharedInstance;
return sharedInstance.get();
}
void TrackIRScaffold::setDefaultLogLevel(SurgSim::Framework::LogLevel logLevel)
{
m_defaultLogLevel = logLevel;
}
SurgSim::Framework::LogLevel TrackIRScaffold::m_defaultLogLevel = SurgSim::Framework::LOG_LEVEL_INFO;
}; // namespace Device
}; // namespace SurgSim
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "ObjectPoolTest.h"
#include "ObjectPool.h"
#include "TestFixtures/SimpleThreaded.h"
class PooledObject {
};
TEST_F(ObjectPoolTest, VerifyOutstandingLimit) {
ObjectPool<PooledObject> pool(2);
std::shared_ptr<PooledObject> obj1, obj2, obj3;
// Try to grab some objects out of the pool:
pool(obj1);
pool(obj2);
// Verify that grabbing a third object fails:
pool(obj3);
EXPECT_TRUE(obj3 == nullptr) << "Object pool issued more objects than it was authorized to issue";
}
TEST_F(ObjectPoolTest, DISABLED_VerifyAsynchronousUsage) {
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
AutoRequired<SimpleThreadedT<PooledObject>> obj;
AutoFired<SharedPtrReceiver<PooledObject>> spr;
ObjectPool<PooledObject> pool(3);
{
// Obtain the pool limit in objects:
std::shared_ptr<PooledObject> obj1, obj2, obj3;
pool(obj1);
pool(obj2);
pool(obj3);
// Block--verify that we _do not_ get any of those objects back while they are
// still outstanding.
{
auto obj4 = pool.WaitFor(boost::chrono::milliseconds(1));
EXPECT_TRUE(obj4 == nullptr) << "Pool issued another element even though it should have hit its outstanding limit";
}
// Now we kick off threads:
AutoCurrentContext()->Initiate();
// Fire off a few events:
spr(&SharedPtrReceiver<PooledObject>::OnEvent)(obj1);
spr(&SharedPtrReceiver<PooledObject>::OnEvent)(obj2);
spr(&SharedPtrReceiver<PooledObject>::OnEvent)(obj3);
}
// This should return more or less right away as objects become available:
{
auto obj4 = pool.WaitFor(boost::chrono::milliseconds(1));
EXPECT_TRUE(obj4 != nullptr) << "Object pool failed to be notified that it received a new element";
}
// Cause the thread to quit:
*obj += [&obj] { obj->Stop(); };
obj->Wait();
}
TEST_F(ObjectPoolTest, VerifyOutOfOrderDestruction) {
std::shared_ptr<int> ptr;
{
ObjectPool<int> pool;
pool(ptr);
}
// Verify that returning a shared pointer after the pool is gone does not result in an exception
ASSERT_NO_THROW(ptr.reset()) << "Attempting to release a shared pointer on a destroyed pool caused an unexpected exception";
}
<commit_msg>Lengthened wait time in ObjectPoolTest.VerifyAsynchronousUsage #9403<commit_after>#include "stdafx.h"
#include "ObjectPoolTest.h"
#include "ObjectPool.h"
#include "TestFixtures/SimpleThreaded.h"
class PooledObject {
};
TEST_F(ObjectPoolTest, VerifyOutstandingLimit) {
ObjectPool<PooledObject> pool(2);
std::shared_ptr<PooledObject> obj1, obj2, obj3;
// Try to grab some objects out of the pool:
pool(obj1);
pool(obj2);
// Verify that grabbing a third object fails:
pool(obj3);
EXPECT_TRUE(obj3 == nullptr) << "Object pool issued more objects than it was authorized to issue";
}
TEST_F(ObjectPoolTest, VerifyAsynchronousUsage) {
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
AutoRequired<SimpleThreadedT<PooledObject>> obj;
AutoFired<SharedPtrReceiver<PooledObject>> spr;
ObjectPool<PooledObject> pool(3);
{
// Obtain the pool limit in objects:
std::shared_ptr<PooledObject> obj1, obj2, obj3;
pool(obj1);
pool(obj2);
pool(obj3);
// Block--verify that we _do not_ get any of those objects back while they are
// still outstanding.
{
auto obj4 = pool.WaitFor(boost::chrono::milliseconds(1));
EXPECT_TRUE(obj4 == nullptr) << "Pool issued another element even though it should have hit its outstanding limit";
}
// Now we kick off threads:
AutoCurrentContext()->Initiate();
// Fire off a few events:
spr(&SharedPtrReceiver<PooledObject>::OnEvent)(obj1);
spr(&SharedPtrReceiver<PooledObject>::OnEvent)(obj2);
spr(&SharedPtrReceiver<PooledObject>::OnEvent)(obj3);
}
// This should return more or less right away as objects become available:
{
auto obj4 = pool.WaitFor(boost::chrono::milliseconds(10));
EXPECT_TRUE(obj4 != nullptr) << "Object pool failed to be notified that it received a new element";
}
// Cause the thread to quit:
*obj += [&obj] { obj->Stop(); };
obj->Wait();
}
TEST_F(ObjectPoolTest, VerifyOutOfOrderDestruction) {
std::shared_ptr<int> ptr;
{
ObjectPool<int> pool;
pool(ptr);
}
// Verify that returning a shared pointer after the pool is gone does not result in an exception
ASSERT_NO_THROW(ptr.reset()) << "Attempting to release a shared pointer on a destroyed pool caused an unexpected exception";
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkDisplayInteractor.h"
#include <mitkOperationActor.h>
#include <mitkEventMapper.h>
#include <mitkGlobalInteraction.h>
#include <mitkCoordinateSupplier.h>
#include <mitkDisplayCoordinateOperation.h>
#include <mitkDisplayVectorInteractor.h>
#include <mitkBaseRenderer.h>
#include <mitkRenderingManager.h>
#include <mitkInteractionConst.h>
mitk::DisplayInteractor::DisplayInteractor(mitk::BaseRenderer * ren)
{
m_ParentRenderer = ren;
}
void mitk::DisplayInteractor::ExecuteOperation(mitk::Operation * operation)
{
bool ok;//as return type
mitk::DisplayCoordinateOperation* dcOperation=dynamic_cast<mitk::DisplayCoordinateOperation*>(operation);
if ( dcOperation != NULL )
{
/****ZOOM & MOVE of the whole volume****/
mitk::BaseRenderer* renderer = dcOperation->GetRenderer();
if( renderer == NULL || (m_ParentRenderer != NULL && m_ParentRenderer != renderer))
return;
switch (operation->GetOperationType())
{
case OpMOVE :
{
renderer->GetDisplayGeometry()->MoveBy(dcOperation->GetLastToCurrentDisplayVector()*(-1.0));
mitk::RenderingManager::GetInstance()->RequestUpdate(renderer->GetRenderWindow());
ok = true;
}
break;
case OpZOOM :
{
float distance = dcOperation->GetLastToCurrentDisplayVector()[1];
//float factor= 1.0 + distance * 0.05; // stupid because factors from +1 and -1 dont give results that represent inverse zooms
float factor = 1.0;
if (distance < 0.0)
{
factor = 1.0 / 1.05;
}
else if (distance > 0.0)
{
factor = 1.0 * 1.05; // 5%
}
else // distance == 0.0
{
// nothing to do, factor remains 1.0
}
//renderer->GetDisplayGeometry()->Zoom(factor, dcOperation->GetStartDisplayCoordinate());
Point2D center;
center[0] = renderer->GetDisplayGeometry()->GetDisplayWidth()/2;
center[1] = renderer->GetDisplayGeometry()->GetDisplayHeight()/2;
renderer->GetDisplayGeometry()->Zoom(factor, center);
mitk::RenderingManager::GetInstance()->RequestUpdate(renderer->GetRenderWindow());
ok = true;
}
break;
default:
;
}
}
}
<commit_msg>FIX (#4039): zooming to mouse-curser instead of center of viewport<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkDisplayInteractor.h"
#include <mitkOperationActor.h>
#include <mitkEventMapper.h>
#include <mitkGlobalInteraction.h>
#include <mitkCoordinateSupplier.h>
#include <mitkDisplayCoordinateOperation.h>
#include <mitkDisplayVectorInteractor.h>
#include <mitkBaseRenderer.h>
#include <mitkRenderingManager.h>
#include <mitkInteractionConst.h>
mitk::DisplayInteractor::DisplayInteractor(mitk::BaseRenderer * ren)
{
m_ParentRenderer = ren;
}
void mitk::DisplayInteractor::ExecuteOperation(mitk::Operation * operation)
{
bool ok;//as return type
mitk::DisplayCoordinateOperation* dcOperation=dynamic_cast<mitk::DisplayCoordinateOperation*>(operation);
if ( dcOperation != NULL )
{
/****ZOOM & MOVE of the whole volume****/
mitk::BaseRenderer* renderer = dcOperation->GetRenderer();
if( renderer == NULL || (m_ParentRenderer != NULL && m_ParentRenderer != renderer))
return;
switch (operation->GetOperationType())
{
case OpMOVE :
{
renderer->GetDisplayGeometry()->MoveBy(dcOperation->GetLastToCurrentDisplayVector()*(-1.0));
mitk::RenderingManager::GetInstance()->RequestUpdate(renderer->GetRenderWindow());
ok = true;
}
break;
case OpZOOM :
{
float distance = dcOperation->GetLastToCurrentDisplayVector()[1];
//float factor= 1.0 + distance * 0.05; // stupid because factors from +1 and -1 dont give results that represent inverse zooms
float factor = 1.0;
if (distance < 0.0)
{
factor = 1.0 / 1.05;
}
else if (distance > 0.0)
{
factor = 1.0 * 1.05; // 5%
}
else // distance == 0.0
{
// nothing to do, factor remains 1.0
}
renderer->GetDisplayGeometry()->Zoom(factor, dcOperation->GetStartDisplayCoordinate());
mitk::RenderingManager::GetInstance()->RequestUpdate(renderer->GetRenderWindow());
ok = true;
}
break;
default:
;
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <algorithm>
#include <iomanip>
#include <cstdlib>
#include <cstring>
#include <functional>
#ifdef _WIN32
#include <Windows.h>
#endif
using namespace Aws::Utils;
void StringUtils::Replace(Aws::String& s, const char* search, const char* replace)
{
if(!search || !replace)
{
return;
}
size_t replaceLength = strlen(replace);
size_t searchLength = strlen(search);
for (std::size_t pos = 0;; pos += replaceLength)
{
pos = s.find(search, pos);
if (pos == Aws::String::npos)
break;
s.erase(pos, searchLength);
s.insert(pos, replace);
}
}
Aws::String StringUtils::ToLower(const char* source)
{
Aws::String copy;
size_t sourceLength = strlen(source);
copy.resize(sourceLength);
//appease the latest whims of the VC++ 2017 gods
std::transform(source, source + sourceLength, copy.begin(), [](unsigned char c) { return (char)::tolower(c); });
return copy;
}
Aws::String StringUtils::ToUpper(const char* source)
{
Aws::String copy;
size_t sourceLength = strlen(source);
copy.resize(sourceLength);
//appease the latest whims of the VC++ 2017 gods
std::transform(source, source + sourceLength, copy.begin(), [](unsigned char c) { return (char)::toupper(c); });
return copy;
}
bool StringUtils::CaselessCompare(const char* value1, const char* value2)
{
Aws::String value1Lower = ToLower(value1);
Aws::String value2Lower = ToLower(value2);
return value1Lower == value2Lower;
}
Aws::Vector<Aws::String> StringUtils::Split(const Aws::String& toSplit, char splitOn)
{
Aws::StringStream input(toSplit);
Aws::Vector<Aws::String> returnValues;
Aws::String item;
while(std::getline(input, item, splitOn))
{
if(item.size() > 0)
{
returnValues.push_back(item);
}
}
return returnValues;
}
Aws::Vector<Aws::String> StringUtils::SplitOnLine(const Aws::String& toSplit)
{
Aws::StringStream input(toSplit);
Aws::Vector<Aws::String> returnValues;
Aws::String item;
while (std::getline(input, item))
{
if (item.size() > 0)
{
returnValues.push_back(item);
}
}
return returnValues;
}
Aws::String StringUtils::URLEncode(const char* unsafe)
{
Aws::StringStream escaped;
escaped.fill('0');
escaped << std::hex << std::uppercase;
size_t unsafeLength = strlen(unsafe);
for (auto i = unsafe, n = unsafe + unsafeLength; i != n; ++i)
{
int c = *i;
//MSVC 2015 has an assertion that c is positive in isalnum(). This breaks unicode support.
//bypass that with the first check.
if (c >= 0 && (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~'))
{
escaped << (char)c;
}
else
{
//this unsigned char cast allows us to handle unicode characters.
escaped << '%' << std::setw(2) << int((unsigned char)c) << std::setw(0);
}
}
return escaped.str();
}
Aws::String StringUtils::UTF8Escape(const char* unicodeString, const char* delimiter)
{
Aws::StringStream escaped;
escaped.fill('0');
escaped << std::hex << std::uppercase;
size_t unsafeLength = strlen(unicodeString);
for (auto i = unicodeString, n = unicodeString + unsafeLength; i != n; ++i)
{
int c = *i;
//MSVC 2015 has an assertion that c is positive in isalnum(). This breaks unicode support.
//bypass that with the first check.
if (c >= ' ' && c < 127 )
{
escaped << (char)c;
}
else
{
//this unsigned char cast allows us to handle unicode characters.
escaped << delimiter << std::setw(2) << int((unsigned char)c) << std::setw(0);
}
}
return escaped.str();
}
Aws::String StringUtils::URLEncode(double unsafe)
{
char buffer[32];
#if defined(_MSC_VER) && _MSC_VER < 1900
_snprintf_s(buffer, sizeof(buffer), _TRUNCATE, "%g", unsafe);
#else
snprintf(buffer, sizeof(buffer), "%g", unsafe);
#endif
return StringUtils::URLEncode(buffer);
}
Aws::String StringUtils::URLDecode(const char* safe)
{
Aws::StringStream unescaped;
unescaped.fill('0');
unescaped << std::hex;
size_t safeLength = strlen(safe);
for (auto i = safe, n = safe + safeLength; i != n; ++i)
{
char c = *i;
if(c == '%')
{
char hex[3];
hex[0] = *(i + 1);
hex[1] = *(i + 2);
hex[2] = 0;
i += 2;
auto hexAsInteger = strtol(hex, nullptr, 16);
unescaped << (char)hexAsInteger;
}
else
{
unescaped << *i;
}
}
return unescaped.str();
}
Aws::String StringUtils::LTrim(const char* source)
{
Aws::String copy(source);
copy.erase(copy.begin(), std::find_if(copy.begin(), copy.end(), std::not1(std::ptr_fun<int, int>(::isspace))));
return copy;
}
// trim from end
Aws::String StringUtils::RTrim(const char* source)
{
Aws::String copy(source);
copy.erase(std::find_if(copy.rbegin(), copy.rend(), std::not1(std::ptr_fun<int, int>(::isspace))).base(), copy.end());
return copy;
}
// trim from both ends
Aws::String StringUtils::Trim(const char* source)
{
return LTrim(RTrim(source).c_str());
}
long long StringUtils::ConvertToInt64(const char* source)
{
if(!source)
{
return 0;
}
#ifdef __ANDROID__
return atoll(source);
#else
return std::atoll(source);
#endif // __ANDROID__
}
long StringUtils::ConvertToInt32(const char* source)
{
if (!source)
{
return 0;
}
return std::atol(source);
}
bool StringUtils::ConvertToBool(const char* source)
{
if(!source)
{
return false;
}
Aws::String strValue = ToLower(source);
if(strValue == "true" || strValue == "1")
{
return true;
}
return false;
}
double StringUtils::ConvertToDouble(const char* source)
{
if(!source)
{
return 0.0;
}
return std::strtod(source, NULL);
}
#ifdef _WIN32
Aws::WString StringUtils::ToWString(const char* source)
{
const auto len = std::strlen(source);
Aws::WString outString;
outString.resize(len); // there is no way UTF-16 would require _more_ code-points than UTF-8 for the _same_ string
const auto result = MultiByteToWideChar(CP_UTF8 /*CodePage*/,
0 /*dwFlags*/,
source /*lpMultiByteStr*/,
len /*cbMultiByte*/,
&outString[0] /*lpWideCharStr*/,
outString.length() /*cchWideChar*/);
if (!result)
{
return L"";
}
outString.resize(result);
return outString;
}
Aws::String StringUtils::FromWString(const wchar_t* source)
{
const auto len = wcslen(source);
Aws::String output;
if (int requiredSizeInBytes = WideCharToMultiByte(CP_UTF8 /*CodePage*/,
0 /*dwFlags*/,
source /*lpWideCharStr*/,
len /*cchWideChar*/,
nullptr /*lpMultiByteStr*/,
0 /*cbMultiByte*/,
nullptr /*lpDefaultChar*/,
nullptr /*lpUsedDefaultChar*/))
{
output.resize(requiredSizeInBytes);
}
const auto result = WideCharToMultiByte(CP_UTF8 /*CodePage*/,
0 /*dwFlags*/,
source /*lpWideCharStr*/,
len /*cchWideChar*/,
&output[0] /*lpMultiByteStr*/,
output.length() /*cbMultiByte*/,
nullptr /*lpDefaultChar*/,
nullptr /*lpUsedDefaultChar*/);
if (!result)
{
return "";
}
output.resize(result);
return output;
}
#endif
<commit_msg>Cast size_t to int to avoid msvc warnings<commit_after>/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <algorithm>
#include <iomanip>
#include <cstdlib>
#include <cstring>
#include <functional>
#ifdef _WIN32
#include <Windows.h>
#endif
using namespace Aws::Utils;
void StringUtils::Replace(Aws::String& s, const char* search, const char* replace)
{
if(!search || !replace)
{
return;
}
size_t replaceLength = strlen(replace);
size_t searchLength = strlen(search);
for (std::size_t pos = 0;; pos += replaceLength)
{
pos = s.find(search, pos);
if (pos == Aws::String::npos)
break;
s.erase(pos, searchLength);
s.insert(pos, replace);
}
}
Aws::String StringUtils::ToLower(const char* source)
{
Aws::String copy;
size_t sourceLength = strlen(source);
copy.resize(sourceLength);
//appease the latest whims of the VC++ 2017 gods
std::transform(source, source + sourceLength, copy.begin(), [](unsigned char c) { return (char)::tolower(c); });
return copy;
}
Aws::String StringUtils::ToUpper(const char* source)
{
Aws::String copy;
size_t sourceLength = strlen(source);
copy.resize(sourceLength);
//appease the latest whims of the VC++ 2017 gods
std::transform(source, source + sourceLength, copy.begin(), [](unsigned char c) { return (char)::toupper(c); });
return copy;
}
bool StringUtils::CaselessCompare(const char* value1, const char* value2)
{
Aws::String value1Lower = ToLower(value1);
Aws::String value2Lower = ToLower(value2);
return value1Lower == value2Lower;
}
Aws::Vector<Aws::String> StringUtils::Split(const Aws::String& toSplit, char splitOn)
{
Aws::StringStream input(toSplit);
Aws::Vector<Aws::String> returnValues;
Aws::String item;
while(std::getline(input, item, splitOn))
{
if(item.size() > 0)
{
returnValues.push_back(item);
}
}
return returnValues;
}
Aws::Vector<Aws::String> StringUtils::SplitOnLine(const Aws::String& toSplit)
{
Aws::StringStream input(toSplit);
Aws::Vector<Aws::String> returnValues;
Aws::String item;
while (std::getline(input, item))
{
if (item.size() > 0)
{
returnValues.push_back(item);
}
}
return returnValues;
}
Aws::String StringUtils::URLEncode(const char* unsafe)
{
Aws::StringStream escaped;
escaped.fill('0');
escaped << std::hex << std::uppercase;
size_t unsafeLength = strlen(unsafe);
for (auto i = unsafe, n = unsafe + unsafeLength; i != n; ++i)
{
int c = *i;
//MSVC 2015 has an assertion that c is positive in isalnum(). This breaks unicode support.
//bypass that with the first check.
if (c >= 0 && (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~'))
{
escaped << (char)c;
}
else
{
//this unsigned char cast allows us to handle unicode characters.
escaped << '%' << std::setw(2) << int((unsigned char)c) << std::setw(0);
}
}
return escaped.str();
}
Aws::String StringUtils::UTF8Escape(const char* unicodeString, const char* delimiter)
{
Aws::StringStream escaped;
escaped.fill('0');
escaped << std::hex << std::uppercase;
size_t unsafeLength = strlen(unicodeString);
for (auto i = unicodeString, n = unicodeString + unsafeLength; i != n; ++i)
{
int c = *i;
//MSVC 2015 has an assertion that c is positive in isalnum(). This breaks unicode support.
//bypass that with the first check.
if (c >= ' ' && c < 127 )
{
escaped << (char)c;
}
else
{
//this unsigned char cast allows us to handle unicode characters.
escaped << delimiter << std::setw(2) << int((unsigned char)c) << std::setw(0);
}
}
return escaped.str();
}
Aws::String StringUtils::URLEncode(double unsafe)
{
char buffer[32];
#if defined(_MSC_VER) && _MSC_VER < 1900
_snprintf_s(buffer, sizeof(buffer), _TRUNCATE, "%g", unsafe);
#else
snprintf(buffer, sizeof(buffer), "%g", unsafe);
#endif
return StringUtils::URLEncode(buffer);
}
Aws::String StringUtils::URLDecode(const char* safe)
{
Aws::StringStream unescaped;
unescaped.fill('0');
unescaped << std::hex;
size_t safeLength = strlen(safe);
for (auto i = safe, n = safe + safeLength; i != n; ++i)
{
char c = *i;
if(c == '%')
{
char hex[3];
hex[0] = *(i + 1);
hex[1] = *(i + 2);
hex[2] = 0;
i += 2;
auto hexAsInteger = strtol(hex, nullptr, 16);
unescaped << (char)hexAsInteger;
}
else
{
unescaped << *i;
}
}
return unescaped.str();
}
Aws::String StringUtils::LTrim(const char* source)
{
Aws::String copy(source);
copy.erase(copy.begin(), std::find_if(copy.begin(), copy.end(), std::not1(std::ptr_fun<int, int>(::isspace))));
return copy;
}
// trim from end
Aws::String StringUtils::RTrim(const char* source)
{
Aws::String copy(source);
copy.erase(std::find_if(copy.rbegin(), copy.rend(), std::not1(std::ptr_fun<int, int>(::isspace))).base(), copy.end());
return copy;
}
// trim from both ends
Aws::String StringUtils::Trim(const char* source)
{
return LTrim(RTrim(source).c_str());
}
long long StringUtils::ConvertToInt64(const char* source)
{
if(!source)
{
return 0;
}
#ifdef __ANDROID__
return atoll(source);
#else
return std::atoll(source);
#endif // __ANDROID__
}
long StringUtils::ConvertToInt32(const char* source)
{
if (!source)
{
return 0;
}
return std::atol(source);
}
bool StringUtils::ConvertToBool(const char* source)
{
if(!source)
{
return false;
}
Aws::String strValue = ToLower(source);
if(strValue == "true" || strValue == "1")
{
return true;
}
return false;
}
double StringUtils::ConvertToDouble(const char* source)
{
if(!source)
{
return 0.0;
}
return std::strtod(source, NULL);
}
#ifdef _WIN32
Aws::WString StringUtils::ToWString(const char* source)
{
const auto len = static_cast<int>(std::strlen(source));
Aws::WString outString;
outString.resize(len); // there is no way UTF-16 would require _more_ code-points than UTF-8 for the _same_ string
const auto result = MultiByteToWideChar(CP_UTF8 /*CodePage*/,
0 /*dwFlags*/,
source /*lpMultiByteStr*/,
len /*cbMultiByte*/,
&outString[0] /*lpWideCharStr*/,
static_cast<int>(outString.length())/*cchWideChar*/);
if (!result)
{
return L"";
}
outString.resize(result);
return outString;
}
Aws::String StringUtils::FromWString(const wchar_t* source)
{
const auto len = static_cast<int>(std::wcslen(source));
Aws::String output;
if (int requiredSizeInBytes = WideCharToMultiByte(CP_UTF8 /*CodePage*/,
0 /*dwFlags*/,
source /*lpWideCharStr*/,
len /*cchWideChar*/,
nullptr /*lpMultiByteStr*/,
0 /*cbMultiByte*/,
nullptr /*lpDefaultChar*/,
nullptr /*lpUsedDefaultChar*/))
{
output.resize(requiredSizeInBytes);
}
const auto result = WideCharToMultiByte(CP_UTF8 /*CodePage*/,
0 /*dwFlags*/,
source /*lpWideCharStr*/,
len /*cchWideChar*/,
&output[0] /*lpMultiByteStr*/,
static_cast<int>(output.length()) /*cbMultiByte*/,
nullptr /*lpDefaultChar*/,
nullptr /*lpUsedDefaultChar*/);
if (!result)
{
return "";
}
output.resize(result);
return output;
}
#endif
<|endoftext|> |
<commit_before>#ifndef GNR_STRUCTITERATOR_HPP
# define GNR_STRUCTITERATOR_HPP
# pragma once
#include <iterator>
#include <memory> //std::addressof()
#include "boost/pfr.hpp"
namespace gnr
{
namespace detail::struct_iterator
{
template <class S>
constexpr auto all_same() noexcept
{
if constexpr (constexpr auto N(boost::pfr::tuple_size_v<S>); N > 1)
{
return [&]<auto ...I>(std::index_sequence<I...>) noexcept
{
return (
(
std::is_same_v<
boost::pfr::tuple_element_t<I, S>,
boost::pfr::tuple_element_t<I + 1, S>
>
) && ...
);
}(std::make_index_sequence<N - 1>());
}
else
{
return true;
}
}
template <class S>
static constexpr bool is_proper_v(std::is_class_v<S> && all_same<S>());
}
template <typename S>
requires detail::struct_iterator::is_proper_v<S>
class struct_iterator
{
S& s_;
std::size_t i_;
public:
using iterator_category = std::random_access_iterator_tag;
using difference_type = std::ptrdiff_t;
using pointer = decltype(&boost::pfr::get<0>(s_));
using reference = decltype(boost::pfr::get<0>(s_));
using value_type = std::remove_reference_t<reference>;
public:
constexpr explicit struct_iterator(S& s,
std::size_t const i = boost::pfr::tuple_size<S>{}) noexcept:
s_{s},
i_{i}
{
}
// increment, decrement
constexpr auto& operator++() noexcept { return ++i_, *this; }
constexpr auto& operator--() noexcept { return --i_, *this; }
constexpr auto operator++(int) const noexcept
{
return struct_iterator(s_, i_ + 1);
}
constexpr auto operator--(int) const noexcept
{
return struct_iterator(s_, i_ - 1);
}
// arithmetic
constexpr auto operator-(struct_iterator const other) const noexcept
{
return difference_type(i_ - other.i_);
}
constexpr auto operator+(std::size_t const N) const noexcept
{
return struct_iterator(s_, i_ + N);
}
constexpr auto operator-(std::size_t const N) const noexcept
{
return struct_iterator(s_, i_ - N);
}
// comparison
constexpr bool operator==(struct_iterator const other) const noexcept
{
return (std::addressof(other.s_) == std::addressof(s_)) &&
(other.i_ == i_);
}
constexpr bool operator!=(struct_iterator const other) const noexcept
{
return !(*this == other);
}
constexpr auto operator<(struct_iterator const other) const noexcept
{
return i_ < other.i_;
}
//
constexpr auto& operator*() const noexcept
{
return [&]<auto ...I>(std::index_sequence<I...>) noexcept -> auto&
{
return *pointer(
(
(
I == i_ ?
std::uintptr_t(&boost::pfr::get<I>(s_)) :
std::uintptr_t{}
) |
...
)
);
}(std::make_index_sequence<boost::pfr::tuple_size_v<S>>());
}
constexpr auto& operator[](std::size_t const i) const noexcept
{
return *(*this + i);
}
};
template <typename S>
requires detail::struct_iterator::is_proper_v<S>
class range
{
S& s_;
public:
constexpr explicit range(S& s) noexcept : s_{s}
{
}
constexpr auto begin() const noexcept
{
return struct_iterator{s_, {}};
}
constexpr auto end() const noexcept
{
return struct_iterator{s_};
}
};
template <typename S>
requires detail::struct_iterator::is_proper_v<S>
constexpr auto begin(S& s) noexcept
{
return struct_iterator{s, {}};
}
template <typename S>
requires detail::struct_iterator::is_proper_v<S>
constexpr auto end(S& s) noexcept
{
return struct_iterator{s};
}
template <typename S>
requires detail::struct_iterator::is_proper_v<S>
constexpr auto size(S& s) noexcept
{
return boost::pfr::tuple_size_v<S>;
}
}
#endif // GNR_STRUCTITERATOR_HPP
<commit_msg>some fixes<commit_after>#ifndef GNR_STRUCTITERATOR_HPP
# define GNR_STRUCTITERATOR_HPP
# pragma once
#include <iterator>
#include <memory> //std::addressof()
#include "boost/pfr.hpp"
namespace gnr
{
namespace detail::struct_iterator
{
template <class S>
constexpr auto all_same() noexcept
{
if constexpr (constexpr auto N(boost::pfr::tuple_size_v<S>); N > 1)
{
return [&]<auto ...I>(std::index_sequence<I...>) noexcept
{
return (
(
std::is_same_v<
boost::pfr::tuple_element_t<I, S>,
boost::pfr::tuple_element_t<I + 1, S>
>
) && ...
);
}(std::make_index_sequence<N - 1>());
}
else
{
return true;
}
}
template <class S>
static constexpr auto is_proper_v(std::is_class_v<S> && all_same<S>());
}
template <typename S>
requires detail::struct_iterator::is_proper_v<S>
class struct_iterator
{
S& s_;
std::size_t i_;
public:
using iterator_category = std::random_access_iterator_tag;
using difference_type = std::ptrdiff_t;
using pointer = decltype(&boost::pfr::get<0>(s_));
using reference = decltype(boost::pfr::get<0>(s_));
using value_type = std::remove_reference_t<reference>;
public:
constexpr explicit struct_iterator(S& s,
std::size_t const i = boost::pfr::tuple_size<S>{}) noexcept:
s_{s},
i_{i}
{
}
// increment, decrement
constexpr auto& operator++() noexcept { return ++i_, *this; }
constexpr auto& operator--() noexcept { return --i_, *this; }
constexpr auto operator++(int) const noexcept
{
return struct_iterator(s_, i_ + 1);
}
constexpr auto operator--(int) const noexcept
{
return struct_iterator(s_, i_ - 1);
}
// arithmetic
constexpr auto operator-(struct_iterator const other) const noexcept
{
return difference_type(i_ - other.i_);
}
constexpr auto operator+(std::size_t const N) const noexcept
{
return struct_iterator(s_, i_ + N);
}
constexpr auto operator-(std::size_t const N) const noexcept
{
return struct_iterator(s_, i_ - N);
}
// comparison
constexpr auto operator==(struct_iterator const other) const noexcept
{
return (std::addressof(other.s_) == std::addressof(s_)) &&
(other.i_ == i_);
}
constexpr auto operator!=(struct_iterator const other) const noexcept
{
return !(*this == other);
}
constexpr auto operator<(struct_iterator const other) const noexcept
{
return i_ < other.i_;
}
//
constexpr auto& operator*() const noexcept
{
return [&]<auto ...I>(std::index_sequence<I...>) noexcept -> auto&
{
return *pointer(
(
(
I == i_ ?
std::uintptr_t(&boost::pfr::get<I>(s_)) :
std::uintptr_t{}
) |
...
)
);
}(std::make_index_sequence<boost::pfr::tuple_size_v<S>>());
}
constexpr auto& operator[](std::size_t const i) const noexcept
{
return *(*this + i);
}
};
template <typename S>
requires detail::struct_iterator::is_proper_v<S>
class range
{
S& s_;
public:
constexpr explicit range(S& s) noexcept : s_{s}
{
}
constexpr auto begin() const noexcept
{
return struct_iterator{s_, {}};
}
constexpr auto end() const noexcept
{
return struct_iterator{s_};
}
};
template <typename S>
requires detail::struct_iterator::is_proper_v<S>
constexpr auto begin(S& s) noexcept
{
return struct_iterator{s, {}};
}
template <typename S>
requires detail::struct_iterator::is_proper_v<S>
constexpr auto end(S& s) noexcept
{
return struct_iterator{s};
}
template <typename S>
requires detail::struct_iterator::is_proper_v<S>
constexpr auto size(S& s) noexcept
{
return boost::pfr::tuple_size_v<S>;
}
}
#endif // GNR_STRUCTITERATOR_HPP
<|endoftext|> |
<commit_before>/*
* TurretDataComponent.cpp
*
* Created on: Dec 10, 2012
* Author: root
*/
#include "TurretDataComponent.h"
#include "server/zone/objects/installation/InstallationObject.h"
#include "server/zone/packets/scene/AttributeListMessage.h"
#include "server/zone/objects/installation/components/TurretFireTask.h"
void TurretDataComponent::initializeTransientMembers() {
if(getParent() != NULL){
templateData = dynamic_cast<SharedInstallationObjectTemplate*>(getParent()->getObjectTemplate());
SceneObject* sceneObject = getParent()->getSlottedObject("hold_r");
if(sceneObject == NULL){
return;
}
WeaponObject* weapon = cast<WeaponObject*>(sceneObject);
if(weapon != NULL){
attackSpeed = weapon->getAttackSpeed();
maxrange = weapon->getMaxRange();
}
}
}
void TurretDataComponent::rescheduleFireTask(float secondsToWait, bool manual){
if(getParent() == NULL)
return;
CreatureObject* attacker = getController();
CreatureObject* target = getTarget();
Logger::Logger tlog("reschedule");
if(target != NULL){
Reference<TurretFireTask*> fireTask = new TurretFireTask(cast<TangibleObject*>(getParent()), getTarget(),manual);
this->setFireTask(fireTask);
getFireTask()->schedule(secondsToWait * 1000);
} else {
tlog.info("target is null",true);
setController(NULL);
setFireTask(NULL);
setTarget(NULL);
}
}
void TurretDataComponent::setWeapon(WeaponObject* weapon){
if(weapon != NULL){
attackSpeed = weapon->getAttackSpeed();
maxrange = weapon->getMaxRange();
}
}
void TurretDataComponent::fillAttributeList(AttributeListMessage* alm){
if(getParent() == NULL)
return;
ManagedReference<InstallationObject*> turret = cast<InstallationObject*>(getParent());
alm->insertAttribute("condition",String::valueOf(turret->getMaxCondition() - turret->getConditionDamage()) + "/" + String::valueOf(turret->getMaxCondition()));
alm->insertAttribute("armorrating","Heavy");
alm->insertAttribute("cat_armor_special_protection.armor_eff_energy",String::valueOf(getEnergy()) + "%");
alm->insertAttribute("cat_armor_special_protection.armor_eff_stun",String::valueOf(getStun()) + "%");
alm->insertAttribute("cat_armor_effectiveness.armor_eff_kinetic",String::valueOf(getKinetic()) + "%");
alm->insertAttribute("cat_armor_effectiveness.armor_eff_elemental_heat",String::valueOf(getHeat()) + "%");
alm->insertAttribute("cat_armor_effectiveness.armor_eff_elemental_cold",String::valueOf(getCold()) + "%");
alm->insertAttribute("cat_armor_effectiveness.armor_eff_elemental_acid",String::valueOf(getAcid()) + "%");
alm->insertAttribute("cat_armor_effectiveness.armor_eff_elemental_electrical",String::valueOf(getElectricity()) + "%");
alm->insertAttribute("cat_armor_vulnerability.armor_eff_blast",String::valueOf(getBlast()) + "%");
alm->insertAttribute("cat_armor_encumbrance.health","0");
alm->insertAttribute("cat_armor_encumbrance.action","0");
alm->insertAttribute("cat_armor_encumbrance.mind","0");
alm->insertAttribute("description",turret->getDetailedDescription());
alm->insertAttribute("owner",String::valueOf(turret->getOwnerObjectID()));
}
void TurretDataComponent::updateAutoCooldown(float secondsToAdd){
int milisecondsToAdd = secondsToAdd*1000;
nextFireTime = Time();
nextFireTime.addMiliTime(milisecondsToAdd);
}
void TurretDataComponent::updateManualCooldown(float secondsToAdd){
int milisecondsToAdd = secondsToAdd*1000;
nextManualFireTime = Time();
nextManualFireTime.addMiliTime(milisecondsToAdd);
}
unsigned int TurretDataComponent::getArmorRating(){
if(templateData != NULL)
return templateData->getArmorRating();
return 0;
}
float TurretDataComponent::getKinetic(){
if(templateData != NULL)
return templateData->getKinetic();
return 0;
}
float TurretDataComponent::getEnergy(){
if(templateData != NULL)
return templateData->getKinetic();
return 0;
}
float TurretDataComponent::getElectricity(){
if(templateData != NULL)
return templateData->getElectricity();
return 0;
}
float TurretDataComponent::getStun(){
if(templateData != NULL)
return templateData->getStun();
return 0;
}
float TurretDataComponent::getBlast(){
if(templateData != NULL)
return templateData->getBlast();
return 0;
}
float TurretDataComponent::getHeat(){
if(templateData != NULL)
return templateData->getHeat();
return 0;
}
float TurretDataComponent::getCold(){
if(templateData != NULL)
return templateData->getCold();
return 0;
}
float TurretDataComponent::getAcid(){
if(templateData != NULL)
return templateData->getAcid();
return 0;
}
float TurretDataComponent::getLightSaber(){
if(templateData != NULL)
return templateData->getLightSaber();
return 0;
}
float TurretDataComponent::getChanceHit(){
if(templateData != NULL)
return templateData->getChanceHit();
return 0;
}
String TurretDataComponent::getWeaponString(){
if(templateData != NULL)
return templateData->getWeapon();
return "";
}
<commit_msg>[Fixed] attribute list on turrets [Fixed] turrets using kinetic resist for energy resist<commit_after>/*
* TurretDataComponent.cpp
*
* Created on: Dec 10, 2012
* Author: root
*/
#include "TurretDataComponent.h"
#include "server/zone/objects/installation/InstallationObject.h"
#include "server/zone/packets/scene/AttributeListMessage.h"
#include "server/zone/objects/installation/components/TurretFireTask.h"
void TurretDataComponent::initializeTransientMembers() {
if(getParent() != NULL){
templateData = dynamic_cast<SharedInstallationObjectTemplate*>(getParent()->getObjectTemplate());
SceneObject* sceneObject = getParent()->getSlottedObject("hold_r");
if(sceneObject == NULL){
return;
}
WeaponObject* weapon = cast<WeaponObject*>(sceneObject);
if(weapon != NULL){
attackSpeed = weapon->getAttackSpeed();
maxrange = weapon->getMaxRange();
}
}
}
void TurretDataComponent::rescheduleFireTask(float secondsToWait, bool manual){
if(getParent() == NULL)
return;
CreatureObject* attacker = getController();
CreatureObject* target = getTarget();
Logger::Logger tlog("reschedule");
if(target != NULL){
Reference<TurretFireTask*> fireTask = new TurretFireTask(cast<TangibleObject*>(getParent()), getTarget(),manual);
this->setFireTask(fireTask);
getFireTask()->schedule(secondsToWait * 1000);
} else {
tlog.info("target is null",true);
setController(NULL);
setFireTask(NULL);
setTarget(NULL);
}
}
void TurretDataComponent::setWeapon(WeaponObject* weapon){
if(weapon != NULL){
attackSpeed = weapon->getAttackSpeed();
maxrange = weapon->getMaxRange();
}
}
void TurretDataComponent::fillAttributeList(AttributeListMessage* alm){
if(getParent() == NULL)
return;
ManagedReference<InstallationObject*> turret = cast<InstallationObject*>(getParent());
alm->insertAttribute("condition",String::valueOf(turret->getMaxCondition() - turret->getConditionDamage()) + "/" + String::valueOf(turret->getMaxCondition()));
if (getArmorRating() == 0)
alm->insertAttribute("armorrating", "None");
else if (getArmorRating() == 1)
alm->insertAttribute("armorrating", "Light");
else if (getArmorRating() == 2)
alm->insertAttribute("armorrating", "Medium");
else if (getArmorRating() == 3)
alm->insertAttribute("armorrating", "Heavy");
if (getKinetic() > 90) {
StringBuffer txt;
txt << round(getKinetic()) << "%";
alm->insertAttribute("cat_armor_special_protection.armor_eff_kinetic", txt.toString());
}
if (getEnergy() > 90) {
StringBuffer txt;
txt << round(getEnergy()) << "%";
alm->insertAttribute("cat_armor_special_protection.armor_eff_energy", txt.toString());
}
if (getElectricity() > 90) {
StringBuffer txt;
txt << round(getElectricity()) << "%";
alm->insertAttribute("cat_armor_special_protection.armor_eff_elemental_electrical", txt.toString());
}
if (getStun() > 90) {
StringBuffer txt;
txt << round(getStun()) << "%";
alm->insertAttribute("cat_armor_special_protection.armor_eff_stun", txt.toString());
}
if (getBlast() > 90) {
StringBuffer txt;
txt << round(getBlast()) << "%";
alm->insertAttribute("cat_armor_special_protection.armor_eff_blast", txt.toString());
}
if (getHeat() > 90) {
StringBuffer txt;
txt << round(getHeat()) << "%";
alm->insertAttribute("cat_armor_special_protection.armor_eff_elemental_heat", txt.toString());
}
if (getCold() > 90) {
StringBuffer txt;
txt << round(getCold()) << "%";
alm->insertAttribute("cat_armor_special_protection.armor_eff_elemental_cold", txt.toString());
}
if (getAcid() > 90) {
StringBuffer txt;
txt << round(getAcid()) << "%";
alm->insertAttribute("cat_armor_special_protection.armor_eff_elemental_acid", txt.toString());
}
if (getLightSaber() > 90) {
StringBuffer txt;
txt << round(getLightSaber()) << "%";
alm->insertAttribute("cat_armor_special_protection.armor_eff_restraint", txt.toString());
}
if (getKinetic() > 0 && getKinetic() <= 90) {
StringBuffer txt;
txt << round(getKinetic()) << "%";
alm->insertAttribute("cat_armor_effectiveness.armor_eff_kinetic", txt.toString());
}
if (getEnergy() > 0 && getEnergy() <= 90) {
StringBuffer txt;
txt << round(getEnergy()) << "%";
alm->insertAttribute("cat_armor_effectiveness.armor_eff_energy", txt.toString());
}
if (getElectricity() > 0 && getElectricity() <= 90) {
StringBuffer txt;
txt << round(getElectricity()) << "%";
alm->insertAttribute("cat_armor_effectiveness.armor_eff_elemental_electrical", txt.toString());
}
if (getStun() > 0 && getStun() <= 90) {
StringBuffer txt;
txt << round(getStun()) << "%";
alm->insertAttribute("cat_armor_effectiveness.armor_eff_stun", txt.toString());
}
if (getBlast() > 0 && getBlast() <= 90) {
StringBuffer txt;
txt << round(getBlast()) << "%";
alm->insertAttribute("cat_armor_effectiveness.armor_eff_blast", txt.toString());
}
if (getHeat() > 0 && getHeat() <= 90) {
StringBuffer txt;
txt << round(getHeat()) << "%";
alm->insertAttribute("cat_armor_effectiveness.armor_eff_elemental_heat", txt.toString());
}
if (getCold() > 0 && getCold() <= 90) {
StringBuffer txt;
txt << round(getCold()) << "%";
alm->insertAttribute("cat_armor_effectiveness.armor_eff_elemental_cold", txt.toString());
}
if (getAcid() > 0 && getAcid() <= 90) {
StringBuffer txt;
txt << round(getAcid()) << "%";
alm->insertAttribute("cat_armor_effectiveness.armor_eff_elemental_acid", txt.toString());
}
if (getLightSaber() > 0 && getLightSaber() <= 90) {
StringBuffer txt;
txt << round(getLightSaber()) << "%";
alm->insertAttribute("cat_armor_effectiveness.armor_eff_restraint", txt.toString());
}
if (getKinetic() < 0)
alm->insertAttribute("cat_armor_vulnerability.armor_eff_kinetic", "-");
if (getEnergy() < 0)
alm->insertAttribute("cat_armor_vulnerability.armor_eff_energy", "-");
if (getElectricity() < 0)
alm->insertAttribute("cat_armor_vulnerability.armor_eff_elemental_electrical", "-");
if (getStun() < 0)
alm->insertAttribute("cat_armor_vulnerability.armor_eff_stun", "-");
if (getBlast() < 0)
alm->insertAttribute("cat_armor_vulnerability.armor_eff_blast", "-");
if (getHeat() < 0)
alm->insertAttribute("cat_armor_vulnerability.armor_eff_elemental_heat", "-");
if (getCold() < 0)
alm->insertAttribute("cat_armor_vulnerability.armor_eff_elemental_cold", "-");
if (getAcid() < 0)
alm->insertAttribute("cat_armor_vulnerability.armor_eff_elemental_acid", "-");
if (getLightSaber() < 0)
alm->insertAttribute("cat_armor_vulnerability.armor_eff_restraint", "-");
}
void TurretDataComponent::updateAutoCooldown(float secondsToAdd){
int milisecondsToAdd = secondsToAdd*1000;
nextFireTime = Time();
nextFireTime.addMiliTime(milisecondsToAdd);
}
void TurretDataComponent::updateManualCooldown(float secondsToAdd){
int milisecondsToAdd = secondsToAdd*1000;
nextManualFireTime = Time();
nextManualFireTime.addMiliTime(milisecondsToAdd);
}
unsigned int TurretDataComponent::getArmorRating(){
if(templateData != NULL)
return templateData->getArmorRating();
return 0;
}
float TurretDataComponent::getKinetic(){
if(templateData != NULL)
return templateData->getKinetic();
return 0;
}
float TurretDataComponent::getEnergy(){
if(templateData != NULL)
return templateData->getEnergy();
return 0;
}
float TurretDataComponent::getElectricity(){
if(templateData != NULL)
return templateData->getElectricity();
return 0;
}
float TurretDataComponent::getStun(){
if(templateData != NULL)
return templateData->getStun();
return 0;
}
float TurretDataComponent::getBlast(){
if(templateData != NULL)
return templateData->getBlast();
return 0;
}
float TurretDataComponent::getHeat(){
if(templateData != NULL)
return templateData->getHeat();
return 0;
}
float TurretDataComponent::getCold(){
if(templateData != NULL)
return templateData->getCold();
return 0;
}
float TurretDataComponent::getAcid(){
if(templateData != NULL)
return templateData->getAcid();
return 0;
}
float TurretDataComponent::getLightSaber(){
if(templateData != NULL)
return templateData->getLightSaber();
return 0;
}
float TurretDataComponent::getChanceHit(){
if(templateData != NULL)
return templateData->getChanceHit();
return 0;
}
String TurretDataComponent::getWeaponString(){
if(templateData != NULL)
return templateData->getWeapon();
return "";
}
<|endoftext|> |
<commit_before>/*************************************************************************
* Copyright(c) 1998-2008, 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. *
**************************************************************************/
#define AliFlowAnalysisWithMCEventPlane_cxx
#include "Riostream.h" //needed as include
#include "TFile.h" //needed as include
#include "TProfile.h" //needed as include
#include "TComplex.h" //needed as include
#include "TList.h"
class TH1F;
#include "AliFlowCommonConstants.h" //needed as include
#include "AliFlowEventSimple.h"
#include "AliFlowTrackSimple.h"
#include "AliFlowCommonHist.h"
#include "AliFlowCommonHistResults.h"
#include "AliFlowAnalysisWithMCEventPlane.h"
class AliFlowVector;
// AliFlowAnalysisWithMCEventPlane:
// Description: Maker to analyze Flow from the generated MC reaction plane.
// This class is used to get the real value of the flow
// to compare the other methods to when analysing simulated events
// author: N. van der Kolk (kolk@nikhef.nl)
ClassImp(AliFlowAnalysisWithMCEventPlane)
//-----------------------------------------------------------------------
AliFlowAnalysisWithMCEventPlane::AliFlowAnalysisWithMCEventPlane():
fQsum(NULL),
fQ2sum(0),
fEventNumber(0),
fDebug(kFALSE),
fHistList(NULL),
fCommonHists(NULL),
fCommonHistsRes(NULL),
fHistProFlow(NULL),
fHistRP(NULL),
fHistProIntFlowRP(NULL),
fHistProDiffFlowPtRP(NULL),
fHistProDiffFlowEtaRP(NULL),
fHistProDiffFlowPtPOI(NULL),
fHistProDiffFlowEtaPOI(NULL)
{
// Constructor.
fHistList = new TList();
fQsum = new TVector2; // flow vector sum
}
//-----------------------------------------------------------------------
AliFlowAnalysisWithMCEventPlane::~AliFlowAnalysisWithMCEventPlane()
{
//destructor
delete fHistList;
delete fQsum;
}
//-----------------------------------------------------------------------
void AliFlowAnalysisWithMCEventPlane::WriteHistograms(TString* outputFileName)
{
//store the final results in output .root file
TFile *output = new TFile(outputFileName->Data(),"RECREATE");
output->WriteObject(fHistList, "cobjMCEP","SingleKey");
delete output;
}
//-----------------------------------------------------------------------
void AliFlowAnalysisWithMCEventPlane::Init() {
//Define all histograms
cout<<"---Analysis with the real MC Event Plane---"<<endl;
Int_t iNbinsPt = AliFlowCommonConstants::GetNbinsPt();
Double_t dPtMin = AliFlowCommonConstants::GetPtMin();
Double_t dPtMax = AliFlowCommonConstants::GetPtMax();
Int_t iNbinsEta = AliFlowCommonConstants::GetNbinsEta();
Double_t dEtaMin = AliFlowCommonConstants::GetEtaMin();
Double_t dEtaMax = AliFlowCommonConstants::GetEtaMax();
fCommonHists = new AliFlowCommonHist("AliFlowCommonHistMCEP");
fHistList->Add(fCommonHists);
fCommonHistsRes = new AliFlowCommonHistResults("AliFlowCommonHistResultsMCEP");
fHistList->Add(fCommonHistsRes);
fHistProFlow = new TProfile("FlowPro_VPt_MCEP","FlowPro_VPt_MCEP",iNbinsPt,dPtMin,dPtMax);
fHistProFlow->SetXTitle("P_{t}");
fHistProFlow->SetYTitle("v_{2}");
fHistList->Add(fHistProFlow);
fHistRP = new TH1F("Flow_RP_MCEP","Flow_RP_MCEP",100,0.,3.14);
fHistRP->SetXTitle("Reaction Plane Angle");
fHistRP->SetYTitle("Counts");
fHistList->Add(fHistRP);
fHistProIntFlowRP = new TProfile("fHistProIntFlowRP","fHistProIntFlowRP",1,0.,1.);
fHistProIntFlowRP->SetLabelSize(0.06);
(fHistProIntFlowRP->GetXaxis())->SetBinLabel(1,"v_{n}{2}");
fHistProIntFlowRP->SetYTitle("");
fHistList->Add(fHistProIntFlowRP);
fHistProDiffFlowPtRP = new TProfile("fHistProDiffFlowPtRP","fHistProDiffFlowPtRP",iNbinsPt,dPtMin,dPtMax);
fHistProDiffFlowPtRP->SetXTitle("P_{t}");
fHistProDiffFlowPtRP->SetYTitle("");
fHistList->Add(fHistProDiffFlowPtRP);
fHistProDiffFlowEtaRP = new TProfile("fHistProDiffFlowEtaRP","fHistProDiffFlowEtaRP",iNbinsEta,dEtaMin,dEtaMax);
fHistProDiffFlowEtaRP->SetXTitle("#eta");
fHistProDiffFlowEtaRP->SetYTitle("");
fHistList->Add(fHistProDiffFlowEtaRP);
fHistProDiffFlowPtPOI = new TProfile("fHistProDiffFlowPtPOI","fHistProDiffFlowPtPOI",iNbinsPt,dPtMin,dPtMax);
fHistProDiffFlowPtPOI->SetXTitle("P_{t}");
fHistProDiffFlowPtPOI->SetYTitle("");
fHistList->Add(fHistProDiffFlowPtPOI);
fHistProDiffFlowEtaPOI = new TProfile("fHistProDiffFlowEtaPOI","fHistProDiffFlowEtaPOI",iNbinsEta,dEtaMin,dEtaMax);
fHistProDiffFlowEtaPOI->SetXTitle("#eta");
fHistProDiffFlowEtaPOI->SetYTitle("");
fHistList->Add(fHistProDiffFlowEtaPOI);
fEventNumber = 0; //set number of events to zero
}
//-----------------------------------------------------------------------
void AliFlowAnalysisWithMCEventPlane::Make(AliFlowEventSimple* anEvent, Double_t aRP) {
//Calculate v2 from the MC reaction plane
if (anEvent) {
//fill control histograms
fCommonHists->FillControlHistograms(anEvent);
//get the Q vector from the FlowEvent
AliFlowVector vQ = anEvent->GetQ();
//cout<<"vQ.Mod() = " << vQ.Mod() << endl;
//for chi calculation:
*fQsum += vQ;
//cout<<"fQsum.Mod() = "<<fQsum.Mod()<<endl;
fQ2sum += vQ.Mod2();
//cout<<"fQ2sum = "<<fQ2sum<<endl;
fHistRP->Fill(aRP);
Double_t dPhi = 0.;
Double_t dv2 = 0.;
Double_t dPt = 0.;
Double_t dEta = 0.;
//Double_t dPi = TMath::Pi();
//calculate flow
//loop over the tracks of the event
Int_t iNumberOfTracks = anEvent->NumberOfTracks();
for (Int_t i=0;i<iNumberOfTracks;i++)
{
AliFlowTrackSimple* pTrack = anEvent->GetTrack(i) ;
if (pTrack){
if (pTrack->UseForIntegratedFlow()){
dPhi = pTrack->Phi();
dv2 = TMath::Cos(2*(dPhi-aRP));
dPt = pTrack->Pt();
dEta = pTrack->Eta();
//integrated flow (RP):
fHistProIntFlowRP->Fill(0.,dv2);
//differential flow (Pt, RP):
fHistProDiffFlowPtRP->Fill(dPt,dv2,1.);
//differential flow (Eta, RP):
fHistProDiffFlowEtaRP->Fill(dEta,dv2,1.);
}
if (pTrack->UseForDifferentialFlow()) {
dPhi = pTrack->Phi();
//if (dPhi<0.) dPhi+=2*TMath::Pi();
//calculate flow v2:
dv2 = TMath::Cos(2*(dPhi-aRP));
dPt = pTrack->Pt();
dEta = pTrack->Eta();
//fill histogram
fHistProFlow->Fill(dPt,dv2);//to be removed
//differential flow (Pt, POI):
fHistProDiffFlowPtPOI->Fill(dPt,dv2,1.);
//differential flow (Eta, POI):
fHistProDiffFlowEtaPOI->Fill(dEta,dv2,1.);
}
}//track selected
}//loop over tracks
fEventNumber++;
cout<<"@@@@@ "<<fEventNumber<<" events processed"<<endl;
}
}
//--------------------------------------------------------------------
void AliFlowAnalysisWithMCEventPlane::Finish() {
//*************make histograms etc.
if (fDebug) cout<<"AliFlowAnalysisWithMCEventPlane::Terminate()"<<endl;
Int_t iNbinsPt = AliFlowCommonConstants::GetNbinsPt();
Int_t iNbinsEta = AliFlowCommonConstants::GetNbinsEta();
//RP:
//integrated flow:
Double_t dVRP = fHistProIntFlowRP->GetBinContent(1);
Double_t dErrVRP = fHistProIntFlowRP->GetBinError(1);
fCommonHistsRes->FillIntegratedFlowRP(dVRP,dErrVRP);
//differential flow (Pt):
Double_t dvPtRP = 0.;
Double_t dErrvPtRP = 0.;
for(Int_t b=0;b<iNbinsPt;b++)
{
dvPtRP = fHistProDiffFlowPtRP->GetBinContent(b+1);
dErrvPtRP = fHistProDiffFlowPtRP->GetBinError(b+1);
fCommonHistsRes->FillDifferentialFlowPtRP(b, dvPtRP , dErrvPtRP);
}
//differential flow (Eta):
Double_t dvEtaRP = 0.;
Double_t dErrvEtaRP = 0.;
for(Int_t b=0;b<iNbinsEta;b++)
{
dvEtaRP = fHistProDiffFlowEtaRP->GetBinContent(b+1);
dErrvEtaRP = fHistProDiffFlowEtaRP->GetBinError(b+1);
fCommonHistsRes->FillDifferentialFlowEtaRP(b, dvEtaRP , dErrvEtaRP);
}
//POI:
TH1F* fHistPtDiff = fCommonHists->GetHistPtDiff();
Double_t dV = 0.;
Double_t dErrV = 0.;
Double_t dSum = 0.;
Double_t dv2proPt = 0.;
Double_t dErrdifcombPt = 0.;
Double_t dv2proEta = 0.;
Double_t dErrdifcombEta = 0.;
//Pt:
if(fHistProFlow && fHistProDiffFlowPtPOI) {//to be removed (fHistProFlow)
for(Int_t b=0;b<iNbinsPt;b++){
//dv2pro = fHistProFlow->GetBinContent(b);//to be removed
//dErrdifcomb = fHistProFlow->GetBinError(b);//to be removed
dv2proPt = fHistProDiffFlowPtPOI->GetBinContent(b);
dErrdifcombPt = fHistProDiffFlowPtPOI->GetBinError(b); //in case error from profile is correct
//fill TH1D
fCommonHistsRes->FillDifferentialFlow(b, dv2proPt, dErrdifcombPt);//to be removed
fCommonHistsRes->FillDifferentialFlowPtPOI(b, dv2proPt, dErrdifcombPt);
if (fHistPtDiff){
//integrated flow
Double_t dYield = fHistPtDiff->GetBinContent(b);
dV += dv2proPt*dYield ;
dSum += dYield;
//error on integrated flow
dErrV += dYield*dYield*dErrdifcombPt*dErrdifcombPt;
}
}
} else { cout<<"fHistProFlow is NULL"<<endl; }
if (dSum != 0. ) {
dV /= dSum; //because pt distribution should be normalised
dErrV /= dSum*dSum;
dErrV = TMath::Sqrt(dErrV); }
cout<<"dV is "<<dV<<" +- "<<dErrV<<endl;
fCommonHistsRes->FillIntegratedFlow(dV,dErrV);//to be removed
fCommonHistsRes->FillIntegratedFlowPOI(dV,dErrV);
//Eta:
if(fHistProDiffFlowEtaPOI)
{
for(Int_t b=0;b<iNbinsEta;b++)
{
dv2proEta = fHistProDiffFlowEtaPOI->GetBinContent(b);
dErrdifcombEta = fHistProDiffFlowEtaPOI->GetBinError(b); //in case error from profile is correct
//fill common hist results:
fCommonHistsRes->FillDifferentialFlowEtaPOI(b, dv2proEta, dErrdifcombEta);
}
}
cout<<".....finished"<<endl;
}
<commit_msg>fixed bugs with underflows<commit_after>/*************************************************************************
* Copyright(c) 1998-2008, 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. *
**************************************************************************/
#define AliFlowAnalysisWithMCEventPlane_cxx
#include "Riostream.h" //needed as include
#include "TFile.h" //needed as include
#include "TProfile.h" //needed as include
#include "TComplex.h" //needed as include
#include "TList.h"
class TH1F;
#include "AliFlowCommonConstants.h" //needed as include
#include "AliFlowEventSimple.h"
#include "AliFlowTrackSimple.h"
#include "AliFlowCommonHist.h"
#include "AliFlowCommonHistResults.h"
#include "AliFlowAnalysisWithMCEventPlane.h"
class AliFlowVector;
// AliFlowAnalysisWithMCEventPlane:
// Description: Maker to analyze Flow from the generated MC reaction plane.
// This class is used to get the real value of the flow
// to compare the other methods to when analysing simulated events
// author: N. van der Kolk (kolk@nikhef.nl)
ClassImp(AliFlowAnalysisWithMCEventPlane)
//-----------------------------------------------------------------------
AliFlowAnalysisWithMCEventPlane::AliFlowAnalysisWithMCEventPlane():
fQsum(NULL),
fQ2sum(0),
fEventNumber(0),
fDebug(kFALSE),
fHistList(NULL),
fCommonHists(NULL),
fCommonHistsRes(NULL),
fHistProFlow(NULL),
fHistRP(NULL),
fHistProIntFlowRP(NULL),
fHistProDiffFlowPtRP(NULL),
fHistProDiffFlowEtaRP(NULL),
fHistProDiffFlowPtPOI(NULL),
fHistProDiffFlowEtaPOI(NULL)
{
// Constructor.
fHistList = new TList();
fQsum = new TVector2; // flow vector sum
}
//-----------------------------------------------------------------------
AliFlowAnalysisWithMCEventPlane::~AliFlowAnalysisWithMCEventPlane()
{
//destructor
delete fHistList;
delete fQsum;
}
//-----------------------------------------------------------------------
void AliFlowAnalysisWithMCEventPlane::WriteHistograms(TString* outputFileName)
{
//store the final results in output .root file
TFile *output = new TFile(outputFileName->Data(),"RECREATE");
output->WriteObject(fHistList, "cobjMCEP","SingleKey");
delete output;
}
//-----------------------------------------------------------------------
void AliFlowAnalysisWithMCEventPlane::Init() {
//Define all histograms
cout<<"---Analysis with the real MC Event Plane---"<<endl;
Int_t iNbinsPt = AliFlowCommonConstants::GetNbinsPt();
Double_t dPtMin = AliFlowCommonConstants::GetPtMin();
Double_t dPtMax = AliFlowCommonConstants::GetPtMax();
Int_t iNbinsEta = AliFlowCommonConstants::GetNbinsEta();
Double_t dEtaMin = AliFlowCommonConstants::GetEtaMin();
Double_t dEtaMax = AliFlowCommonConstants::GetEtaMax();
fCommonHists = new AliFlowCommonHist("AliFlowCommonHistMCEP");
fHistList->Add(fCommonHists);
fCommonHistsRes = new AliFlowCommonHistResults("AliFlowCommonHistResultsMCEP");
fHistList->Add(fCommonHistsRes);
fHistProFlow = new TProfile("FlowPro_VPt_MCEP","FlowPro_VPt_MCEP",iNbinsPt,dPtMin,dPtMax);
fHistProFlow->SetXTitle("P_{t}");
fHistProFlow->SetYTitle("v_{2}");
fHistList->Add(fHistProFlow);
fHistRP = new TH1F("Flow_RP_MCEP","Flow_RP_MCEP",100,0.,3.14);
fHistRP->SetXTitle("Reaction Plane Angle");
fHistRP->SetYTitle("Counts");
fHistList->Add(fHistRP);
fHistProIntFlowRP = new TProfile("fHistProIntFlowRP","fHistProIntFlowRP",1,0.,1.);
fHistProIntFlowRP->SetLabelSize(0.06);
(fHistProIntFlowRP->GetXaxis())->SetBinLabel(1,"v_{n}{2}");
fHistProIntFlowRP->SetYTitle("");
fHistList->Add(fHistProIntFlowRP);
fHistProDiffFlowPtRP = new TProfile("fHistProDiffFlowPtRP","fHistProDiffFlowPtRP",iNbinsPt,dPtMin,dPtMax);
fHistProDiffFlowPtRP->SetXTitle("P_{t}");
fHistProDiffFlowPtRP->SetYTitle("");
fHistList->Add(fHistProDiffFlowPtRP);
fHistProDiffFlowEtaRP = new TProfile("fHistProDiffFlowEtaRP","fHistProDiffFlowEtaRP",iNbinsEta,dEtaMin,dEtaMax);
fHistProDiffFlowEtaRP->SetXTitle("#eta");
fHistProDiffFlowEtaRP->SetYTitle("");
fHistList->Add(fHistProDiffFlowEtaRP);
fHistProDiffFlowPtPOI = new TProfile("fHistProDiffFlowPtPOI","fHistProDiffFlowPtPOI",iNbinsPt,dPtMin,dPtMax);
fHistProDiffFlowPtPOI->SetXTitle("P_{t}");
fHistProDiffFlowPtPOI->SetYTitle("");
fHistList->Add(fHistProDiffFlowPtPOI);
fHistProDiffFlowEtaPOI = new TProfile("fHistProDiffFlowEtaPOI","fHistProDiffFlowEtaPOI",iNbinsEta,dEtaMin,dEtaMax);
fHistProDiffFlowEtaPOI->SetXTitle("#eta");
fHistProDiffFlowEtaPOI->SetYTitle("");
fHistList->Add(fHistProDiffFlowEtaPOI);
fEventNumber = 0; //set number of events to zero
}
//-----------------------------------------------------------------------
void AliFlowAnalysisWithMCEventPlane::Make(AliFlowEventSimple* anEvent, Double_t aRP) {
//Calculate v2 from the MC reaction plane
if (anEvent) {
//fill control histograms
fCommonHists->FillControlHistograms(anEvent);
//get the Q vector from the FlowEvent
AliFlowVector vQ = anEvent->GetQ();
//cout<<"vQ.Mod() = " << vQ.Mod() << endl;
//for chi calculation:
*fQsum += vQ;
//cout<<"fQsum.Mod() = "<<fQsum.Mod()<<endl;
fQ2sum += vQ.Mod2();
//cout<<"fQ2sum = "<<fQ2sum<<endl;
fHistRP->Fill(aRP);
Double_t dPhi = 0.;
Double_t dv2 = 0.;
Double_t dPt = 0.;
Double_t dEta = 0.;
//Double_t dPi = TMath::Pi();
//calculate flow
//loop over the tracks of the event
Int_t iNumberOfTracks = anEvent->NumberOfTracks();
for (Int_t i=0;i<iNumberOfTracks;i++)
{
AliFlowTrackSimple* pTrack = anEvent->GetTrack(i) ;
if (pTrack){
if (pTrack->UseForIntegratedFlow()){
dPhi = pTrack->Phi();
dv2 = TMath::Cos(2*(dPhi-aRP));
dPt = pTrack->Pt();
dEta = pTrack->Eta();
//integrated flow (RP):
fHistProIntFlowRP->Fill(0.,dv2);
//differential flow (Pt, RP):
fHistProDiffFlowPtRP->Fill(dPt,dv2,1.);
//differential flow (Eta, RP):
fHistProDiffFlowEtaRP->Fill(dEta,dv2,1.);
}
if (pTrack->UseForDifferentialFlow()) {
dPhi = pTrack->Phi();
//if (dPhi<0.) dPhi+=2*TMath::Pi();
//calculate flow v2:
dv2 = TMath::Cos(2*(dPhi-aRP));
dPt = pTrack->Pt();
dEta = pTrack->Eta();
//fill histogram
fHistProFlow->Fill(dPt,dv2);//to be removed
//differential flow (Pt, POI):
fHistProDiffFlowPtPOI->Fill(dPt,dv2,1.);
//differential flow (Eta, POI):
fHistProDiffFlowEtaPOI->Fill(dEta,dv2,1.);
}
}//track selected
}//loop over tracks
fEventNumber++;
cout<<"@@@@@ "<<fEventNumber<<" events processed"<<endl;
}
}
//--------------------------------------------------------------------
void AliFlowAnalysisWithMCEventPlane::Finish() {
//*************make histograms etc.
if (fDebug) cout<<"AliFlowAnalysisWithMCEventPlane::Terminate()"<<endl;
Int_t iNbinsPt = AliFlowCommonConstants::GetNbinsPt();
Int_t iNbinsEta = AliFlowCommonConstants::GetNbinsEta();
//RP:
//integrated flow:
Double_t dVRP = fHistProIntFlowRP->GetBinContent(1);
Double_t dErrVRP = fHistProIntFlowRP->GetBinError(1);//to be improved (treatment of errors for non-Gaussian distribution needed!)
fCommonHistsRes->FillIntegratedFlowRP(dVRP,dErrVRP);
//differential flow (Pt):
Double_t dvPtRP = 0.;
Double_t dErrvPtRP = 0.;
for(Int_t b=0;b<iNbinsPt;b++)
{
dvPtRP = fHistProDiffFlowPtRP->GetBinContent(b+1);
dErrvPtRP = fHistProDiffFlowPtRP->GetBinError(b+1);//to be improved (treatment of errors for non-Gaussian distribution needed!)
fCommonHistsRes->FillDifferentialFlowPtRP(b+1, dvPtRP, dErrvPtRP);
}
//differential flow (Eta):
Double_t dvEtaRP = 0.;
Double_t dErrvEtaRP = 0.;
for(Int_t b=0;b<iNbinsEta;b++)
{
dvEtaRP = fHistProDiffFlowEtaRP->GetBinContent(b+1);
dErrvEtaRP = fHistProDiffFlowEtaRP->GetBinError(b+1);//to be improved (treatment of errors for non-Gaussian distribution needed!)
fCommonHistsRes->FillDifferentialFlowEtaRP(b+1, dvEtaRP, dErrvEtaRP);
}
//POI:
TH1F* fHistPtDiff = fCommonHists->GetHistPtDiff();
Double_t dYieldPt = 0.;
Double_t dV = 0.;
Double_t dErrV = 0.;
Double_t dSum = 0.;
Double_t dv2proPt = 0.;
Double_t dErrdifcombPt = 0.;
Double_t dv2proEta = 0.;
Double_t dErrdifcombEta = 0.;
//Pt:
if(fHistProFlow && fHistProDiffFlowPtPOI) {//to be removed (fHistProFlow)
for(Int_t b=0;b<iNbinsPt;b++){
//dv2pro = fHistProFlow->GetBinContent(b);//to be removed
//dErrdifcomb = fHistProFlow->GetBinError(b);//to be removed
dv2proPt = fHistProDiffFlowPtPOI->GetBinContent(b+1);
dErrdifcombPt = fHistProDiffFlowPtPOI->GetBinError(b+1);//to be improved (treatment of errors for non-Gaussian distribution needed!)
//fill TH1D
fCommonHistsRes->FillDifferentialFlow(b+1, dv2proPt, dErrdifcombPt);//to be removed
fCommonHistsRes->FillDifferentialFlowPtPOI(b+1, dv2proPt, dErrdifcombPt);
if (fHistPtDiff){
//integrated flow (POI)
dYieldPt = fHistPtDiff->GetBinContent(b+1);
dV += dv2proPt*dYieldPt;
dSum += dYieldPt;
//error on integrated flow
dErrV += dYieldPt*dYieldPt*dErrdifcombPt*dErrdifcombPt;
}
}//end of for(Int_t b=0;b<iNbinsPt;b++)
} else { cout<<"fHistProFlow is NULL"<<endl; }
if (dSum != 0. ) {
dV /= dSum; //because pt distribution should be normalised
dErrV /= (dSum*dSum);
dErrV = TMath::Sqrt(dErrV);
}
cout<<"dV{MC} is "<<dV<<" +- "<<dErrV<<endl;
fCommonHistsRes->FillIntegratedFlow(dV,dErrV);//to be removed
fCommonHistsRes->FillIntegratedFlowPOI(dV,dErrV);
//Eta:
if(fHistProDiffFlowEtaPOI)
{
for(Int_t b=0;b<iNbinsEta;b++)
{
dv2proEta = fHistProDiffFlowEtaPOI->GetBinContent(b+1);
dErrdifcombEta = fHistProDiffFlowEtaPOI->GetBinError(b+1);//to be improved (treatment of errors for non-Gaussian distribution needed!)
//fill common hist results:
fCommonHistsRes->FillDifferentialFlowEtaPOI(b+1, dv2proEta, dErrdifcombEta);
}
}
cout<<".....finished"<<endl;
}
<|endoftext|> |
<commit_before>#include "cnn/nodes.h"
#include "cnn/cnn.h"
#include "cnn/training.h"
#include "cnn/timing.h"
#include "cnn/expr.h"
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
using namespace cnn;
using namespace cnn::expr;
int main(int argc, char** argv) {
cnn::Initialize(argc, argv);
unsigned CONTEXT = 3;
unsigned DIM = 100;
unsigned VOCAB_SIZE = 29;
// parameters
Model model;
SimpleSGDTrainer sgd(&model);
LookupParameters* p_c = model.add_lookup_parameters(VOCAB_SIZE, {DIM});
ComputationGraph cg;
unsigned in_c1, in_c2, in_c3; // set these to set the context words
Expression c1 = lookup(cg, p_c, &in_c1);
Expression c2 = lookup(cg, p_c, &in_c2);
Expression c3 = lookup(cg, p_c, &in_c3);
Expression C1 = parameter(cg, model.add_parameters({DIM, DIM}));
Expression C2 = parameter(cg, model.add_parameters({DIM, DIM}));
Expression C3 = parameter(cg, model.add_parameters({DIM, DIM}));
Expression hb = parameter(cg, model.add_parameters({DIM}));
Expression R = parameter(cg, model.add_parameters({VOCAB_SIZE, DIM}));
unsigned ytrue; // set ytrue to change the value of the input
Expression bias = parameter(cg, model.add_parameters({VOCAB_SIZE}));
Expression r = hb + C1 * c1 + C2 * c2 + C3 * c3;
Expression nl = rectify(r);
Expression o2 = bias + R * nl;
Expression ydist = log_softmax(o2);
Expression nerr = -pick(ydist, &ytrue);
cg.PrintGraphviz();
// load some training data
if (argc != 2) {
cerr << "Usage: " << argv[0] << " ngrams.txt\n";
return 1;
}
ifstream in(argv[1]);
vector<vector<unsigned>> corpus;
string line;
while(getline(in, line)) {
istringstream is(line);
vector<unsigned> x(CONTEXT+1);
for (unsigned i = 0; i <= CONTEXT; ++i) {
is >> x[i];
assert(x[i] < VOCAB_SIZE);
}
corpus.push_back(x);
}
// train the parameters
for (unsigned iter = 0; iter < 100; ++iter) {
Timer iteration("epoch completed in");
double loss = 0;
unsigned n = 0;
for (auto& ci : corpus) {
in_c1 = ci[0];
in_c2 = ci[1];
in_c3 = ci[2];
ytrue = ci[3];
loss += as_scalar(cg.forward());
cg.backward();
++n;
sgd.update(1.0);
if (n == 2500) break;
}
loss /= n;
cerr << "E = " << loss << ' ';
}
}
<commit_msg>nlm more concise, works for any n<commit_after>#include "cnn/nodes.h"
#include "cnn/cnn.h"
#include "cnn/training.h"
#include "cnn/timing.h"
#include "cnn/expr.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
using namespace std;
using namespace cnn;
using namespace cnn::expr;
int main(int argc, char** argv) {
cnn::Initialize(argc, argv);
unsigned CONTEXT = 3;
unsigned DIM = 100;
unsigned VOCAB_SIZE = 29;
// parameters
Model model;
SimpleSGDTrainer sgd(&model);
LookupParameters* p_c = model.add_lookup_parameters(VOCAB_SIZE, {DIM});
ComputationGraph cg;
vector<unsigned> in_c(CONTEXT); // set these to set the context words
vector<Expression> c(CONTEXT);
for (int i=0; i<CONTEXT; ++i)
c[i] = lookup(cg, p_c, &in_c[i]);
Expression C = parameter(cg, model.add_parameters({DIM, DIM*CONTEXT}));
Expression hb = parameter(cg, model.add_parameters({DIM}));
Expression R = parameter(cg, model.add_parameters({VOCAB_SIZE, DIM}));
unsigned ytrue; // set ytrue to change the value of the input
Expression bias = parameter(cg, model.add_parameters({VOCAB_SIZE}));
Expression cc = concatenate(c);
Expression r = hb + C * cc;
Expression nl = rectify(r);
Expression o2 = bias + R * nl;
Expression ydist = log_softmax(o2);
Expression nerr = -pick(ydist, &ytrue);
cg.PrintGraphviz();
// load some training data
if (argc != 2) {
cerr << "Usage: " << argv[0] << " ngrams.txt\n";
return 1;
}
ifstream in(argv[1]);
vector<vector<unsigned>> corpus;
string line;
while(getline(in, line)) {
istringstream is(line);
vector<unsigned> x(CONTEXT+1);
for (unsigned i = 0; i <= CONTEXT; ++i) {
is >> x[i];
assert(x[i] < VOCAB_SIZE);
}
corpus.push_back(x);
}
// train the parameters
for (unsigned iter = 0; iter < 100; ++iter) {
Timer iteration("epoch completed in");
double loss = 0;
unsigned n = 0;
for (auto& ci : corpus) {
copy(ci.begin(), ci.begin()+CONTEXT, in_c.begin());
ytrue = ci.back();
loss += as_scalar(cg.forward());
cg.backward();
++n;
sgd.update(1.0);
if (n == 2500) break;
}
loss /= n;
cerr << "E = " << loss << ' ';
}
}
<|endoftext|> |
<commit_before>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
#include <stdio.h>
#include <cv.h>
#include <highgui.h>
CvHaarClassifierCascade *cascade;
CvMemStorage *storage;
void detect(IplImage *img);
int main(int argc, char** argv)
{
CvCapture *capture;
IplImage *frame;
int input_resize_percent = 100;
if(argc < 3)
{
std::cout << "Usage " << argv[0] << " cascade.xml video.avi" << std::endl;
return 0;
}
if(argc == 4)
{
input_resize_percent = atoi(argv[3]);
std::cout << "Resizing to: " << input_resize_percent << "%" << std::endl;
}
cascade = (CvHaarClassifierCascade*) cvLoad(argv[1], 0, 0, 0);
storage = cvCreateMemStorage(0);
capture = cvCaptureFromAVI(argv[2]);
assert(cascade && storage && capture);
cvNamedWindow("video", 1);
IplImage* frame1 = cvQueryFrame(capture);
frame = cvCreateImage(cvSize((int)((frame1->width*input_resize_percent)/100) , (int)((frame1->height*input_resize_percent)/100)), frame1->depth, frame1->nChannels);
const int KEY_SPACE = 32;
const int KEY_ESC = 27;
int key = 0;
do
{
frame1 = cvQueryFrame(capture);
if(!frame1)
break;
cvResize(frame1, frame);
detect(frame);
key = cvWaitKey(10);
if(key == KEY_SPACE)
key = cvWaitKey(0);
if(key == KEY_ESC)
break;
}while(1);
cvDestroyAllWindows();
cvReleaseImage(&frame);
cvReleaseCapture(&capture);
cvReleaseHaarClassifierCascade(&cascade);
cvReleaseMemStorage(&storage);
return 0;
}
void detect(IplImage *img)
{
// cv::Mat img_mat(img);
// // Create ROI to desired area
// cv::Mat roi_image = img_mat(cv::Rect(0,img_mat.rows*1/3.5,img_mat.cols,img_mat.rows*2/3.5));
// imshow("roi_image",roi_image);
// IplImage ipl_img = img_mat;
cvSetImageROI(img, cvRect(0, img->height*1/3.5, img->width, img->height*2/3.5));
IplImage *img2 = cvCreateImage(cvGetSize(img),
img->depth,
img->nChannels);
cvCopy(img, img2, NULL);
cvResetImageROI(img);
//OpenCV C++ function
//CascadeClassifier::detectMultiScale(img_mat,cascade,)
CvSize img_size = cvGetSize(img2);
CvSeq *object = cvHaarDetectObjects(
img2,
cascade,
storage,
1.1, //1.1,//1.5, //-------------------SCALE FACTOR
1, //2 //------------------MIN NEIGHBOURS
0, //CV_HAAR_DO_CANNY_PRUNING
cvSize(0,0),//cvSize( 30,30), // ------MINSIZE
img_size //cvSize(70,70)//cvSize(640,480) //---------MAXSIZE
);
std::cout << "Total: " << object->total << " cars" << std::endl;
for(int i = 0 ; i < ( object ? object->total : 0 ) ; i++)
{
CvRect *r = (CvRect*)cvGetSeqElem(object, i);
cvRectangle(img2,
cvPoint(r->x, r->y),
cvPoint(r->x + r->width, r->y + r->height),
CV_RGB(255, 0, 0), 2, 8, 0);
}
cvShowImage("video", img2);
cvWaitKey(0);
}<commit_msg>Haarcascade: reduce ROI to get only the main road until the shield<commit_after>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
#include <stdio.h>
#include <cv.h>
#include <highgui.h>
CvHaarClassifierCascade *cascade;
CvMemStorage *storage;
void detect(IplImage *img);
int main(int argc, char** argv)
{
CvCapture *capture;
IplImage *frame;
int input_resize_percent = 100;
if(argc < 3)
{
std::cout << "Usage " << argv[0] << " cascade.xml video.avi" << std::endl;
return 0;
}
if(argc == 4)
{
input_resize_percent = atoi(argv[3]);
std::cout << "Resizing to: " << input_resize_percent << "%" << std::endl;
}
cascade = (CvHaarClassifierCascade*) cvLoad(argv[1], 0, 0, 0);
storage = cvCreateMemStorage(0);
capture = cvCaptureFromAVI(argv[2]);
assert(cascade && storage && capture);
cvNamedWindow("video", 1);
IplImage* frame1 = cvQueryFrame(capture);
frame = cvCreateImage(cvSize((int)((frame1->width*input_resize_percent)/100) , (int)((frame1->height*input_resize_percent)/100)), frame1->depth, frame1->nChannels);
const int KEY_SPACE = 32;
const int KEY_ESC = 27;
int key = 0;
do
{
frame1 = cvQueryFrame(capture);
if(!frame1)
break;
cvResize(frame1, frame);
detect(frame);
key = cvWaitKey(10);
if(key == KEY_SPACE)
key = cvWaitKey(0);
if(key == KEY_ESC)
break;
}while(1);
cvDestroyAllWindows();
cvReleaseImage(&frame);
cvReleaseCapture(&capture);
cvReleaseHaarClassifierCascade(&cascade);
cvReleaseMemStorage(&storage);
return 0;
}
void detect(IplImage *img)
{
// cv::Mat img_mat(img);
// // Create ROI to desired area
// cv::Mat roi_image = img_mat(cv::Rect(img_mat.cols*1/2.6,img_mat.rows*1/3.5,img_mat.cols,img_mat.rows*2/3.5));
// imshow("roi_image",roi_image);
// IplImage ipl_img = img_mat;
cvSetImageROI(img, cvRect(img->width*1/2.6, img->height*1/3.5, img->width, img->height*2/3.5));
IplImage *img2 = cvCreateImage(cvGetSize(img),
img->depth,
img->nChannels);
cvCopy(img, img2, NULL);
cvResetImageROI(img);
//OpenCV C++ function
//CascadeClassifier::detectMultiScale(img_mat,cascade,)
CvSize img_size = cvGetSize(img2);
CvSeq *object = cvHaarDetectObjects(
img2,
cascade,
storage,
1.1, //1.1,//1.5, //-------------------SCALE FACTOR
1, //2 //------------------MIN NEIGHBOURS
0, //CV_HAAR_DO_CANNY_PRUNING
cvSize(0,0),//cvSize( 30,30), // ------MINSIZE
img_size //cvSize(70,70)//cvSize(640,480) //---------MAXSIZE
);
std::cout << "Total: " << object->total << " cars" << std::endl;
for(int i = 0 ; i < ( object ? object->total : 0 ) ; i++)
{
CvRect *r = (CvRect*)cvGetSeqElem(object, i);
cvRectangle(img2,
cvPoint(r->x, r->y),
cvPoint(r->x + r->width, r->y + r->height),
CV_RGB(255, 0, 0), 2, 8, 0);
}
cvShowImage("video", img2);
cvWaitKey(0);
}<|endoftext|> |
<commit_before>/**
* Copyright 2016, Quickstep Research Group, Computer Sciences Department,
* University of Wisconsin—Madison.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
#ifndef QUICKSTEP_TRANSACTION_DIRECTED_GRAPH_HPP_
#define QUICKSTEP_TRANSACTION_DIRECTED_GRAPH_HPP_
#include <algorithm>
#include <memory>
#include <stack>
#include <unordered_set>
#include <vector>
#include "transaction/Transaction.hpp"
#include "utility/Macros.hpp"
#include "glog/logging.h"
namespace quickstep {
namespace transaction {
/** \addtogroup Transaction
* @{
*/
/**
* @brief Class for representing a directed graph. Vertices are transaction
* ids, edges are wait-for relations.
**/
class DirectedGraph {
public:
typedef std::uint64_t node_id;
/**
* @brief Default constructor
**/
DirectedGraph() {}
/**
* @brief Adds a new node to the graph with the given transaction id.
* It does not check whether the transaction id is valid or not.
* @warning Pointer ownership will pass to the graph, therefore it
* should not be deleted.
*
* @param data Pointer to the transaction id that will be contained
* in the node.
* @return Id of the newly created node.
**/
inline node_id addNodeUnchecked(transaction_id *data) {
nodes_.emplace_back(data);
return nodes_.size() - 1;
}
/**
* @brief Adds a new node to the graph with the given transaction id.
* It checks whether the transaction id is valid or not.
* @warning Pointer ownership will pass to the graph, therefore it
* should not be deleted.
*
* @param data Pointer to the transaction id that will be contained
* in the node.
* @return Id of the newly created node.
**/
inline node_id addNodeCheckExists(transaction_id *data) {
for (std::vector<DirectedGraphNode>::const_iterator
it = nodes_.cbegin(); it != nodes_.cend(); ++it) {
CHECK(*data != it->getData());
}
nodes_.emplace_back(data);
return nodes_.size() - 1;
}
/**
* @brief Adds an edge between nodes. It does not check whether the
* parameters are valid node ids.
* @warning Does not check arguments are legit. It may cause
* out of range errors.
*
* @param fromNode The node that edge is orginated.
* @param toNode The node that edge is ended.
**/
inline void addEdgeUnchecked(node_id from_node, node_id to_node) {
nodes_[from_node].addOutgoingEdge(to_node);
}
/**
* @brief Adds an edge between nodes. It checks whether the
* parameters are valid node ids.
*
* @param fromNode The node that edge is orginated.
* @param toNode The node that edge is ended.
**/
inline void addEdgeCheckExists(node_id from_node, node_id to_node) {
CHECK(from_node < getNumNodes() && to_node < getNumNodes());
nodes_[from_node].addOutgoingEdge(to_node);
}
/**
* @brief Check whether there is a directed edge.
* @warning When parameters are not valid ids, it may cause
* out of range errors.
*
* @param fromNode Id of the node that edge is originated from.
* @param toNode Id of the node that edge is ended.
* @return True if there is an edge, false otherwise.
**/
inline bool hasEdge(node_id from_node, node_id to_node) const {
DCHECK(from_node < getNumNodes() && to_node < getNumNodes());
return nodes_[from_node].hasOutgoingEdge(to_node);
}
/**
* @brief Get data (transaction id) contained in the node.
* @warning Does not check index validity.
*
* @param node Id of the node that the data is got from.
* @return Id of the transaction that this node contains.
**/
inline transaction_id getDataFromNode(node_id node) const {
return nodes_[node].getData();
}
/**
* @brief Calculate how many nodes the graph has.
*
* @return The number of nodes the graph has.
**/
inline std::size_t getNumNodes() const {
return nodes_.size();
}
/**
* @brief Gives the node ids that this node has edges to.
*
* @param id Id of the corresponding node.
* @return Vector of node ids that id has edges to.
**/
inline std::vector<node_id> getAdjacentNodes(node_id id) const {
return nodes_[id].getOutgoingEdges();
}
private:
// Class for representing a graph node.
class DirectedGraphNode {
public:
explicit DirectedGraphNode(transaction_id *data)
: data_(data) {}
inline void addOutgoingEdge(node_id to_node) {
outgoing_edges_.insert(to_node);
}
inline bool hasOutgoingEdge(node_id to_node) const {
return outgoing_edges_.count(to_node) == 1;
}
inline std::vector<node_id> getOutgoingEdges() const {
// TODO(hakan): Benchmark this version and the alternative which the
// function returns const reference and the uniqueness
// is imposed in the outgoing_edges_ as a vector.
std::vector<node_id> result;
std::copy(outgoing_edges_.begin(), outgoing_edges_.end(),
std::back_inserter(result));
return result;
}
inline transaction_id getData() const {
return *(data_.get());
}
private:
// Owner pointer to transaction id.
std::unique_ptr<transaction_id> data_;
// Endpoint nodes of outgoing edges originated from this node.
std::unordered_set<node_id> outgoing_edges_;
};
// The list of nodes that are created. NodeId is the index of that
// node in this buffer.
std::vector<DirectedGraphNode> nodes_;
DISALLOW_COPY_AND_ASSIGN(DirectedGraph);
};
/** @} */
} // namespace transaction
} // namespace quickstep
#endif // QUICKSTEP_TRANSACTION_DIRECTED_GRAPH_HPP_
<commit_msg>Added DCHECK to getDataFromNode() in DirectedGraph class.<commit_after>/**
* Copyright 2016, Quickstep Research Group, Computer Sciences Department,
* University of Wisconsin—Madison.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
#ifndef QUICKSTEP_TRANSACTION_DIRECTED_GRAPH_HPP_
#define QUICKSTEP_TRANSACTION_DIRECTED_GRAPH_HPP_
#include <algorithm>
#include <memory>
#include <stack>
#include <unordered_set>
#include <vector>
#include "transaction/Transaction.hpp"
#include "utility/Macros.hpp"
#include "glog/logging.h"
namespace quickstep {
namespace transaction {
/** \addtogroup Transaction
* @{
*/
/**
* @brief Class for representing a directed graph. Vertices are transaction
* ids, edges are wait-for relations.
**/
class DirectedGraph {
public:
typedef std::uint64_t node_id;
/**
* @brief Default constructor
**/
DirectedGraph() {}
/**
* @brief Adds a new node to the graph with the given transaction id.
* It does not check whether the transaction id is valid or not.
* @warning Pointer ownership will pass to the graph, therefore it
* should not be deleted.
*
* @param data Pointer to the transaction id that will be contained
* in the node.
* @return Id of the newly created node.
**/
inline node_id addNodeUnchecked(transaction_id *data) {
nodes_.emplace_back(data);
return nodes_.size() - 1;
}
/**
* @brief Adds a new node to the graph with the given transaction id.
* It checks whether the transaction id is valid or not.
* @warning Pointer ownership will pass to the graph, therefore it
* should not be deleted.
*
* @param data Pointer to the transaction id that will be contained
* in the node.
* @return Id of the newly created node.
**/
inline node_id addNodeCheckExists(transaction_id *data) {
for (std::vector<DirectedGraphNode>::const_iterator
it = nodes_.cbegin(); it != nodes_.cend(); ++it) {
CHECK(*data != it->getData());
}
nodes_.emplace_back(data);
return nodes_.size() - 1;
}
/**
* @brief Adds an edge between nodes. It does not check whether the
* parameters are valid node ids.
* @warning Does not check arguments are legit. It may cause
* out of range errors.
*
* @param fromNode The node that edge is orginated.
* @param toNode The node that edge is ended.
**/
inline void addEdgeUnchecked(node_id from_node, node_id to_node) {
nodes_[from_node].addOutgoingEdge(to_node);
}
/**
* @brief Adds an edge between nodes. It checks whether the
* parameters are valid node ids.
*
* @param fromNode The node that edge is orginated.
* @param toNode The node that edge is ended.
**/
inline void addEdgeCheckExists(node_id from_node, node_id to_node) {
CHECK(from_node < getNumNodes() && to_node < getNumNodes());
nodes_[from_node].addOutgoingEdge(to_node);
}
/**
* @brief Check whether there is a directed edge.
* @warning When parameters are not valid ids, it may cause
* out of range errors.
*
* @param fromNode Id of the node that edge is originated from.
* @param toNode Id of the node that edge is ended.
* @return True if there is an edge, false otherwise.
**/
inline bool hasEdge(node_id from_node, node_id to_node) const {
DCHECK(from_node < getNumNodes() && to_node < getNumNodes());
return nodes_[from_node].hasOutgoingEdge(to_node);
}
/**
* @brief Get data (transaction id) contained in the node.
*
* @param node Id of the node that the data is got from.
* @return Id of the transaction that this node contains.
**/
inline transaction_id getDataFromNode(node_id node) const {
DCHECK(node < getNumNodes());
return nodes_[node].getData();
}
/**
* @brief Calculate how many nodes the graph has.
*
* @return The number of nodes the graph has.
**/
inline std::size_t getNumNodes() const {
return nodes_.size();
}
/**
* @brief Gives the node ids that this node has edges to.
*
* @param id Id of the corresponding node.
* @return Vector of node ids that id has edges to.
**/
inline std::vector<node_id> getAdjacentNodes(node_id id) const {
return nodes_[id].getOutgoingEdges();
}
private:
// Class for representing a graph node.
class DirectedGraphNode {
public:
explicit DirectedGraphNode(transaction_id *data)
: data_(data) {}
inline void addOutgoingEdge(node_id to_node) {
outgoing_edges_.insert(to_node);
}
inline bool hasOutgoingEdge(node_id to_node) const {
return outgoing_edges_.count(to_node) == 1;
}
inline std::vector<node_id> getOutgoingEdges() const {
// TODO(hakan): Benchmark this version and the alternative which the
// function returns const reference and the uniqueness
// is imposed in the outgoing_edges_ as a vector.
std::vector<node_id> result;
std::copy(outgoing_edges_.begin(), outgoing_edges_.end(),
std::back_inserter(result));
return result;
}
inline transaction_id getData() const {
return *(data_.get());
}
private:
// Owner pointer to transaction id.
std::unique_ptr<transaction_id> data_;
// Endpoint nodes of outgoing edges originated from this node.
std::unordered_set<node_id> outgoing_edges_;
};
// The list of nodes that are created. NodeId is the index of that
// node in this buffer.
std::vector<DirectedGraphNode> nodes_;
DISALLOW_COPY_AND_ASSIGN(DirectedGraph);
};
/** @} */
} // namespace transaction
} // namespace quickstep
#endif // QUICKSTEP_TRANSACTION_DIRECTED_GRAPH_HPP_
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/system_wrappers/interface/atomic32.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/event_wrapper.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/voice_engine/test/auto_test/fixtures/after_streaming_fixture.h"
#include "webrtc/voice_engine/test/auto_test/voe_standard_test.h"
class TestRtpObserver : public webrtc::VoERTPObserver {
public:
TestRtpObserver()
: crit_(voetest::CriticalSectionWrapper::CreateCriticalSection()),
changed_ssrc_event_(voetest::EventWrapper::Create()) {}
virtual ~TestRtpObserver() {}
virtual void OnIncomingCSRCChanged(int channel,
unsigned int CSRC,
bool added) {}
virtual void OnIncomingSSRCChanged(int channel,
unsigned int SSRC);
void WaitForChangedSsrc() {
// 10 seconds should be enough.
EXPECT_EQ(voetest::kEventSignaled, changed_ssrc_event_->Wait(10*1000));
changed_ssrc_event_->Reset();
}
void SetIncomingSsrc(unsigned int ssrc) {
voetest::CriticalSectionScoped lock(crit_.get());
incoming_ssrc_ = ssrc;
}
public:
voetest::scoped_ptr<voetest::CriticalSectionWrapper> crit_;
unsigned int incoming_ssrc_;
voetest::scoped_ptr<voetest::EventWrapper> changed_ssrc_event_;
};
void TestRtpObserver::OnIncomingSSRCChanged(int channel,
unsigned int SSRC) {
char msg[128];
sprintf(msg, "\n=> OnIncomingSSRCChanged(channel=%d, SSRC=%u)\n", channel,
SSRC);
TEST_LOG("%s", msg);
{
voetest::CriticalSectionScoped lock(crit_.get());
if (incoming_ssrc_ == SSRC)
changed_ssrc_event_->Set();
}
}
class RtcpAppHandler : public webrtc::VoERTCPObserver {
public:
RtcpAppHandler() : length_in_bytes_(0), sub_type_(0), name_(0) {}
void OnApplicationDataReceived(int channel,
unsigned char sub_type,
unsigned int name,
const unsigned char* data,
unsigned short length_in_bytes);
void Reset();
~RtcpAppHandler() {}
unsigned short length_in_bytes_;
unsigned char data_[256];
unsigned char sub_type_;
unsigned int name_;
};
static const char* const RTCP_CNAME = "Whatever";
class RtpRtcpTest : public AfterStreamingFixture {
protected:
void SetUp() {
// We need a second channel for this test, so set it up.
second_channel_ = voe_base_->CreateChannel();
EXPECT_GE(second_channel_, 0);
transport_ = new LoopBackTransport(voe_network_);
EXPECT_EQ(0, voe_network_->RegisterExternalTransport(second_channel_,
*transport_));
EXPECT_EQ(0, voe_base_->StartReceive(second_channel_));
EXPECT_EQ(0, voe_base_->StartPlayout(second_channel_));
EXPECT_EQ(0, voe_rtp_rtcp_->SetLocalSSRC(second_channel_, 5678));
EXPECT_EQ(0, voe_base_->StartSend(second_channel_));
// We'll set up the RTCP CNAME and SSRC to something arbitrary here.
voe_rtp_rtcp_->SetRTCP_CNAME(channel_, RTCP_CNAME);
}
void TearDown() {
EXPECT_EQ(0, voe_network_->DeRegisterExternalTransport(second_channel_));
voe_base_->DeleteChannel(second_channel_);
delete transport_;
}
int second_channel_;
LoopBackTransport* transport_;
};
void RtcpAppHandler::OnApplicationDataReceived(
const int /*channel*/, unsigned char sub_type,
unsigned int name, const unsigned char* data,
unsigned short length_in_bytes) {
length_in_bytes_ = length_in_bytes;
memcpy(data_, &data[0], length_in_bytes);
sub_type_ = sub_type;
name_ = name;
}
void RtcpAppHandler::Reset() {
length_in_bytes_ = 0;
memset(data_, 0, sizeof(data_));
sub_type_ = 0;
name_ = 0;
}
TEST_F(RtpRtcpTest, RemoteRtcpCnameHasPropagatedToRemoteSide) {
if (!FLAGS_include_timing_dependent_tests) {
TEST_LOG("Skipping test - running in slow execution environment...\n");
return;
}
// We need to sleep a bit here for the name to propagate. For instance,
// 200 milliseconds is not enough, so we'll go with one second here.
Sleep(1000);
char char_buffer[256];
voe_rtp_rtcp_->GetRemoteRTCP_CNAME(channel_, char_buffer);
EXPECT_STREQ(RTCP_CNAME, char_buffer);
}
// Flakily hangs on Linux. code.google.com/p/webrtc/issues/detail?id=2178.
TEST_F(RtpRtcpTest, DISABLED_ON_LINUX(SSRCPropagatesCorrectly)) {
unsigned int local_ssrc = 1234;
EXPECT_EQ(0, voe_base_->StopSend(channel_));
EXPECT_EQ(0, voe_rtp_rtcp_->SetLocalSSRC(channel_, local_ssrc));
EXPECT_EQ(0, voe_base_->StartSend(channel_));
Sleep(1000);
unsigned int ssrc;
EXPECT_EQ(0, voe_rtp_rtcp_->GetLocalSSRC(channel_, ssrc));
EXPECT_EQ(local_ssrc, ssrc);
EXPECT_EQ(0, voe_rtp_rtcp_->GetRemoteSSRC(channel_, ssrc));
EXPECT_EQ(local_ssrc, ssrc);
}
TEST_F(RtpRtcpTest, RtcpApplicationDefinedPacketsCanBeSentAndReceived) {
RtcpAppHandler rtcp_app_handler;
EXPECT_EQ(0, voe_rtp_rtcp_->RegisterRTCPObserver(
channel_, rtcp_app_handler));
// Send data aligned to 32 bytes.
const char* data = "application-dependent data------";
unsigned short data_length = strlen(data);
unsigned int data_name = 0x41424344; // 'ABCD' in ascii
unsigned char data_subtype = 1;
EXPECT_EQ(0, voe_rtp_rtcp_->SendApplicationDefinedRTCPPacket(
channel_, data_subtype, data_name, data, data_length));
// Ensure the RTP-RTCP process gets scheduled.
Sleep(1000);
// Ensure we received the data in the callback.
ASSERT_EQ(data_length, rtcp_app_handler.length_in_bytes_);
EXPECT_EQ(0, memcmp(data, rtcp_app_handler.data_, data_length));
EXPECT_EQ(data_name, rtcp_app_handler.name_);
EXPECT_EQ(data_subtype, rtcp_app_handler.sub_type_);
EXPECT_EQ(0, voe_rtp_rtcp_->DeRegisterRTCPObserver(channel_));
}
TEST_F(RtpRtcpTest, DisabledRtcpObserverDoesNotReceiveData) {
RtcpAppHandler rtcp_app_handler;
EXPECT_EQ(0, voe_rtp_rtcp_->RegisterRTCPObserver(
channel_, rtcp_app_handler));
// Put observer in a known state before de-registering.
rtcp_app_handler.Reset();
EXPECT_EQ(0, voe_rtp_rtcp_->DeRegisterRTCPObserver(channel_));
const char* data = "whatever";
EXPECT_EQ(0, voe_rtp_rtcp_->SendApplicationDefinedRTCPPacket(
channel_, 1, 0x41424344, data, strlen(data)));
// Ensure the RTP-RTCP process gets scheduled.
Sleep(1000);
// Ensure we received no data.
EXPECT_EQ(0u, rtcp_app_handler.name_);
EXPECT_EQ(0u, rtcp_app_handler.sub_type_);
}
TEST_F(RtpRtcpTest, InsertExtraRTPPacketDealsWithInvalidArguments) {
const char payload_data[8] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' };
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
-1, 0, false, payload_data, 8)) <<
"Should reject: invalid channel.";
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, -1, false, payload_data, 8)) <<
"Should reject: invalid payload type.";
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, 128, false, payload_data, 8)) <<
"Should reject: invalid payload type.";
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, 99, false, NULL, 8)) <<
"Should reject: bad pointer.";
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, 99, false, payload_data, 1500 - 28 + 1)) <<
"Should reject: invalid size.";
}
TEST_F(RtpRtcpTest, DISABLED_ON_WIN(CanTransmitExtraRtpPacketsWithoutError)) {
const char payload_data[8] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' };
for (int i = 0; i < 128; ++i) {
// Try both with and without the marker bit set
EXPECT_EQ(0, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, i, false, payload_data, 8));
EXPECT_EQ(0, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, i, true, payload_data, 8));
}
}
// TODO(xians, phoglund): Re-enable when issue 372 is resolved.
TEST_F(RtpRtcpTest, DISABLED_CanCreateRtpDumpFilesWithoutError) {
// Create two RTP dump files (3 seconds long). You can verify these after
// the test using rtpplay or NetEqRTPplay if you like.
std::string output_path = webrtc::test::OutputPath();
std::string incoming_filename = output_path + "dump_in_3sec.rtp";
std::string outgoing_filename = output_path + "dump_out_3sec.rtp";
EXPECT_EQ(0, voe_rtp_rtcp_->StartRTPDump(
channel_, incoming_filename.c_str(), webrtc::kRtpIncoming));
EXPECT_EQ(0, voe_rtp_rtcp_->StartRTPDump(
channel_, outgoing_filename.c_str(), webrtc::kRtpOutgoing));
Sleep(3000);
EXPECT_EQ(0, voe_rtp_rtcp_->StopRTPDump(channel_, webrtc::kRtpIncoming));
EXPECT_EQ(0, voe_rtp_rtcp_->StopRTPDump(channel_, webrtc::kRtpOutgoing));
}
TEST_F(RtpRtcpTest, ObserverGetsNotifiedOnSsrcChange) {
TestRtpObserver rtcp_observer;
EXPECT_EQ(0, voe_rtp_rtcp_->RegisterRTPObserver(
channel_, rtcp_observer));
unsigned int new_ssrc = 7777;
EXPECT_EQ(0, voe_base_->StopSend(channel_));
rtcp_observer.SetIncomingSsrc(new_ssrc);
EXPECT_EQ(0, voe_rtp_rtcp_->SetLocalSSRC(channel_, new_ssrc));
EXPECT_EQ(0, voe_base_->StartSend(channel_));
rtcp_observer.WaitForChangedSsrc();
// Now try another SSRC.
unsigned int newer_ssrc = 1717;
EXPECT_EQ(0, voe_base_->StopSend(channel_));
rtcp_observer.SetIncomingSsrc(newer_ssrc);
EXPECT_EQ(0, voe_rtp_rtcp_->SetLocalSSRC(channel_, newer_ssrc));
EXPECT_EQ(0, voe_base_->StartSend(channel_));
rtcp_observer.WaitForChangedSsrc();
EXPECT_EQ(0, voe_rtp_rtcp_->DeRegisterRTPObserver(channel_));
}
<commit_msg>Disables RtpRtcpTest.CanTransmitExtraRtpPacketsWithoutError as it flakily breaks the waterfall. See http://chromegw.corp.google.com/i/client.webrtc/builders/Linux64%20Release%20%5Blarge%20tests%5D/builds/99/steps/voe_auto_test/logs/stdio the cl triggering it was a no-change (disabled some other broken tests).<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/system_wrappers/interface/atomic32.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/event_wrapper.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/voice_engine/test/auto_test/fixtures/after_streaming_fixture.h"
#include "webrtc/voice_engine/test/auto_test/voe_standard_test.h"
class TestRtpObserver : public webrtc::VoERTPObserver {
public:
TestRtpObserver()
: crit_(voetest::CriticalSectionWrapper::CreateCriticalSection()),
changed_ssrc_event_(voetest::EventWrapper::Create()) {}
virtual ~TestRtpObserver() {}
virtual void OnIncomingCSRCChanged(int channel,
unsigned int CSRC,
bool added) {}
virtual void OnIncomingSSRCChanged(int channel,
unsigned int SSRC);
void WaitForChangedSsrc() {
// 10 seconds should be enough.
EXPECT_EQ(voetest::kEventSignaled, changed_ssrc_event_->Wait(10*1000));
changed_ssrc_event_->Reset();
}
void SetIncomingSsrc(unsigned int ssrc) {
voetest::CriticalSectionScoped lock(crit_.get());
incoming_ssrc_ = ssrc;
}
public:
voetest::scoped_ptr<voetest::CriticalSectionWrapper> crit_;
unsigned int incoming_ssrc_;
voetest::scoped_ptr<voetest::EventWrapper> changed_ssrc_event_;
};
void TestRtpObserver::OnIncomingSSRCChanged(int channel,
unsigned int SSRC) {
char msg[128];
sprintf(msg, "\n=> OnIncomingSSRCChanged(channel=%d, SSRC=%u)\n", channel,
SSRC);
TEST_LOG("%s", msg);
{
voetest::CriticalSectionScoped lock(crit_.get());
if (incoming_ssrc_ == SSRC)
changed_ssrc_event_->Set();
}
}
class RtcpAppHandler : public webrtc::VoERTCPObserver {
public:
RtcpAppHandler() : length_in_bytes_(0), sub_type_(0), name_(0) {}
void OnApplicationDataReceived(int channel,
unsigned char sub_type,
unsigned int name,
const unsigned char* data,
unsigned short length_in_bytes);
void Reset();
~RtcpAppHandler() {}
unsigned short length_in_bytes_;
unsigned char data_[256];
unsigned char sub_type_;
unsigned int name_;
};
static const char* const RTCP_CNAME = "Whatever";
class RtpRtcpTest : public AfterStreamingFixture {
protected:
void SetUp() {
// We need a second channel for this test, so set it up.
second_channel_ = voe_base_->CreateChannel();
EXPECT_GE(second_channel_, 0);
transport_ = new LoopBackTransport(voe_network_);
EXPECT_EQ(0, voe_network_->RegisterExternalTransport(second_channel_,
*transport_));
EXPECT_EQ(0, voe_base_->StartReceive(second_channel_));
EXPECT_EQ(0, voe_base_->StartPlayout(second_channel_));
EXPECT_EQ(0, voe_rtp_rtcp_->SetLocalSSRC(second_channel_, 5678));
EXPECT_EQ(0, voe_base_->StartSend(second_channel_));
// We'll set up the RTCP CNAME and SSRC to something arbitrary here.
voe_rtp_rtcp_->SetRTCP_CNAME(channel_, RTCP_CNAME);
}
void TearDown() {
EXPECT_EQ(0, voe_network_->DeRegisterExternalTransport(second_channel_));
voe_base_->DeleteChannel(second_channel_);
delete transport_;
}
int second_channel_;
LoopBackTransport* transport_;
};
void RtcpAppHandler::OnApplicationDataReceived(
const int /*channel*/, unsigned char sub_type,
unsigned int name, const unsigned char* data,
unsigned short length_in_bytes) {
length_in_bytes_ = length_in_bytes;
memcpy(data_, &data[0], length_in_bytes);
sub_type_ = sub_type;
name_ = name;
}
void RtcpAppHandler::Reset() {
length_in_bytes_ = 0;
memset(data_, 0, sizeof(data_));
sub_type_ = 0;
name_ = 0;
}
TEST_F(RtpRtcpTest, RemoteRtcpCnameHasPropagatedToRemoteSide) {
if (!FLAGS_include_timing_dependent_tests) {
TEST_LOG("Skipping test - running in slow execution environment...\n");
return;
}
// We need to sleep a bit here for the name to propagate. For instance,
// 200 milliseconds is not enough, so we'll go with one second here.
Sleep(1000);
char char_buffer[256];
voe_rtp_rtcp_->GetRemoteRTCP_CNAME(channel_, char_buffer);
EXPECT_STREQ(RTCP_CNAME, char_buffer);
}
// Flakily hangs on Linux. code.google.com/p/webrtc/issues/detail?id=2178.
TEST_F(RtpRtcpTest, DISABLED_ON_LINUX(SSRCPropagatesCorrectly)) {
unsigned int local_ssrc = 1234;
EXPECT_EQ(0, voe_base_->StopSend(channel_));
EXPECT_EQ(0, voe_rtp_rtcp_->SetLocalSSRC(channel_, local_ssrc));
EXPECT_EQ(0, voe_base_->StartSend(channel_));
Sleep(1000);
unsigned int ssrc;
EXPECT_EQ(0, voe_rtp_rtcp_->GetLocalSSRC(channel_, ssrc));
EXPECT_EQ(local_ssrc, ssrc);
EXPECT_EQ(0, voe_rtp_rtcp_->GetRemoteSSRC(channel_, ssrc));
EXPECT_EQ(local_ssrc, ssrc);
}
TEST_F(RtpRtcpTest, RtcpApplicationDefinedPacketsCanBeSentAndReceived) {
RtcpAppHandler rtcp_app_handler;
EXPECT_EQ(0, voe_rtp_rtcp_->RegisterRTCPObserver(
channel_, rtcp_app_handler));
// Send data aligned to 32 bytes.
const char* data = "application-dependent data------";
unsigned short data_length = strlen(data);
unsigned int data_name = 0x41424344; // 'ABCD' in ascii
unsigned char data_subtype = 1;
EXPECT_EQ(0, voe_rtp_rtcp_->SendApplicationDefinedRTCPPacket(
channel_, data_subtype, data_name, data, data_length));
// Ensure the RTP-RTCP process gets scheduled.
Sleep(1000);
// Ensure we received the data in the callback.
ASSERT_EQ(data_length, rtcp_app_handler.length_in_bytes_);
EXPECT_EQ(0, memcmp(data, rtcp_app_handler.data_, data_length));
EXPECT_EQ(data_name, rtcp_app_handler.name_);
EXPECT_EQ(data_subtype, rtcp_app_handler.sub_type_);
EXPECT_EQ(0, voe_rtp_rtcp_->DeRegisterRTCPObserver(channel_));
}
TEST_F(RtpRtcpTest, DisabledRtcpObserverDoesNotReceiveData) {
RtcpAppHandler rtcp_app_handler;
EXPECT_EQ(0, voe_rtp_rtcp_->RegisterRTCPObserver(
channel_, rtcp_app_handler));
// Put observer in a known state before de-registering.
rtcp_app_handler.Reset();
EXPECT_EQ(0, voe_rtp_rtcp_->DeRegisterRTCPObserver(channel_));
const char* data = "whatever";
EXPECT_EQ(0, voe_rtp_rtcp_->SendApplicationDefinedRTCPPacket(
channel_, 1, 0x41424344, data, strlen(data)));
// Ensure the RTP-RTCP process gets scheduled.
Sleep(1000);
// Ensure we received no data.
EXPECT_EQ(0u, rtcp_app_handler.name_);
EXPECT_EQ(0u, rtcp_app_handler.sub_type_);
}
TEST_F(RtpRtcpTest, InsertExtraRTPPacketDealsWithInvalidArguments) {
const char payload_data[8] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' };
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
-1, 0, false, payload_data, 8)) <<
"Should reject: invalid channel.";
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, -1, false, payload_data, 8)) <<
"Should reject: invalid payload type.";
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, 128, false, payload_data, 8)) <<
"Should reject: invalid payload type.";
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, 99, false, NULL, 8)) <<
"Should reject: bad pointer.";
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, 99, false, payload_data, 1500 - 28 + 1)) <<
"Should reject: invalid size.";
}
TEST_F(RtpRtcpTest, DISABLED_CanTransmitExtraRtpPacketsWithoutError) {
const char payload_data[8] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' };
for (int i = 0; i < 128; ++i) {
// Try both with and without the marker bit set
EXPECT_EQ(0, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, i, false, payload_data, 8));
EXPECT_EQ(0, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, i, true, payload_data, 8));
}
}
// TODO(xians, phoglund): Re-enable when issue 372 is resolved.
TEST_F(RtpRtcpTest, DISABLED_CanCreateRtpDumpFilesWithoutError) {
// Create two RTP dump files (3 seconds long). You can verify these after
// the test using rtpplay or NetEqRTPplay if you like.
std::string output_path = webrtc::test::OutputPath();
std::string incoming_filename = output_path + "dump_in_3sec.rtp";
std::string outgoing_filename = output_path + "dump_out_3sec.rtp";
EXPECT_EQ(0, voe_rtp_rtcp_->StartRTPDump(
channel_, incoming_filename.c_str(), webrtc::kRtpIncoming));
EXPECT_EQ(0, voe_rtp_rtcp_->StartRTPDump(
channel_, outgoing_filename.c_str(), webrtc::kRtpOutgoing));
Sleep(3000);
EXPECT_EQ(0, voe_rtp_rtcp_->StopRTPDump(channel_, webrtc::kRtpIncoming));
EXPECT_EQ(0, voe_rtp_rtcp_->StopRTPDump(channel_, webrtc::kRtpOutgoing));
}
TEST_F(RtpRtcpTest, ObserverGetsNotifiedOnSsrcChange) {
TestRtpObserver rtcp_observer;
EXPECT_EQ(0, voe_rtp_rtcp_->RegisterRTPObserver(
channel_, rtcp_observer));
unsigned int new_ssrc = 7777;
EXPECT_EQ(0, voe_base_->StopSend(channel_));
rtcp_observer.SetIncomingSsrc(new_ssrc);
EXPECT_EQ(0, voe_rtp_rtcp_->SetLocalSSRC(channel_, new_ssrc));
EXPECT_EQ(0, voe_base_->StartSend(channel_));
rtcp_observer.WaitForChangedSsrc();
// Now try another SSRC.
unsigned int newer_ssrc = 1717;
EXPECT_EQ(0, voe_base_->StopSend(channel_));
rtcp_observer.SetIncomingSsrc(newer_ssrc);
EXPECT_EQ(0, voe_rtp_rtcp_->SetLocalSSRC(channel_, newer_ssrc));
EXPECT_EQ(0, voe_base_->StartSend(channel_));
rtcp_observer.WaitForChangedSsrc();
EXPECT_EQ(0, voe_rtp_rtcp_->DeRegisterRTPObserver(channel_));
}
<|endoftext|> |
<commit_before>#ifndef STREAM_H_
#define STREAM_H_
#include "dtypes.hpp"
#include "server.hpp"
#include "Decerealiser.hpp"
#include <vector>
#include <memory>
#include <cassert>
class MqttStream {
public:
MqttStream(int size):
_buffer(size),
_scratch(size),
_begin{_buffer.begin()}
{
}
auto begin() noexcept { return _begin; }
auto readableData() noexcept { return _buffer.data() + std::distance(_buffer.begin(), _begin); }
auto readableDataSize() noexcept { return std::distance(_begin, _buffer.end()); }
template<typename C>
void handleMessages(int numBytes, MqttServer<C>& server, C& connection) {
auto slice = gsl::as_span(_buffer.data(), std::distance(_buffer.begin(), _begin) + numBytes);
auto totLen = totalLength(slice);
assert(totLen > 0);
while(slice.length() >= totLen) {
server.newMessage(connection, slice);
slice = slice.sub(totLen);
totLen = totalLength(slice);
}
//shift everything to the beginning
copy(slice.cbegin(), slice.cend(), _scratch.begin());
copy(_scratch.cbegin(), _scratch.cend(), _buffer.begin());
_begin = _buffer.begin() + slice.size();
}
private:
std::vector<ubyte> _buffer;
std::vector<ubyte> _scratch;
decltype(_buffer)::iterator _begin;
static int remainingLength(gsl::span<ubyte> bytes) noexcept {
Decerealiser dec{bytes};
return dec.create<MqttFixedHeader>().remaining;
}
static int totalLength(gsl::span<ubyte> bytes) noexcept {
return bytes.size() > MqttFixedHeader::SIZE
? remainingLength(bytes) + MqttFixedHeader::SIZE
: MqttFixedHeader::SIZE;
}
};
#endif // STREAM_H_
<commit_msg>Bug fix for stream<commit_after>#ifndef STREAM_H_
#define STREAM_H_
#include "dtypes.hpp"
#include "server.hpp"
#include "Decerealiser.hpp"
#include <vector>
#include <memory>
#include <cassert>
class MqttStream {
public:
MqttStream(int size):
_buffer(size),
_scratch(size),
_begin{_buffer.begin()}
{
}
auto begin() noexcept { return _begin; }
auto readableData() noexcept { return _buffer.data() + std::distance(_buffer.begin(), _begin); }
auto readableDataSize() noexcept { return std::distance(_begin, _buffer.end()); }
template<typename C>
void handleMessages(int numBytes, MqttServer<C>& server, C& connection) {
auto slice = gsl::as_span(_buffer.data(), std::distance(_buffer.begin(), _begin) + numBytes);
auto totLen = totalLength(slice);
assert(totLen > 0);
while(slice.length() >= totLen) {
const auto msg = slice.sub(0, totLen);
server.newMessage(connection, msg);
slice = slice.sub(totLen);
totLen = totalLength(slice);
}
//shift everything to the beginning
copy(slice.cbegin(), slice.cend(), _scratch.begin());
copy(_scratch.cbegin(), _scratch.cend(), _buffer.begin());
_begin = _buffer.begin() + slice.size();
}
private:
std::vector<ubyte> _buffer;
std::vector<ubyte> _scratch;
decltype(_buffer)::iterator _begin;
static int remainingLength(gsl::span<ubyte> bytes) noexcept {
Decerealiser dec{bytes};
return dec.create<MqttFixedHeader>().remaining;
}
static int totalLength(gsl::span<ubyte> bytes) noexcept {
return bytes.size() > MqttFixedHeader::SIZE
? remainingLength(bytes) + MqttFixedHeader::SIZE
: MqttFixedHeader::SIZE;
}
};
#endif // STREAM_H_
<|endoftext|> |
<commit_before>/*
pvsops.c: pvs and other spectral-based opcodes
Copyright (C) 2017 Victor Lazzarini
This file is part of Csound.
The Csound 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.
Csound 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 Csound; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
*/
#include <algorithm>
#include <plugin.h>
struct PVTrace : csnd::FPlugin<1, 2> {
csnd::AuxMem<float> amps;
static constexpr char const *otypes = "f";
static constexpr char const *itypes = "fk";
int init() {
if (inargs.fsig_data(0).isSliding())
return csound->init_error("sliding not supported");
if (inargs.fsig_data(0).fsig_format() != csnd::fsig_format::pvs &&
inargs.fsig_data(0).fsig_format() != csnd::fsig_format::polar)
return csound->init_error("fsig format not supported");
amps.allocate(csound, inargs.fsig_data(0).nbins());
csnd::Fsig &fout = outargs.fsig_data(0);
fout.init(csound, inargs.fsig_data(0));
framecount = 0;
return OK;
}
int kperf() {
csnd::pv_frame &fin = inargs.fsig_data(0);
csnd::pv_frame &fout = outargs.fsig_data(0);
if (framecount < fin.count()) {
int n = fin.len() - (int)inargs[1];
float thrsh;
std::transform(fin.begin(), fin.end(), amps.begin(),
[](csnd::pv_bin f) { return f.amp(); });
std::nth_element(amps.begin(), amps.begin() + n, amps.end());
thrsh = amps[n];
std::transform(fin.begin(), fin.end(), fout.begin(),
[thrsh](csnd::pv_bin f) {
return f.amp() >= thrsh ? f : csnd::pv_bin();
});
framecount = fout.count(fin.count());
}
return OK;
}
};
struct binamp {
int bin;
float amp;
};
struct PVTrace2 : csnd::FPlugin<2, 5> {
csnd::AuxMem<float> amps;
csnd::AuxMem<binamp> binlist;
static constexpr char const *otypes = "fk[]";
static constexpr char const *itypes = "fkopp";
int init() {
csnd::Vector<MYFLT> &bins = outargs.vector_data<MYFLT>(1);
if (inargs.fsig_data(0).isSliding())
return csound->init_error("sliding not supported");
if (inargs.fsig_data(0).fsig_format() != csnd::fsig_format::pvs &&
inargs.fsig_data(0).fsig_format() != csnd::fsig_format::polar)
return csound->init_error("fsig format not supported");
amps.allocate(csound, inargs.fsig_data(0).nbins());
binlist.allocate(csound, inargs.fsig_data(0).nbins());
csnd::Fsig &fout = outargs.fsig_data(0);
fout.init(csound, inargs.fsig_data(0));
bins.init(csound, inargs.fsig_data(0).nbins());
framecount = 0;
return OK;
}
int kperf() {
csnd::pv_frame &fin = inargs.fsig_data(0);
csnd::pv_frame &fout = outargs.fsig_data(0);
csnd::Vector<MYFLT> &bins = outargs.vector_data<MYFLT>(1);
csnd::AuxMem<binamp> &mbins = binlist;
if (framecount < fin.count()) {
int n = fin.len() - (int)inargs[1];
float thrsh;
int cnt = 0;
int bin = 0;
int start = (int) inargs[3];
int end = (int) inargs[4];
std::transform(fin.begin() + start,
end ? fin.begin() +
(end <= fin.len() ? end : fin.len()) :
fin.end(), amps.begin(),
[](csnd::pv_bin f) { return f.amp(); });
std::nth_element(amps.begin(), amps.begin() + n, amps.end());
thrsh = amps[n];
std::transform(fin.begin(), fin.end(), fout.begin(),
[thrsh, &mbins, &cnt, &bin](csnd::pv_bin f) {
if(f.amp() >= thrsh) {
mbins[cnt].bin = bin++;
mbins[cnt++].amp = f.amp();
return f;
}
else {
bin++;
return csnd::pv_bin();
}
});
if(inargs[2] > 0)
std::sort(binlist.begin(), binlist.begin()+cnt, [](binamp a, binamp b){
return (a.amp > b.amp);});
std::transform(binlist.begin(), binlist.begin()+cnt, bins.begin(),
[](binamp a) { return (MYFLT) a.bin;});
std::fill(bins.begin()+cnt, bins.end(), FL(0.0));
framecount = fout.count(fin.count());
}
return OK;
}
};
struct TVConv : csnd::Plugin<1, 6> {
csnd::AuxMem<MYFLT> ir;
csnd::AuxMem<MYFLT> in;
csnd::AuxMem<MYFLT> insp;
csnd::AuxMem<MYFLT> irsp;
csnd::AuxMem<MYFLT> out;
csnd::AuxMem<MYFLT> saved;
csnd::AuxMem<MYFLT>::iterator itn;
csnd::AuxMem<MYFLT>::iterator itr;
csnd::AuxMem<MYFLT>::iterator itnsp;
csnd::AuxMem<MYFLT>::iterator itrsp;
uint32_t n;
uint32_t fils;
uint32_t pars;
uint32_t ffts;
csnd::fftp fwd, inv;
typedef std::complex<MYFLT> cmplx;
uint32_t rpow2(uint32_t n) {
uint32_t v = 2;
while (v <= n)
v <<= 1;
if ((n - (v >> 1)) < (v - n))
return v >> 1;
else
return v;
}
cmplx *to_cmplx(MYFLT *f) { return reinterpret_cast<cmplx *>(f); }
cmplx real_prod(cmplx &a, cmplx &b) {
return cmplx(a.real() * b.real(), a.imag() * b.imag());
}
int init() {
pars = inargs[4];
fils = inargs[5];
if (pars > fils)
std::swap(pars, fils);
if (pars > 1) {
pars = rpow2(pars);
fils = rpow2(fils) * 2;
ffts = pars * 2;
fwd = csound->fft_setup(ffts, FFT_FWD);
inv = csound->fft_setup(ffts, FFT_INV);
out.allocate(csound, ffts);
insp.allocate(csound, fils);
irsp.allocate(csound, fils);
saved.allocate(csound, pars);
ir.allocate(csound, fils);
in.allocate(csound, fils);
itnsp = insp.begin();
itrsp = irsp.begin();
n = 0;
} else {
ir.allocate(csound, fils);
in.allocate(csound, fils);
}
itn = in.begin();
itr = ir.begin();
return OK;
}
int pconv() {
csnd::AudioSig insig(this, inargs(0));
csnd::AudioSig irsig(this, inargs(1));
csnd::AudioSig outsig(this, outargs(0));
auto irp = irsig.begin();
auto inp = insig.begin();
auto *frz1 = inargs(2);
auto *frz2 = inargs(3);
auto inc1 = csound->is_asig(frz1);
auto inc2 = csound->is_asig(frz2);
MYFLT _0dbfs = csound->_0dbfs();
for (auto &s : outsig) {
if (*frz1 > 0)
itn[n] = *inp/_0dbfs;
if (*frz2 > 0)
itr[n] = *irp/_0dbfs;
s = (out[n] + saved[n])*_0dbfs;
saved[n] = out[n + pars];
if (++n == pars) {
cmplx *ins, *irs, *ous = to_cmplx(out.data());
std::copy(itn, itn + ffts, itnsp);
std::copy(itr, itr + ffts, itrsp);
std::fill(out.begin(), out.end(), 0.);
// FFT
csound->rfft(fwd, itnsp);
csound->rfft(fwd, itrsp);
// increment iterators
itnsp += ffts, itrsp += ffts;
itn += ffts, itr += ffts;
if (itnsp == insp.end()) {
itnsp = insp.begin();
itrsp = irsp.begin();
itn = in.begin();
itr = ir.begin();
}
// spectral delay line
for (csnd::AuxMem<MYFLT>::iterator it1 = itnsp, it2 = irsp.end() - ffts;
it2 >= irsp.begin(); it1 += ffts, it2 -= ffts) {
if (it1 == insp.end())
it1 = insp.begin();
ins = to_cmplx(it1);
irs = to_cmplx(it2);
// spectral product
for (uint32_t i = 1; i < pars; i++)
ous[i] += ins[i] * irs[i];
ous[0] += real_prod(ins[0], irs[0]);
}
// IFFT
csound->rfft(inv, out.data());
n = 0;
}
frz1 += inc1, frz2 += inc2;
irp++, inp++;
}
return OK;
}
int dconv() {
csnd::AudioSig insig(this, inargs(0));
csnd::AudioSig irsig(this, inargs(1));
csnd::AudioSig outsig(this, outargs(0));
auto irp = irsig.begin();
auto inp = insig.begin();
auto frz1 = inargs(2);
auto frz2 = inargs(3);
auto inc1 = csound->is_asig(frz1);
auto inc2 = csound->is_asig(frz2);
for (auto &s : outsig) {
if (*frz1 > 0)
*itn = *inp;
if (*frz2 > 0)
*itr = *irp;
itn++, itr++;
if (itn == in.end()) {
itn = in.begin();
itr = ir.begin();
}
s = 0.;
for (csnd::AuxMem<MYFLT>::iterator it1 = itn, it2 = ir.end() - 1;
it2 >= ir.begin(); it1++, it2--) {
if (it1 == in.end())
it1 = in.begin();
s += *it1 * *it2;
}
frz1 += inc1, frz2 += inc2;
inp++, irp++;
}
return OK;
}
int aperf() {
if (pars > 1)
return pconv();
else
return dconv();
}
};
/*
class PrintThread : public csnd::Thread {
std::atomic_bool splock;
std::atomic_bool on;
std::string message;
void lock() {
bool tmp = false;
while(!splock.compare_exchange_weak(tmp,true))
tmp = false;
}
void unlock() {
splock = false;
}
uintptr_t run() {
std::string old;
while(on) {
lock();
if(old.compare(message)) {
csound->message(message.c_str());
old = message;
}
unlock();
}
return 0;
}
public:
PrintThread(csnd::Csound *csound)
: Thread(csound), splock(false), on(true), message("") {};
~PrintThread(){
on = false;
join();
}
void set_message(const char *m) {
lock();
message = m;
unlock();
}
};
struct TPrint : csnd::Plugin<0, 1> {
static constexpr char const *otypes = "";
static constexpr char const *itypes = "S";
PrintThread t;
int init() {
csound->plugin_deinit(this);
csnd::constr(&t, csound);
return OK;
}
int deinit() {
csnd::destr(&t);
return OK;
}
int kperf() {
t.set_message(inargs.str_data(0).data);
return OK;
}
};
*/
#include <modload.h>
void csnd::on_load(Csound *csound) {
csnd::plugin<PVTrace>(csound, "pvstrace", csnd::thread::ik);
csnd::plugin<PVTrace2>(csound, "pvstrace", csnd::thread::ik);
csnd::plugin<TVConv>(csound, "tvconv", "a", "aaxxii", csnd::thread::ia);
}
<commit_msg>small fix to code<commit_after>/*
pvsops.c: pvs and other spectral-based opcodes
Copyright (C) 2017 Victor Lazzarini
This file is part of Csound.
The Csound 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.
Csound 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 Csound; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
*/
#include <algorithm>
#include <plugin.h>
struct PVTrace : csnd::FPlugin<1, 2> {
csnd::AuxMem<float> amps;
static constexpr char const *otypes = "f";
static constexpr char const *itypes = "fk";
int init() {
if (inargs.fsig_data(0).isSliding())
return csound->init_error("sliding not supported");
if (inargs.fsig_data(0).fsig_format() != csnd::fsig_format::pvs &&
inargs.fsig_data(0).fsig_format() != csnd::fsig_format::polar)
return csound->init_error("fsig format not supported");
amps.allocate(csound, inargs.fsig_data(0).nbins());
csnd::Fsig &fout = outargs.fsig_data(0);
fout.init(csound, inargs.fsig_data(0));
framecount = 0;
return OK;
}
int kperf() {
csnd::pv_frame &fin = inargs.fsig_data(0);
csnd::pv_frame &fout = outargs.fsig_data(0);
if (framecount < fin.count()) {
int n = fin.len() - (int)inargs[1];
float thrsh;
std::transform(fin.begin(), fin.end(), amps.begin(),
[](csnd::pv_bin f) { return f.amp(); });
std::nth_element(amps.begin(), amps.begin() + n, amps.end());
thrsh = amps[n];
std::transform(fin.begin(), fin.end(), fout.begin(),
[thrsh](csnd::pv_bin f) {
return f.amp() >= thrsh ? f : csnd::pv_bin();
});
framecount = fout.count(fin.count());
}
return OK;
}
};
struct binamp {
int bin;
float amp;
};
struct PVTrace2 : csnd::FPlugin<2, 5> {
csnd::AuxMem<float> amps;
csnd::AuxMem<binamp> binlist;
static constexpr char const *otypes = "fk[]";
static constexpr char const *itypes = "fkopp";
int init() {
csnd::Vector<MYFLT> &bins = outargs.vector_data<MYFLT>(1);
if (inargs.fsig_data(0).isSliding())
return csound->init_error("sliding not supported");
if (inargs.fsig_data(0).fsig_format() != csnd::fsig_format::pvs &&
inargs.fsig_data(0).fsig_format() != csnd::fsig_format::polar)
return csound->init_error("fsig format not supported");
amps.allocate(csound, inargs.fsig_data(0).nbins());
binlist.allocate(csound, inargs.fsig_data(0).nbins());
csnd::Fsig &fout = outargs.fsig_data(0);
fout.init(csound, inargs.fsig_data(0));
bins.init(csound, inargs.fsig_data(0).nbins());
framecount = 0;
return OK;
}
int kperf() {
csnd::pv_frame &fin = inargs.fsig_data(0);
csnd::pv_frame &fout = outargs.fsig_data(0);
csnd::Vector<MYFLT> &bins = outargs.vector_data<MYFLT>(1);
csnd::AuxMem<binamp> &mbins = binlist;
if (framecount < fin.count()) {
int n = fin.len() - (int)inargs[1];
float thrsh;
int cnt = 0;
int bin = 0;
int start = (int) inargs[3];
int end = (int) inargs[4];
std::transform(fin.begin() + start,
end ? fin.begin() +
((unsigned int)end <= fin.len() ? end : fin.len()) :
fin.end(), amps.begin(),
[](csnd::pv_bin f) { return f.amp(); });
std::nth_element(amps.begin(), amps.begin() + n, amps.end());
thrsh = amps[n];
std::transform(fin.begin(), fin.end(), fout.begin(),
[thrsh, &mbins, &cnt, &bin](csnd::pv_bin f) {
if(f.amp() >= thrsh) {
mbins[cnt].bin = bin++;
mbins[cnt++].amp = f.amp();
return f;
}
else {
bin++;
return csnd::pv_bin();
}
});
if(inargs[2] > 0)
std::sort(binlist.begin(), binlist.begin()+cnt, [](binamp a, binamp b){
return (a.amp > b.amp);});
std::transform(binlist.begin(), binlist.begin()+cnt, bins.begin(),
[](binamp a) { return (MYFLT) a.bin;});
std::fill(bins.begin()+cnt, bins.end(), FL(0.0));
framecount = fout.count(fin.count());
}
return OK;
}
};
struct TVConv : csnd::Plugin<1, 6> {
csnd::AuxMem<MYFLT> ir;
csnd::AuxMem<MYFLT> in;
csnd::AuxMem<MYFLT> insp;
csnd::AuxMem<MYFLT> irsp;
csnd::AuxMem<MYFLT> out;
csnd::AuxMem<MYFLT> saved;
csnd::AuxMem<MYFLT>::iterator itn;
csnd::AuxMem<MYFLT>::iterator itr;
csnd::AuxMem<MYFLT>::iterator itnsp;
csnd::AuxMem<MYFLT>::iterator itrsp;
uint32_t n;
uint32_t fils;
uint32_t pars;
uint32_t ffts;
csnd::fftp fwd, inv;
typedef std::complex<MYFLT> cmplx;
uint32_t rpow2(uint32_t n) {
uint32_t v = 2;
while (v <= n)
v <<= 1;
if ((n - (v >> 1)) < (v - n))
return v >> 1;
else
return v;
}
cmplx *to_cmplx(MYFLT *f) { return reinterpret_cast<cmplx *>(f); }
cmplx real_prod(cmplx &a, cmplx &b) {
return cmplx(a.real() * b.real(), a.imag() * b.imag());
}
int init() {
pars = inargs[4];
fils = inargs[5];
if (pars > fils)
std::swap(pars, fils);
if (pars > 1) {
pars = rpow2(pars);
fils = rpow2(fils) * 2;
ffts = pars * 2;
fwd = csound->fft_setup(ffts, FFT_FWD);
inv = csound->fft_setup(ffts, FFT_INV);
out.allocate(csound, ffts);
insp.allocate(csound, fils);
irsp.allocate(csound, fils);
saved.allocate(csound, pars);
ir.allocate(csound, fils);
in.allocate(csound, fils);
itnsp = insp.begin();
itrsp = irsp.begin();
n = 0;
} else {
ir.allocate(csound, fils);
in.allocate(csound, fils);
}
itn = in.begin();
itr = ir.begin();
return OK;
}
int pconv() {
csnd::AudioSig insig(this, inargs(0));
csnd::AudioSig irsig(this, inargs(1));
csnd::AudioSig outsig(this, outargs(0));
auto irp = irsig.begin();
auto inp = insig.begin();
auto *frz1 = inargs(2);
auto *frz2 = inargs(3);
auto inc1 = csound->is_asig(frz1);
auto inc2 = csound->is_asig(frz2);
MYFLT _0dbfs = csound->_0dbfs();
for (auto &s : outsig) {
if (*frz1 > 0)
itn[n] = *inp/_0dbfs;
if (*frz2 > 0)
itr[n] = *irp/_0dbfs;
s = (out[n] + saved[n])*_0dbfs;
saved[n] = out[n + pars];
if (++n == pars) {
cmplx *ins, *irs, *ous = to_cmplx(out.data());
std::copy(itn, itn + ffts, itnsp);
std::copy(itr, itr + ffts, itrsp);
std::fill(out.begin(), out.end(), 0.);
// FFT
csound->rfft(fwd, itnsp);
csound->rfft(fwd, itrsp);
// increment iterators
itnsp += ffts, itrsp += ffts;
itn += ffts, itr += ffts;
if (itnsp == insp.end()) {
itnsp = insp.begin();
itrsp = irsp.begin();
itn = in.begin();
itr = ir.begin();
}
// spectral delay line
for (csnd::AuxMem<MYFLT>::iterator it1 = itnsp, it2 = irsp.end() - ffts;
it2 >= irsp.begin(); it1 += ffts, it2 -= ffts) {
if (it1 == insp.end())
it1 = insp.begin();
ins = to_cmplx(it1);
irs = to_cmplx(it2);
// spectral product
for (uint32_t i = 1; i < pars; i++)
ous[i] += ins[i] * irs[i];
ous[0] += real_prod(ins[0], irs[0]);
}
// IFFT
csound->rfft(inv, out.data());
n = 0;
}
frz1 += inc1, frz2 += inc2;
irp++, inp++;
}
return OK;
}
int dconv() {
csnd::AudioSig insig(this, inargs(0));
csnd::AudioSig irsig(this, inargs(1));
csnd::AudioSig outsig(this, outargs(0));
auto irp = irsig.begin();
auto inp = insig.begin();
auto frz1 = inargs(2);
auto frz2 = inargs(3);
auto inc1 = csound->is_asig(frz1);
auto inc2 = csound->is_asig(frz2);
for (auto &s : outsig) {
if (*frz1 > 0)
*itn = *inp;
if (*frz2 > 0)
*itr = *irp;
itn++, itr++;
if (itn == in.end()) {
itn = in.begin();
itr = ir.begin();
}
s = 0.;
for (csnd::AuxMem<MYFLT>::iterator it1 = itn, it2 = ir.end() - 1;
it2 >= ir.begin(); it1++, it2--) {
if (it1 == in.end())
it1 = in.begin();
s += *it1 * *it2;
}
frz1 += inc1, frz2 += inc2;
inp++, irp++;
}
return OK;
}
int aperf() {
if (pars > 1)
return pconv();
else
return dconv();
}
};
/*
class PrintThread : public csnd::Thread {
std::atomic_bool splock;
std::atomic_bool on;
std::string message;
void lock() {
bool tmp = false;
while(!splock.compare_exchange_weak(tmp,true))
tmp = false;
}
void unlock() {
splock = false;
}
uintptr_t run() {
std::string old;
while(on) {
lock();
if(old.compare(message)) {
csound->message(message.c_str());
old = message;
}
unlock();
}
return 0;
}
public:
PrintThread(csnd::Csound *csound)
: Thread(csound), splock(false), on(true), message("") {};
~PrintThread(){
on = false;
join();
}
void set_message(const char *m) {
lock();
message = m;
unlock();
}
};
struct TPrint : csnd::Plugin<0, 1> {
static constexpr char const *otypes = "";
static constexpr char const *itypes = "S";
PrintThread t;
int init() {
csound->plugin_deinit(this);
csnd::constr(&t, csound);
return OK;
}
int deinit() {
csnd::destr(&t);
return OK;
}
int kperf() {
t.set_message(inargs.str_data(0).data);
return OK;
}
};
*/
#include <modload.h>
void csnd::on_load(Csound *csound) {
csnd::plugin<PVTrace>(csound, "pvstrace", csnd::thread::ik);
csnd::plugin<PVTrace2>(csound, "pvstrace", csnd::thread::ik);
csnd::plugin<TVConv>(csound, "tvconv", "a", "aaxxii", csnd::thread::ia);
}
<|endoftext|> |
<commit_before>void MakeCTPDummyEntries(){
// macro to put in OCDB the dummy entries for CTP configuration and scalers
AliCDBManager *man = AliCDBManager::Instance();
man->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
Char_t * filenameConfig = gSystem->ExpandPathName("$ALICE_ROOT/GRP/CTP/p-p.cfg");
Char_t * filenameScalers = gSystem->ExpandPathName("$ALICE_ROOT/GRP/CTP/xcounters.txt");
AliTriggerConfiguration *runcfg = AliTriggerConfiguration::LoadConfiguration(filenameConfig);
AliTriggerRunScalers *scalers = AliTriggerRunScalers::ReadScalers(filenameScalers);
AliCDBMetaData* metaconfig = new AliCDBMetaData();
metaconfig->SetResponsible("Roman Lietava");
metaconfig->SetComment("Dummy CTP configuration for standalone runs");
AliCDBId idconfig("GRP/CTP/DummyConfig",0,AliCDBRunRange::Infinity());
man->Put(runcfg,idconfig, metaconfig);
AliCDBMetaData* metascalers = new AliCDBMetaData();
metascalers->SetResponsible("Roman Lietava");
metascalers->SetComment("Dummy CTP scalers for standalone runs");
AliCDBId idscalers("GRP/CTP/DummyScalers",0,AliCDBRunRange::Infinity());
man->Put(scalers,idscalers, metascalers);
return;
}
<commit_msg>Updated comment.<commit_after>void MakeCTPDummyEntries(){
// Example macro to put in OCDB the dummy entries for CTP configuration and scalers
// The entries are at present taken from $ALICE_ROOT
// Should be used to test the GRP preprocessor
AliCDBManager *man = AliCDBManager::Instance();
man->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
Char_t * filenameConfig = gSystem->ExpandPathName("$ALICE_ROOT/GRP/CTP/p-p.cfg");
Char_t * filenameScalers = gSystem->ExpandPathName("$ALICE_ROOT/GRP/CTP/xcounters.txt");
AliTriggerConfiguration *runcfg = AliTriggerConfiguration::LoadConfiguration(filenameConfig);
AliTriggerRunScalers *scalers = AliTriggerRunScalers::ReadScalers(filenameScalers);
AliCDBMetaData* metaconfig = new AliCDBMetaData();
metaconfig->SetResponsible("Roman Lietava");
metaconfig->SetComment("Dummy CTP configuration for standalone runs");
AliCDBId idconfig("GRP/CTP/DummyConfig",0,AliCDBRunRange::Infinity());
man->Put(runcfg,idconfig, metaconfig);
AliCDBMetaData* metascalers = new AliCDBMetaData();
metascalers->SetResponsible("Roman Lietava");
metascalers->SetComment("Dummy CTP scalers for standalone runs");
AliCDBId idscalers("GRP/CTP/DummyScalers",0,AliCDBRunRange::Infinity());
man->Put(scalers,idscalers, metascalers);
return;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: fchrfmt.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: dvo $ $Date: 2001-07-09 20:10:42 $
*
* 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 _FCHRFMT_HXX
#define _FCHRFMT_HXX
#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif
#ifndef _CALBCK_HXX //autogen
#include <calbck.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif
class SwCharFmt;
class IntlWrapper;
// ATT_CHARFMT *********************************************
class SwFmtCharFmt: public SfxPoolItem, public SwClient
{
friend class SwTxtCharFmt;
SwTxtCharFmt* pTxtAttr; // mein TextAttribut
public:
SwFmtCharFmt( SwCharFmt *pFmt );
SwFmtCharFmt( const SwFmtCharFmt& rAttr );
~SwFmtCharFmt(); // fuer SEXPORT
TYPEINFO();
// "pure virtual Methoden" vom SfxPoolItem
virtual int operator==( const SfxPoolItem& ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual SfxPoolItem* Create(SvStream &, USHORT nVer) const;
virtual SvStream& Store(SvStream &, USHORT nIVer ) const;
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
// an das SwTxtCharFmt weiterleiten (vom SwClient)
virtual void Modify( SfxPoolItem*, SfxPoolItem* );
virtual BOOL GetInfo( SfxPoolItem& rInfo ) const;
void SetCharFmt( SwFmt* pFmt ) { pFmt->Add(this); }
SwCharFmt* GetCharFmt() const { return (SwCharFmt*)GetRegisteredIn(); }
};
#endif
<commit_msg>INTEGRATION: CWS tune03 (1.4.772); FILE MERGED 2004/07/19 19:10:32 mhu 1.4.772.1: #i29979# Added SW_DLLPUBLIC/PRIVATE (see swdllapi.h) to exported symbols/classes.<commit_after>/*************************************************************************
*
* $RCSfile: fchrfmt.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2004-08-23 08:31:09 $
*
* 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 _FCHRFMT_HXX
#define _FCHRFMT_HXX
#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif
#ifndef _CALBCK_HXX //autogen
#include <calbck.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif
class SwCharFmt;
class IntlWrapper;
// ATT_CHARFMT *********************************************
class SwFmtCharFmt: public SfxPoolItem, public SwClient
{
friend class SwTxtCharFmt;
SwTxtCharFmt* pTxtAttr; // mein TextAttribut
public:
SwFmtCharFmt() : pTxtAttr(0) {}
// single argument ctors shall be explicit.
explicit SwFmtCharFmt( SwCharFmt *pFmt );
virtual ~SwFmtCharFmt();
// @@@ public copy ctor, but no copy assignment?
SwFmtCharFmt( const SwFmtCharFmt& rAttr );
private:
// @@@ public copy ctor, but no copy assignment?
SwFmtCharFmt & operator= (const SwFmtCharFmt &);
public:
TYPEINFO();
// "pure virtual Methoden" vom SfxPoolItem
virtual int operator==( const SfxPoolItem& ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual SfxPoolItem* Create(SvStream &, USHORT nVer) const;
virtual SvStream& Store(SvStream &, USHORT nIVer ) const;
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
// an das SwTxtCharFmt weiterleiten (vom SwClient)
virtual void Modify( SfxPoolItem*, SfxPoolItem* );
virtual BOOL GetInfo( SfxPoolItem& rInfo ) const;
void SetCharFmt( SwFmt* pFmt ) { pFmt->Add(this); }
SwCharFmt* GetCharFmt() const { return (SwCharFmt*)GetRegisteredIn(); }
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: directory.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-10-04 05:51:59 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_transex3.hxx"
#include "directory.hxx"
#include "tools/string.hxx"
#include <iostream>
#include <vector>
#include <algorithm>
namespace transex
{
Directory::Directory( const rtl::OUString sFullpath ) : bSkipLinks( false )
{
sFullName = sFullpath;
}
Directory::Directory( const rtl::OUString sFullPath , const rtl::OUString sEntry ) : bSkipLinks( false )
{
sFullName = sFullPath;
sDirectoryName = sEntry;
}
Directory::Directory( const ByteString sFullPath ) : bSkipLinks( false )
{
sDirectoryName = rtl::OUString( sFullPath.GetBuffer() , RTL_TEXTENCODING_UTF8 , sFullPath.Len() );
}
bool Directory::lessDir ( const Directory& rKey1, const Directory& rKey2 )
{
rtl::OUString sName1( ( static_cast< Directory >( rKey1 ) ).getDirectoryName() );
rtl::OUString sName2( ( static_cast< Directory >( rKey2 ) ).getDirectoryName() );
return sName1.compareTo( sName2 ) < 0 ;
}
void Directory::dump()
{
for( std::vector< transex::File >::iterator iter = aFileVec.begin() ; iter != aFileVec.end() ; ++iter )
{
std::cout << "FILE " << rtl::OUStringToOString( (*iter).getFullName().getStr() , RTL_TEXTENCODING_UTF8 , (*iter).getFullName().getLength() ).getStr() << "\n";
}
for( std::vector< transex::Directory >::iterator iter = aDirVec.begin() ; iter != aDirVec.end() ; ++iter )
{
std::cout << "DIR " << rtl::OUStringToOString( (*iter).getFullName().getStr() , RTL_TEXTENCODING_UTF8 , (*iter).getFullName().getLength() ).getStr() << "\n";
}
}
void Directory::scanSubDir( int nLevels )
{
readDirectory( sFullName );
dump();
if( nLevels > 0 ) {
for( std::vector< transex::Directory >::iterator iter = aDirVec.begin() ; iter != aDirVec.end() || nLevels > 0 ; ++iter , nLevels-- )
{
( *iter ).scanSubDir();
}
}
}
void Directory::setSkipLinks( bool is_skipped )
{
bSkipLinks = is_skipped;
}
void Directory::readDirectory()
{
readDirectory( sFullName );
}
#ifdef WNT
#include <tools/prewin.h>
#include <windows.h>
#include <tools/postwin.h>
void Directory::readDirectory ( const rtl::OUString& sFullpath )
{
BOOL fFinished;
HANDLE hList;
TCHAR szDir[MAX_PATH+1];
TCHAR szSubDir[MAX_PATH+1];
WIN32_FIND_DATA FileData;
rtl::OString sFullpathext = rtl::OUStringToOString( sFullpath , RTL_TEXTENCODING_UTF8 , sFullpath.getLength() );
const char *dirname = sFullpathext.getStr();
// Get the proper directory path
sprintf(szDir, "%s\\*", dirname);
// Get the first file
hList = FindFirstFile(szDir, &FileData);
if (hList == INVALID_HANDLE_VALUE)
{
//FindClose(hList);
//printf("No files found %s\n", szDir ); return;
}
else
{
fFinished = FALSE;
while (!fFinished)
{
sprintf(szSubDir, "%s\\%s", dirname, FileData.cFileName);
rtl::OString myfile( FileData.cFileName );
rtl::OString mydir( szSubDir );
if (FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if ( (strcmp(FileData.cFileName, ".") != 0 ) &&
(strcmp(FileData.cFileName, "..") != 0 ) )
{
//sprintf(szSubDir, "%s\\%s", dirname, FileData.cFileName);
transex::Directory aDir( rtl::OStringToOUString( mydir , RTL_TEXTENCODING_UTF8 , mydir.getLength() ),
rtl::OStringToOUString( myfile , RTL_TEXTENCODING_UTF8 , myfile.getLength() ) );
aDirVec.push_back( aDir );
}
}
else
{
transex::File aFile( rtl::OStringToOUString( mydir , RTL_TEXTENCODING_UTF8 , mydir.getLength() ),
rtl::OStringToOUString( myfile , RTL_TEXTENCODING_UTF8 , myfile.getLength() ) );
aFileVec.push_back( aFile );
}
if (!FindNextFile(hList, &FileData))
{
if (GetLastError() == ERROR_NO_MORE_FILES)
{
fFinished = TRUE;
}
}
}
}
FindClose(hList);
::std::sort( aFileVec.begin() , aFileVec.end() , File::lessFile );
::std::sort( aDirVec.begin() , aDirVec.end() , Directory::lessDir );
}
#else
void Directory::readDirectory( const rtl::OUString& sFullpath )
{
struct stat statbuf;
struct stat statbuf2;
struct dirent *dirp;
DIR *dir;
//int ret;
//char *ptr;
if( sFullpath.getLength() < 1 ) return;
rtl::OString sFullpathext = rtl::OUStringToOString( sFullpath , RTL_TEXTENCODING_UTF8 , sFullpath.getLength() ).getStr();
const char* path = sFullpathext.getStr();
// stat
if( lstat( path , &statbuf ) < 0 ){ printf("readerror 1 in Directory::readDirectory"); return; }// error }
//if( S_ISDIR(statbuf.st_mode ) == 0 && S_ISLNK(statbuf.st_mode )){ printf("readerror 2 in Directory::readDirectory"); return; }// error } return; // not dir
if( (dir = opendir( path ) ) == NULL ) {printf("readerror in %s \n",path); return; } // error } return; // error
sFullpathext += rtl::OString( "/" );
const rtl::OString sDot ( "." ) ;
const rtl::OString sDDot( ".." );
chdir( path );
while( ( dirp = readdir( dir ) ) != NULL )
{
rtl::OString sEntryName( dirp->d_name );
if( sEntryName.equals( sDot ) || sEntryName.equals( sDDot ) )
continue;
// add dir entry
rtl::OString sEntity = sFullpathext;
sEntity += sEntryName;
// stat new entry
if( lstat( sEntity.getStr() , &statbuf2 ) < 0 )
{
printf("error on entry %s\n" , sEntity.getStr() ) ; // error
continue;
}
// add file / dir to vector
switch( statbuf2.st_mode & S_IFMT )
{
case S_IFREG:
{
rtl::OString sFile = sFullpathext;
sFile += sEntryName ;
transex::File aFile( rtl::OStringToOUString( sEntity , RTL_TEXTENCODING_UTF8 , sEntity.getLength() ) ,
rtl::OStringToOUString( sEntryName , RTL_TEXTENCODING_UTF8 , sEntryName.getLength() )
);
aFileVec.push_back( aFile ) ;
break;
}
case S_IFLNK:
{
if( bSkipLinks ) break;
}
case S_IFDIR:
{
rtl::OString sDir = sFullpathext;
sDir += sEntryName ;
transex::Directory aDir(
rtl::OStringToOUString( sEntity , RTL_TEXTENCODING_UTF8 , sEntity.getLength() ) ,
rtl::OStringToOUString( sEntryName , RTL_TEXTENCODING_UTF8 , sEntryName.getLength() )
) ;
aDirVec.push_back( aDir ) ;
break;
}
}
}
chdir( ".." );
if( closedir( dir ) < 0 ) return ; // error
std::sort( aFileVec.begin() , aFileVec.end() , File::lessFile );
std::sort( aDirVec.begin() , aDirVec.end() , Directory::lessDir );
}
#endif
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.4.34); FILE MERGED 2007/06/04 13:33:11 vg 1.4.34.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: directory.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2007-06-27 22:29: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_transex3.hxx"
#include <transex3/directory.hxx>
#include "tools/string.hxx"
#include <iostream>
#include <vector>
#include <algorithm>
namespace transex
{
Directory::Directory( const rtl::OUString sFullpath ) : bSkipLinks( false )
{
sFullName = sFullpath;
}
Directory::Directory( const rtl::OUString sFullPath , const rtl::OUString sEntry ) : bSkipLinks( false )
{
sFullName = sFullPath;
sDirectoryName = sEntry;
}
Directory::Directory( const ByteString sFullPath ) : bSkipLinks( false )
{
sDirectoryName = rtl::OUString( sFullPath.GetBuffer() , RTL_TEXTENCODING_UTF8 , sFullPath.Len() );
}
bool Directory::lessDir ( const Directory& rKey1, const Directory& rKey2 )
{
rtl::OUString sName1( ( static_cast< Directory >( rKey1 ) ).getDirectoryName() );
rtl::OUString sName2( ( static_cast< Directory >( rKey2 ) ).getDirectoryName() );
return sName1.compareTo( sName2 ) < 0 ;
}
void Directory::dump()
{
for( std::vector< transex::File >::iterator iter = aFileVec.begin() ; iter != aFileVec.end() ; ++iter )
{
std::cout << "FILE " << rtl::OUStringToOString( (*iter).getFullName().getStr() , RTL_TEXTENCODING_UTF8 , (*iter).getFullName().getLength() ).getStr() << "\n";
}
for( std::vector< transex::Directory >::iterator iter = aDirVec.begin() ; iter != aDirVec.end() ; ++iter )
{
std::cout << "DIR " << rtl::OUStringToOString( (*iter).getFullName().getStr() , RTL_TEXTENCODING_UTF8 , (*iter).getFullName().getLength() ).getStr() << "\n";
}
}
void Directory::scanSubDir( int nLevels )
{
readDirectory( sFullName );
dump();
if( nLevels > 0 ) {
for( std::vector< transex::Directory >::iterator iter = aDirVec.begin() ; iter != aDirVec.end() || nLevels > 0 ; ++iter , nLevels-- )
{
( *iter ).scanSubDir();
}
}
}
void Directory::setSkipLinks( bool is_skipped )
{
bSkipLinks = is_skipped;
}
void Directory::readDirectory()
{
readDirectory( sFullName );
}
#ifdef WNT
#include <tools/prewin.h>
#include <windows.h>
#include <tools/postwin.h>
void Directory::readDirectory ( const rtl::OUString& sFullpath )
{
BOOL fFinished;
HANDLE hList;
TCHAR szDir[MAX_PATH+1];
TCHAR szSubDir[MAX_PATH+1];
WIN32_FIND_DATA FileData;
rtl::OString sFullpathext = rtl::OUStringToOString( sFullpath , RTL_TEXTENCODING_UTF8 , sFullpath.getLength() );
const char *dirname = sFullpathext.getStr();
// Get the proper directory path
sprintf(szDir, "%s\\*", dirname);
// Get the first file
hList = FindFirstFile(szDir, &FileData);
if (hList == INVALID_HANDLE_VALUE)
{
//FindClose(hList);
//printf("No files found %s\n", szDir ); return;
}
else
{
fFinished = FALSE;
while (!fFinished)
{
sprintf(szSubDir, "%s\\%s", dirname, FileData.cFileName);
rtl::OString myfile( FileData.cFileName );
rtl::OString mydir( szSubDir );
if (FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if ( (strcmp(FileData.cFileName, ".") != 0 ) &&
(strcmp(FileData.cFileName, "..") != 0 ) )
{
//sprintf(szSubDir, "%s\\%s", dirname, FileData.cFileName);
transex::Directory aDir( rtl::OStringToOUString( mydir , RTL_TEXTENCODING_UTF8 , mydir.getLength() ),
rtl::OStringToOUString( myfile , RTL_TEXTENCODING_UTF8 , myfile.getLength() ) );
aDirVec.push_back( aDir );
}
}
else
{
transex::File aFile( rtl::OStringToOUString( mydir , RTL_TEXTENCODING_UTF8 , mydir.getLength() ),
rtl::OStringToOUString( myfile , RTL_TEXTENCODING_UTF8 , myfile.getLength() ) );
aFileVec.push_back( aFile );
}
if (!FindNextFile(hList, &FileData))
{
if (GetLastError() == ERROR_NO_MORE_FILES)
{
fFinished = TRUE;
}
}
}
}
FindClose(hList);
::std::sort( aFileVec.begin() , aFileVec.end() , File::lessFile );
::std::sort( aDirVec.begin() , aDirVec.end() , Directory::lessDir );
}
#else
void Directory::readDirectory( const rtl::OUString& sFullpath )
{
struct stat statbuf;
struct stat statbuf2;
struct dirent *dirp;
DIR *dir;
//int ret;
//char *ptr;
if( sFullpath.getLength() < 1 ) return;
rtl::OString sFullpathext = rtl::OUStringToOString( sFullpath , RTL_TEXTENCODING_UTF8 , sFullpath.getLength() ).getStr();
const char* path = sFullpathext.getStr();
// stat
if( lstat( path , &statbuf ) < 0 ){ printf("readerror 1 in Directory::readDirectory"); return; }// error }
//if( S_ISDIR(statbuf.st_mode ) == 0 && S_ISLNK(statbuf.st_mode )){ printf("readerror 2 in Directory::readDirectory"); return; }// error } return; // not dir
if( (dir = opendir( path ) ) == NULL ) {printf("readerror in %s \n",path); return; } // error } return; // error
sFullpathext += rtl::OString( "/" );
const rtl::OString sDot ( "." ) ;
const rtl::OString sDDot( ".." );
chdir( path );
while( ( dirp = readdir( dir ) ) != NULL )
{
rtl::OString sEntryName( dirp->d_name );
if( sEntryName.equals( sDot ) || sEntryName.equals( sDDot ) )
continue;
// add dir entry
rtl::OString sEntity = sFullpathext;
sEntity += sEntryName;
// stat new entry
if( lstat( sEntity.getStr() , &statbuf2 ) < 0 )
{
printf("error on entry %s\n" , sEntity.getStr() ) ; // error
continue;
}
// add file / dir to vector
switch( statbuf2.st_mode & S_IFMT )
{
case S_IFREG:
{
rtl::OString sFile = sFullpathext;
sFile += sEntryName ;
transex::File aFile( rtl::OStringToOUString( sEntity , RTL_TEXTENCODING_UTF8 , sEntity.getLength() ) ,
rtl::OStringToOUString( sEntryName , RTL_TEXTENCODING_UTF8 , sEntryName.getLength() )
);
aFileVec.push_back( aFile ) ;
break;
}
case S_IFLNK:
{
if( bSkipLinks ) break;
}
case S_IFDIR:
{
rtl::OString sDir = sFullpathext;
sDir += sEntryName ;
transex::Directory aDir(
rtl::OStringToOUString( sEntity , RTL_TEXTENCODING_UTF8 , sEntity.getLength() ) ,
rtl::OStringToOUString( sEntryName , RTL_TEXTENCODING_UTF8 , sEntryName.getLength() )
) ;
aDirVec.push_back( aDir ) ;
break;
}
}
}
chdir( ".." );
if( closedir( dir ) < 0 ) return ; // error
std::sort( aFileVec.begin() , aFileVec.end() , File::lessFile );
std::sort( aDirVec.begin() , aDirVec.end() , Directory::lessDir );
}
#endif
}
<|endoftext|> |
<commit_before>/*
* PrimeSieveGUI.cpp -- This file is part of primesieve
*
* Copyright (C) 2010 Kim Walisch, <kim.walisch@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include "PrimeSieveGUI.h"
#include "ui_PrimeSieveGUI.h"
#include "../src/pmath.h"
#include <QThread>
#include <QSize>
#include <QMessageBox>
#include <QTextCursor>
#include <cstdlib>
#include <stdexcept>
PrimeSieveGUI::PrimeSieveGUI(QWidget *parent) :
QMainWindow(parent), ui(new Ui::PrimeSieveGUI), saveAct_(0), quitAct_(0),
aboutAct_(0), alignmentGroup_(0), validator_(0), finishedProcesses_(0) {
ui->setupUi(this);
this->initMemberVariables();
this->initGUI();
this->initConnections();
}
PrimeSieveGUI::~PrimeSieveGUI() {
// kill all processes
this->cleanUp();
// free all allocated memory
if (saveAct_ != 0) delete saveAct_;
if (quitAct_ != 0) delete quitAct_;
if (aboutAct_ != 0) delete aboutAct_;
if (alignmentGroup_ != 0) delete alignmentGroup_;
if (validator_ != 0) delete validator_;
for (; !countAct_.isEmpty(); countAct_.pop_back())
delete countAct_.back();
for (; !printAct_.isEmpty(); printAct_.pop_back())
delete printAct_.back();
// Qt code
delete ui;
}
void PrimeSieveGUI::changeEvent(QEvent *e) {
QMainWindow::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void PrimeSieveGUI::initMemberVariables() {
primeText_.push_back("Prime numbers");
primeText_.push_back("Twin primes");
primeText_.push_back("Prime triplets");
primeText_.push_back("Prime quadruplets");
primeText_.push_back("Prime quintuplets");
primeText_.push_back("Prime sextuplets");
primeText_.push_back("Prime septuplets");
// get the number of logical CPU cores
int maxCpuCores = QThread::idealThreadCount();
if (maxCpuCores > 0)
isCpuDetected_ = true;
else {
isCpuDetected_ = false;
// default value for undetected CPUs
maxCpuCores = DEFAULT_MAX_CPU_CORES;
}
this->initCpuCoresComboBox(maxCpuCores);
}
void PrimeSieveGUI::initGUI() {
// set the main window title
this->setWindowTitle(APPLICATION_NAME + " " + APPLICATION_VERSION);
// create the menu bar
this->createMenu(primeText_);
// fill with values
this->initSieveSizeComboBox();
// set an ideal ComboBox width
int width = ui->sieveSizeComboBox->minimumSizeHint().width();
ui->sieveSizeComboBox->setFixedWidth(width);
ui->cpuCoresComboBox->setFixedWidth(width);
if (!isCpuDetected_) {
ui->autoSetCheckBox->setChecked(false);
ui->autoSetCheckBox->setDisabled(true);
}
// limit input to 20 digits max
QRegExp rx("[0-9]\\d{0,19}");
validator_ = new QRegExpValidator(rx, this);
ui->lowerBoundLineEdit->setValidator(validator_);
ui->upperBoundLineEdit->setValidator(validator_);
// set a nice GUI size
int guiWidth = this->minimumSizeHint().width();
int guiHeight = this->sizeHint().height();
#if defined(Q_OS_WIN)
guiHeight = static_cast<int> (guiHeight * 0.95);
#elif defined(Q_OS_MAC)
guiHeight = static_cast<int> (guiHeight * 0.96);
#endif
this->resize(QSize(guiWidth, guiHeight));
}
void PrimeSieveGUI::initConnections() {
// advances the progress bar
connect(&progressBarTimer_, SIGNAL(timeout()), this, SLOT(
advanceProgressBar()));
// autoSetCpuCores() connections
if (isCpuDetected_) {
connect(ui->lowerBoundLineEdit, SIGNAL(textChanged(const QString &)),
this, SLOT(autoSetCpuCores()));
connect(ui->upperBoundLineEdit, SIGNAL(textChanged(const QString &)),
this, SLOT(autoSetCpuCores()));
connect(ui->autoSetCheckBox, SIGNAL(toggled(bool)),
this, SLOT(autoSetCpuCores()));
}
}
/**
* Fill the sieveSizeComboBox with power of 2 values from
* 16 KB till 8192 KB.
*/
void PrimeSieveGUI::initSieveSizeComboBox() {
for (int i = MINIMUM_SIEVE_SIZE; i <= MAXIMUM_SIEVE_SIZE; i *= 2)
ui->sieveSizeComboBox->addItem(QString::number(i) + " KB");
// set the default sieve size
QString sieveSize = QString::number(DEFAULT_SIEVE_SIZE) + " KB";
this->setComboBox(ui->sieveSizeComboBox, sieveSize);
}
/**
* Fill the cpuCoresComboBox with power of 2 values from 1 till
* maxCpuCores.
*/
void PrimeSieveGUI::initCpuCoresComboBox(int maxCpuCores) {
for (int i = 1; i < maxCpuCores; i *= 2)
ui->cpuCoresComboBox->addItem(QString::number(i));
ui->cpuCoresComboBox->addItem(QString::number(maxCpuCores));
// default 1 CPU core
this->setComboBox(ui->cpuCoresComboBox, "1");
}
/**
* Get the users lower and upper bound for prime sieving.
*/
void PrimeSieveGUI::getBounds(qulonglong* lowerBound, qulonglong* upperBound) {
QString lbound = ui->lowerBoundLineEdit->text();
QString ubound = ui->upperBoundLineEdit->text();
if (ubound.isEmpty() || lbound.isEmpty())
throw std::invalid_argument("Missing input.");
bool lOk = true;
bool uOk = true;
*lowerBound = lbound.toULongLong(&lOk, 10);
*upperBound = ubound.toULongLong(&uOk, 10);
if (!lOk || !uOk || *lowerBound >= UPPER_BOUND_LIMIT || *upperBound
>= UPPER_BOUND_LIMIT)
throw std::invalid_argument(
"Please use numbers >= 0 and < (2^64-1) - (2^32-1) * 10.");
if (*lowerBound > *upperBound)
throw std::invalid_argument(
"The lower bound must not be greater than the upper bound.");
}
/**
* Get the sieve size (in KiloBytes) from the sieveSizeComboBox.
* @post sieveSize >= 1 && sieveSize <= 8192.
*/
int PrimeSieveGUI::getSieveSize() {
QString sieveSize(ui->sieveSizeComboBox->currentText());
// remove " KB"
sieveSize.chop(3);
return sieveSize.toInt();
}
/**
* Get the current number of CPU cores from the cpuCoresComboBox.
*/
int PrimeSieveGUI::getCpuCores() {
return ui->cpuCoresComboBox->currentText().toInt();
}
/**
* Get the maximum number of CPU cores from the cpuCoresComboBox.
*/
int PrimeSieveGUI::getMaxCpuCores() {
int count = ui->cpuCoresComboBox->count();
return ui->cpuCoresComboBox->itemText(count - 1).toInt();
}
/**
* Show the text string in the ComboBox.
*/
void PrimeSieveGUI::setComboBox(QComboBox* comboBox, QString text) {
int index = comboBox->findText(text);
if (index < 0)
QMessageBox::critical(this, APPLICATION_NAME,
"Internal ComboBox error, please contact the developer.");
comboBox->setCurrentIndex(index);
}
/**
* The user has chosen a custom number of CPU cores.
*/
void PrimeSieveGUI::on_cpuCoresComboBox_activated() {
// disable "Auto set"
ui->autoSetCheckBox->setChecked(false);
}
/**
* Calculate an ideal number of CPU cores for sieving.
*/
int PrimeSieveGUI::getIdealCpuCoreCount(qulonglong lowerBound,
qulonglong upperBound, int maxCpuCores) {
int cpuCores = -1;
// I made some tests around 10^19 which showed that each CPU core
// should at least sieve an interval of sqrt(upperBound) / 6 for a
// performance benefit
qulonglong interval = U32SQRT(upperBound) / 6;
if (interval < MINIMUM_THREAD_INTERVAL)
interval = MINIMUM_THREAD_INTERVAL;
// use all CPU cores for big sieve intervals
if (maxCpuCores * interval <= upperBound - lowerBound)
cpuCores = maxCpuCores;
else {
// use less CPU cores for small sieve intervals
cpuCores = static_cast<int> ((upperBound - lowerBound) / interval);
// floor to the next power of 2 value
cpuCores = 1 << floorLog2(cpuCores);
}
return cpuCores;
}
/**
* Show the ideal CPU core number in the cpuCoresComboBox (if
* "Auto set" is enabled).
*/
void PrimeSieveGUI::autoSetCpuCores() {
if (ui->autoSetCheckBox->isEnabled() &&
ui->autoSetCheckBox->isChecked()) {
qulonglong lowerBound = 0;
qulonglong upperBound = 0;
QString cpuCores("1");
try {
// get the users lower and upper bound
this->getBounds(&lowerBound, &upperBound);
// get an ideal number of CPU cores
cpuCores.setNum(this->getIdealCpuCoreCount(lowerBound, upperBound,
this->getMaxCpuCores()));
} catch (...) {
}
// set to the ideal CPU core number
this->setComboBox(ui->cpuCoresComboBox, cpuCores);
}
}
/**
* Cancel sieving.
*/
void PrimeSieveGUI::on_cancelButton_clicked() {
ui->cancelButton->setDisabled(true);
// set to 0 percent
ui->progressBar->setValue(0);
// too late to abort
if ((flags_ & PRINT_FLAGS) && processes_.front()->isFinished())
return;
// kill all running processes
this->cleanUp();
}
void PrimeSieveGUI::advanceProgressBar() {
// delay the timer after 60 sec
if (progressBarTimer_.interval() < 100 && time_.elapsed() > 60000)
progressBarTimer_.setInterval(100);
// in percents
float status = 0.0f;
// combine the status of all processes
for (int i = 0; i < processes_.size(); i++)
status += processes_[i]->getStatus();
status /= processes_.size();
int permil = static_cast<int> (status * 10.0f);
// advance the progressBar
ui->progressBar->setValue(permil);
}
/**
* Print the sieving results and clean up.
*/
void PrimeSieveGUI::printResults() {
// add newline
if (!ui->textEdit->toPlainText().isEmpty())
ui->textEdit->appendPlainText("");
QString align = this->getAlign();
// combine the count results of all processes
QVector<qlonglong> combinedCount(PrimeSieveProcess::COUNTS_SIZE, 0);
for (int i = 0; i < processes_.size(); i++) {
for (int j = 0; j < combinedCount.size(); j++)
combinedCount[j] += processes_[i]->getCounts(j);
}
// print prime counts
for (int i = 0; i < combinedCount.size(); i++) {
if (combinedCount[i] >= 0)
ui->textEdit->appendPlainText(primeText_[i] + align +
QString::number(combinedCount[i]));
}
// add newline for prime k-tuplets
if (flags_ & (COUNT_FLAGS - COUNT_PRIMES))
ui->textEdit->appendPlainText("");
// print time
QString time("Elapsed time" + align);
int milliSeconds = time_.elapsed();
int hrs = (milliSeconds / 3600000);
int min = (milliSeconds / 60000) % 60;
if (hrs > 0)
time.append(QString::number(hrs) + " hrs ");
if (min > 0)
time.append(QString::number(min) + " min ");
double sec = (milliSeconds / 1000.0) - (hrs * 60 + min) * 60;
time.append(QString::number(sec) + " sec");
ui->textEdit->appendPlainText(time);
}
/**
* Hack to get the count results aligned.
* @return Align string.
*/
QString PrimeSieveGUI::getAlign() {
// find the text with the largest width
QString maxSizeText;
for (int i = 0; i < PrimeSieveProcess::COUNTS_SIZE; i++) {
if (flags_ & (COUNT_PRIMES << i))
if (maxSizeText.size() < primeText_[i].size())
maxSizeText = primeText_[i];
}
// print test string
ui->textEdit->insertPlainText(maxSizeText + ": ");
// get width in pixels
int maxWidth = ui->textEdit->cursorRect().left();
// remove test string
ui->textEdit->moveCursor(QTextCursor::StartOfLine, QTextCursor::KeepAnchor);
ui->textEdit->textCursor().removeSelectedText();
// must be an error, do not use tabs
if (maxWidth <= 20 || maxWidth >= 1024)
return ": ";
// set tab width
ui->textEdit->setTabStopWidth(maxWidth);
return ":\t";
}
/**
* Clean up after sieving is finished or canceled (abort all
* running processes).
*/
void PrimeSieveGUI::cleanUp() {
// stop the timer first
progressBarTimer_.stop();
// kill all processes that are still running
for (; !processes_.isEmpty(); processes_.pop_back())
delete processes_.back();
// reset
finishedProcesses_ = 0;
// invert buttons
ui->cancelButton->setDisabled(true);
ui->sieveButton->setEnabled(true);
// force repainting widgets
this->repaint();
}
<commit_msg>better (slightly smaller) Windows GUI size<commit_after>/*
* PrimeSieveGUI.cpp -- This file is part of primesieve
*
* Copyright (C) 2010 Kim Walisch, <kim.walisch@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include "PrimeSieveGUI.h"
#include "ui_PrimeSieveGUI.h"
#include "../src/pmath.h"
#include <QThread>
#include <QSize>
#include <QMessageBox>
#include <QTextCursor>
#include <cstdlib>
#include <stdexcept>
PrimeSieveGUI::PrimeSieveGUI(QWidget *parent) :
QMainWindow(parent), ui(new Ui::PrimeSieveGUI), saveAct_(0), quitAct_(0),
aboutAct_(0), alignmentGroup_(0), validator_(0), finishedProcesses_(0) {
ui->setupUi(this);
this->initMemberVariables();
this->initGUI();
this->initConnections();
}
PrimeSieveGUI::~PrimeSieveGUI() {
// kill all processes
this->cleanUp();
// free all allocated memory
if (saveAct_ != 0) delete saveAct_;
if (quitAct_ != 0) delete quitAct_;
if (aboutAct_ != 0) delete aboutAct_;
if (alignmentGroup_ != 0) delete alignmentGroup_;
if (validator_ != 0) delete validator_;
for (; !countAct_.isEmpty(); countAct_.pop_back())
delete countAct_.back();
for (; !printAct_.isEmpty(); printAct_.pop_back())
delete printAct_.back();
// Qt code
delete ui;
}
void PrimeSieveGUI::changeEvent(QEvent *e) {
QMainWindow::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void PrimeSieveGUI::initMemberVariables() {
primeText_.push_back("Prime numbers");
primeText_.push_back("Twin primes");
primeText_.push_back("Prime triplets");
primeText_.push_back("Prime quadruplets");
primeText_.push_back("Prime quintuplets");
primeText_.push_back("Prime sextuplets");
primeText_.push_back("Prime septuplets");
// get the number of logical CPU cores
int maxCpuCores = QThread::idealThreadCount();
if (maxCpuCores > 0)
isCpuDetected_ = true;
else {
isCpuDetected_ = false;
// default value for undetected CPUs
maxCpuCores = DEFAULT_MAX_CPU_CORES;
}
this->initCpuCoresComboBox(maxCpuCores);
}
void PrimeSieveGUI::initGUI() {
// set the main window title
this->setWindowTitle(APPLICATION_NAME + " " + APPLICATION_VERSION);
// create the menu bar
this->createMenu(primeText_);
// fill with values
this->initSieveSizeComboBox();
// set an ideal ComboBox width
int width = ui->sieveSizeComboBox->minimumSizeHint().width();
ui->sieveSizeComboBox->setFixedWidth(width);
ui->cpuCoresComboBox->setFixedWidth(width);
if (!isCpuDetected_) {
ui->autoSetCheckBox->setChecked(false);
ui->autoSetCheckBox->setDisabled(true);
}
// limit input to 20 digits max
QRegExp rx("[0-9]\\d{0,19}");
validator_ = new QRegExpValidator(rx, this);
ui->lowerBoundLineEdit->setValidator(validator_);
ui->upperBoundLineEdit->setValidator(validator_);
// set a nice GUI size
int guiWidth = this->minimumSizeHint().width();
int guiHeight = this->sizeHint().height();
#if defined(Q_OS_WIN)
guiHeight = static_cast<int> (guiHeight * 0.94);
#elif defined(Q_OS_MAC)
guiHeight = static_cast<int> (guiHeight * 0.96);
#endif
this->resize(QSize(guiWidth, guiHeight));
}
void PrimeSieveGUI::initConnections() {
// advances the progress bar
connect(&progressBarTimer_, SIGNAL(timeout()), this, SLOT(
advanceProgressBar()));
// autoSetCpuCores() connections
if (isCpuDetected_) {
connect(ui->lowerBoundLineEdit, SIGNAL(textChanged(const QString &)),
this, SLOT(autoSetCpuCores()));
connect(ui->upperBoundLineEdit, SIGNAL(textChanged(const QString &)),
this, SLOT(autoSetCpuCores()));
connect(ui->autoSetCheckBox, SIGNAL(toggled(bool)),
this, SLOT(autoSetCpuCores()));
}
}
/**
* Fill the sieveSizeComboBox with power of 2 values from
* 16 KB till 8192 KB.
*/
void PrimeSieveGUI::initSieveSizeComboBox() {
for (int i = MINIMUM_SIEVE_SIZE; i <= MAXIMUM_SIEVE_SIZE; i *= 2)
ui->sieveSizeComboBox->addItem(QString::number(i) + " KB");
// set the default sieve size
QString sieveSize = QString::number(DEFAULT_SIEVE_SIZE) + " KB";
this->setComboBox(ui->sieveSizeComboBox, sieveSize);
}
/**
* Fill the cpuCoresComboBox with power of 2 values from 1 till
* maxCpuCores.
*/
void PrimeSieveGUI::initCpuCoresComboBox(int maxCpuCores) {
for (int i = 1; i < maxCpuCores; i *= 2)
ui->cpuCoresComboBox->addItem(QString::number(i));
ui->cpuCoresComboBox->addItem(QString::number(maxCpuCores));
// default 1 CPU core
this->setComboBox(ui->cpuCoresComboBox, "1");
}
/**
* Get the users lower and upper bound for prime sieving.
*/
void PrimeSieveGUI::getBounds(qulonglong* lowerBound, qulonglong* upperBound) {
QString lbound = ui->lowerBoundLineEdit->text();
QString ubound = ui->upperBoundLineEdit->text();
if (ubound.isEmpty() || lbound.isEmpty())
throw std::invalid_argument("Missing input.");
bool lOk = true;
bool uOk = true;
*lowerBound = lbound.toULongLong(&lOk, 10);
*upperBound = ubound.toULongLong(&uOk, 10);
if (!lOk || !uOk || *lowerBound >= UPPER_BOUND_LIMIT || *upperBound
>= UPPER_BOUND_LIMIT)
throw std::invalid_argument(
"Please use numbers >= 0 and < (2^64-1) - (2^32-1) * 10.");
if (*lowerBound > *upperBound)
throw std::invalid_argument(
"The lower bound must not be greater than the upper bound.");
}
/**
* Get the sieve size (in KiloBytes) from the sieveSizeComboBox.
* @post sieveSize >= 1 && sieveSize <= 8192.
*/
int PrimeSieveGUI::getSieveSize() {
QString sieveSize(ui->sieveSizeComboBox->currentText());
// remove " KB"
sieveSize.chop(3);
return sieveSize.toInt();
}
/**
* Get the current number of CPU cores from the cpuCoresComboBox.
*/
int PrimeSieveGUI::getCpuCores() {
return ui->cpuCoresComboBox->currentText().toInt();
}
/**
* Get the maximum number of CPU cores from the cpuCoresComboBox.
*/
int PrimeSieveGUI::getMaxCpuCores() {
int count = ui->cpuCoresComboBox->count();
return ui->cpuCoresComboBox->itemText(count - 1).toInt();
}
/**
* Show the text string in the ComboBox.
*/
void PrimeSieveGUI::setComboBox(QComboBox* comboBox, QString text) {
int index = comboBox->findText(text);
if (index < 0)
QMessageBox::critical(this, APPLICATION_NAME,
"Internal ComboBox error, please contact the developer.");
comboBox->setCurrentIndex(index);
}
/**
* The user has chosen a custom number of CPU cores.
*/
void PrimeSieveGUI::on_cpuCoresComboBox_activated() {
// disable "Auto set"
ui->autoSetCheckBox->setChecked(false);
}
/**
* Calculate an ideal number of CPU cores for sieving.
*/
int PrimeSieveGUI::getIdealCpuCoreCount(qulonglong lowerBound,
qulonglong upperBound, int maxCpuCores) {
int cpuCores = -1;
// I made some tests around 10^19 which showed that each CPU core
// should at least sieve an interval of sqrt(upperBound) / 6 for a
// performance benefit
qulonglong interval = U32SQRT(upperBound) / 6;
if (interval < MINIMUM_THREAD_INTERVAL)
interval = MINIMUM_THREAD_INTERVAL;
// use all CPU cores for big sieve intervals
if (maxCpuCores * interval <= upperBound - lowerBound)
cpuCores = maxCpuCores;
else {
// use less CPU cores for small sieve intervals
cpuCores = static_cast<int> ((upperBound - lowerBound) / interval);
// floor to the next power of 2 value
cpuCores = 1 << floorLog2(cpuCores);
}
return cpuCores;
}
/**
* Show the ideal CPU core number in the cpuCoresComboBox (if
* "Auto set" is enabled).
*/
void PrimeSieveGUI::autoSetCpuCores() {
if (ui->autoSetCheckBox->isEnabled() &&
ui->autoSetCheckBox->isChecked()) {
qulonglong lowerBound = 0;
qulonglong upperBound = 0;
QString cpuCores("1");
try {
// get the users lower and upper bound
this->getBounds(&lowerBound, &upperBound);
// get an ideal number of CPU cores
cpuCores.setNum(this->getIdealCpuCoreCount(lowerBound, upperBound,
this->getMaxCpuCores()));
} catch (...) {
}
// set to the ideal CPU core number
this->setComboBox(ui->cpuCoresComboBox, cpuCores);
}
}
/**
* Cancel sieving.
*/
void PrimeSieveGUI::on_cancelButton_clicked() {
ui->cancelButton->setDisabled(true);
// set to 0 percent
ui->progressBar->setValue(0);
// too late to abort
if ((flags_ & PRINT_FLAGS) && processes_.front()->isFinished())
return;
// kill all running processes
this->cleanUp();
}
void PrimeSieveGUI::advanceProgressBar() {
// delay the timer after 60 sec
if (progressBarTimer_.interval() < 100 && time_.elapsed() > 60000)
progressBarTimer_.setInterval(100);
// in percents
float status = 0.0f;
// combine the status of all processes
for (int i = 0; i < processes_.size(); i++)
status += processes_[i]->getStatus();
status /= processes_.size();
int permil = static_cast<int> (status * 10.0f);
// advance the progressBar
ui->progressBar->setValue(permil);
}
/**
* Print the sieving results and clean up.
*/
void PrimeSieveGUI::printResults() {
// add newline
if (!ui->textEdit->toPlainText().isEmpty())
ui->textEdit->appendPlainText("");
QString align = this->getAlign();
// combine the count results of all processes
QVector<qlonglong> combinedCount(PrimeSieveProcess::COUNTS_SIZE, 0);
for (int i = 0; i < processes_.size(); i++) {
for (int j = 0; j < combinedCount.size(); j++)
combinedCount[j] += processes_[i]->getCounts(j);
}
// print prime counts
for (int i = 0; i < combinedCount.size(); i++) {
if (combinedCount[i] >= 0)
ui->textEdit->appendPlainText(primeText_[i] + align +
QString::number(combinedCount[i]));
}
// add newline for prime k-tuplets
if (flags_ & (COUNT_FLAGS - COUNT_PRIMES))
ui->textEdit->appendPlainText("");
// print time
QString time("Elapsed time" + align);
int milliSeconds = time_.elapsed();
int hrs = (milliSeconds / 3600000);
int min = (milliSeconds / 60000) % 60;
if (hrs > 0)
time.append(QString::number(hrs) + " hrs ");
if (min > 0)
time.append(QString::number(min) + " min ");
double sec = (milliSeconds / 1000.0) - (hrs * 60 + min) * 60;
time.append(QString::number(sec) + " sec");
ui->textEdit->appendPlainText(time);
}
/**
* Hack to get the count results aligned.
* @return Align string.
*/
QString PrimeSieveGUI::getAlign() {
// find the text with the largest width
QString maxSizeText;
for (int i = 0; i < PrimeSieveProcess::COUNTS_SIZE; i++) {
if (flags_ & (COUNT_PRIMES << i))
if (maxSizeText.size() < primeText_[i].size())
maxSizeText = primeText_[i];
}
// print test string
ui->textEdit->insertPlainText(maxSizeText + ": ");
// get width in pixels
int maxWidth = ui->textEdit->cursorRect().left();
// remove test string
ui->textEdit->moveCursor(QTextCursor::StartOfLine, QTextCursor::KeepAnchor);
ui->textEdit->textCursor().removeSelectedText();
// must be an error, do not use tabs
if (maxWidth <= 20 || maxWidth >= 1024)
return ": ";
// set tab width
ui->textEdit->setTabStopWidth(maxWidth);
return ":\t";
}
/**
* Clean up after sieving is finished or canceled (abort all
* running processes).
*/
void PrimeSieveGUI::cleanUp() {
// stop the timer first
progressBarTimer_.stop();
// kill all processes that are still running
for (; !processes_.isEmpty(); processes_.pop_back())
delete processes_.back();
// reset
finishedProcesses_ = 0;
// invert buttons
ui->cancelButton->setDisabled(true);
ui->sieveButton->setEnabled(true);
// force repainting widgets
this->repaint();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: fmtclbl.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2004-08-23 08:32:04 $
*
* 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 _FMTCLBL_HXX
#define _FMTCLBL_HXX
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif
#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
class IntlWrapper;
class SW_DLLPUBLIC SwFmtNoBalancedColumns : public SfxBoolItem
{
public:
SwFmtNoBalancedColumns( BOOL bFlag = FALSE )
: SfxBoolItem( RES_COLUMNBALANCE, bFlag ) {}
// "pure virtual Methoden" vom SfxPoolItem
virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const;
virtual SfxPoolItem* Create(SvStream &, USHORT) const;
virtual SvStream& Store(SvStream &, USHORT nItemVersion ) const;
/* virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
*/ virtual USHORT GetVersion( USHORT nFFVer ) const;
};
inline const SwFmtNoBalancedColumns &SwAttrSet::GetBalancedColumns(BOOL bInP) const
{ return (const SwFmtNoBalancedColumns&)Get( RES_COLUMNBALANCE, bInP ); }
inline const SwFmtNoBalancedColumns &SwFmt::GetBalancedColumns(BOOL bInP) const
{ return aSet.GetBalancedColumns( bInP ); }
#endif
<commit_msg>INTEGRATION: CWS os44 (1.6.162); FILE MERGED 2004/11/24 13:57:05 os 1.6.162.1: #i37761# sw3io files removed<commit_after>/*************************************************************************
*
* $RCSfile: fmtclbl.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-01-05 15:48:34 $
*
* 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 _FMTCLBL_HXX
#define _FMTCLBL_HXX
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif
#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
class IntlWrapper;
class SW_DLLPUBLIC SwFmtNoBalancedColumns : public SfxBoolItem
{
public:
SwFmtNoBalancedColumns( BOOL bFlag = FALSE )
: SfxBoolItem( RES_COLUMNBALANCE, bFlag ) {}
// "pure virtual Methoden" vom SfxPoolItem
virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const;
};
inline const SwFmtNoBalancedColumns &SwAttrSet::GetBalancedColumns(BOOL bInP) const
{ return (const SwFmtNoBalancedColumns&)Get( RES_COLUMNBALANCE, bInP ); }
inline const SwFmtNoBalancedColumns &SwFmt::GetBalancedColumns(BOOL bInP) const
{ return aSet.GetBalancedColumns( bInP ); }
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2012 Plenluno All rights reserved.
#include <string>
#include "libj/string.h"
namespace libj {
const Size NO_POS = -1;
const Char NO_CHAR = -1;
class StringImpl : public String {
public:
Size length() const {
return str8_ ? str8_->length() :
str32_ ? str32_->length() : 0;
}
Char charAt(Size index) const {
if (index >= length())
return NO_CHAR;
return str8_ ? str8_->at(index) :
str32_ ? str32_->at(index) : NO_CHAR;
}
Cptr substring(Size begin) const {
if (begin > length()) {
Cptr p(static_cast<String*>(0));
return p;
} else if (begin == 0) {
Cptr p(this);
return p;
} else if (str8_) {
Cptr p(new StringImpl(str8_, begin));
return p;
} else { // if (str32_)
Cptr p(new StringImpl(str32_, begin));
return p;
}
}
Cptr substring(Size begin, Size end) const {
Size len = length();
if (begin > len || end > len || begin > end) {
Cptr p(static_cast<String*>(0));
return p;
} else if (begin == 0 && end == len) {
Cptr p(this);
return p;
} else if (str8_) {
Cptr p(new StringImpl(str8_, begin, end - begin));
return p;
} else { // if (str32_)
Cptr p(new StringImpl(str32_, begin, end - begin));
return p;
}
}
Cptr concat(Cptr other) const {
if (this->isEmpty() || !other) {
return other;
} else if (other->isEmpty()) {
Cptr p(this);
return p;
}
if (this->str8_ && other->isAscii()) {
StringImpl* s = new StringImpl(str8_);
Size len = other->length();
for (Size i = 0; i < len; i++)
s->str8_->push_back(static_cast<int8_t>(other->charAt(i)));
Cptr p(s);
return p;
} else if (this->str8_ && !other->isAscii()) {
StringImpl* s = new StringImpl();
s->str32_ = new Str32();
Size len = this->length();
for (Size i = 0; i < len; i++)
s->str32_->push_back(other->charAt(i));
len = other->length();
for (Size i = 0; i < len; i++)
s->str32_->push_back(other->charAt(i));
Cptr p(s);
return p;
} else if (this->str32_ && other->isAscii()) {
StringImpl* s = new StringImpl(str32_);
Size len = this->length();
for (Size i = 0; i < len; i++)
s->str32_->push_back(other->charAt(i));
Cptr p(s);
return p;
} else { // if (this->str32_ && !other->isAscii())
StringImpl* s = new StringImpl(str32_);
Size len = this->length();
for (Size i = 0; i < len; i++)
s->str32_->push_back(other->charAt(i));
Cptr p(s);
return p;
}
}
Int compareTo(Type<Object>::Cptr that) const {
Int result = Object::compareTo(that);
if (result)
return result;
Type<String>::Cptr other = STATIC_CPTR_CAST(String)(that);
Size len1 = this->length();
Size len2 = other->length();
Size len = len1 < len2 ? len1 : len2;
for (Size i = 0; i < len; i++) {
Char c1 = this->charAt(i);
Char c2 = other->charAt(i);
if (c1 != c2)
return c1 - c2;
}
return len1 - len2;
}
bool startsWith(Cptr other, Size offset) const {
Size len1 = this->length();
Size len2 = other->length();
if (len1 < offset + len2)
return false;
for (Size i = 0; i < len2; i++)
if (this->charAt(offset + i) != other->charAt(i))
return false;
return true;
}
bool endsWith(Cptr other) const {
Size len1 = this->length();
Size len2 = other->length();
if (len1 < len2)
return false;
Size pos = len1 - len2;
for (Size i = 0; i < len2; i++)
if (this->charAt(pos + i) != other->charAt(i))
return false;
return true;
}
Size indexOf(Char c, Size offset) const {
Size len = length();
for (Size i = offset; i < len; i++)
if (charAt(i) == c)
return i;
return NO_POS;
}
Size indexOf(Cptr other, Size offset) const {
// TODO(PL): make it more efficient
Size len1 = this->length();
Size len2 = other->length();
if (len1 < offset + len2)
return NO_POS;
Size n = len1 - len2 + 1;
for (Size i = offset; i < n; i++)
if (startsWith(other, i))
return i;
return NO_POS;
}
Size lastIndexOf(Char c, Size offset) const {
Size len = length();
if (len == 0)
return NO_POS;
for (Size i = offset < len ? offset : len-1; ; i--) {
if (charAt(i) == c)
return i;
if (i == 0)
break;
}
return NO_POS;
}
Size lastIndexOf(Cptr other, Size offset) const {
// TODO(PL): make it more efficient
Size len1 = this->length();
Size len2 = other->length();
if (len1 < offset + len2)
return NO_POS;
Size from = len1 - len2;
from = offset < from ? offset : from;
for (Size i = from; ; i--) {
if (startsWith(other, i))
return i;
if (i == 0)
break;
}
return NO_POS;
}
bool isEmpty() const {
return length() == 0;
}
bool isAscii() const {
return str8_ ? true : str32_ ? false : true;
}
Cptr toString() const {
Cptr p(new StringImpl(this));
return p;
}
public:
static Cptr create() {
Cptr p(new StringImpl());
return p;
}
static Cptr create(const void* data, Encoding enc, Size max) {
// TODO(PL): temp
if (enc == ASCII) {
Cptr p(new StringImpl(static_cast<const int8_t*>(data), max));
return p;
} else if (enc == UTF8) {
// TODO(PL): use ConvertUTF8toUTF32
Cptr p(new StringImpl());
return p;
} else {
Cptr p(new StringImpl());
return p;
}
}
private:
typedef std::basic_string<int8_t> Str8;
typedef std::basic_string<int32_t> Str32;
Str8* str8_;
Str32* str32_;
StringImpl()
: str8_(0)
, str32_(0) {}
StringImpl(const Str8* s)
: str8_(s ? new Str8(*s) : 0)
, str32_(0) {}
StringImpl(const Str32* s)
: str8_(0)
, str32_(s ? new Str32(*s) : 0) {}
StringImpl(const Str8* s, Size pos, Size count = NO_POS)
: str8_(s ? new Str8(*s, pos, count) : 0)
, str32_(0) {}
StringImpl(const Str32* s, Size pos, Size count = NO_POS)
: str8_(0)
, str32_(s ? new Str32(*s, pos, count) : 0) {}
StringImpl(const int8_t* data, Size count = NO_POS)
: str8_(0)
, str32_(0) {
if (!data)
return;
for (Size i = 0; i < count; i++) {
if (data[i] == 0) {
str8_ = new Str8(data);
return;
}
}
str8_ = new Str8(data, count);
}
StringImpl(const int32_t* data, Size count = NO_POS)
: str8_(0)
, str32_(0) {
if (!data)
return;
for (Size i = 0; i < count; i++) {
if (data[i] == 0) {
str32_ = new Str32(data);
return;
}
}
str32_ = new Str32(data, count);
}
StringImpl(const StringImpl* s)
: str8_(s->str8_)
, str32_(s->str32_) {
}
};
Type<String>::Cptr String::create() {
return StringImpl::create();
}
Type<String>::Cptr String::create(const void* data, Encoding enc, Size max) {
return StringImpl::create(data, enc, max);
}
} // namespace libj
<commit_msg>fix memory leak<commit_after>// Copyright (c) 2012 Plenluno All rights reserved.
#include <string>
#include "libj/string.h"
namespace libj {
const Size NO_POS = -1;
const Char NO_CHAR = -1;
class StringImpl : public String {
public:
Size length() const {
return str8_ ? str8_->length() :
str32_ ? str32_->length() : 0;
}
Char charAt(Size index) const {
if (index >= length())
return NO_CHAR;
return str8_ ? str8_->at(index) :
str32_ ? str32_->at(index) : NO_CHAR;
}
Cptr substring(Size begin) const {
if (begin > length()) {
Cptr p(static_cast<String*>(0));
return p;
} else if (begin == 0) {
Cptr p(this);
return p;
} else if (str8_) {
Cptr p(new StringImpl(str8_, begin));
return p;
} else { // if (str32_)
Cptr p(new StringImpl(str32_, begin));
return p;
}
}
Cptr substring(Size begin, Size end) const {
Size len = length();
if (begin > len || end > len || begin > end) {
Cptr p(static_cast<String*>(0));
return p;
} else if (begin == 0 && end == len) {
Cptr p(this);
return p;
} else if (str8_) {
Cptr p(new StringImpl(str8_, begin, end - begin));
return p;
} else { // if (str32_)
Cptr p(new StringImpl(str32_, begin, end - begin));
return p;
}
}
Cptr concat(Cptr other) const {
if (this->isEmpty() || !other) {
return other;
} else if (other->isEmpty()) {
Cptr p(this);
return p;
}
if (this->str8_ && other->isAscii()) {
StringImpl* s = new StringImpl(str8_);
Size len = other->length();
for (Size i = 0; i < len; i++)
s->str8_->push_back(static_cast<int8_t>(other->charAt(i)));
Cptr p(s);
return p;
} else if (this->str8_ && !other->isAscii()) {
StringImpl* s = new StringImpl();
s->str32_ = new Str32();
Size len = this->length();
for (Size i = 0; i < len; i++)
s->str32_->push_back(other->charAt(i));
len = other->length();
for (Size i = 0; i < len; i++)
s->str32_->push_back(other->charAt(i));
Cptr p(s);
return p;
} else if (this->str32_ && other->isAscii()) {
StringImpl* s = new StringImpl(str32_);
Size len = this->length();
for (Size i = 0; i < len; i++)
s->str32_->push_back(other->charAt(i));
Cptr p(s);
return p;
} else { // if (this->str32_ && !other->isAscii())
StringImpl* s = new StringImpl(str32_);
Size len = this->length();
for (Size i = 0; i < len; i++)
s->str32_->push_back(other->charAt(i));
Cptr p(s);
return p;
}
}
Int compareTo(Type<Object>::Cptr that) const {
Int result = Object::compareTo(that);
if (result)
return result;
Type<String>::Cptr other = STATIC_CPTR_CAST(String)(that);
Size len1 = this->length();
Size len2 = other->length();
Size len = len1 < len2 ? len1 : len2;
for (Size i = 0; i < len; i++) {
Char c1 = this->charAt(i);
Char c2 = other->charAt(i);
if (c1 != c2)
return c1 - c2;
}
return len1 - len2;
}
bool startsWith(Cptr other, Size offset) const {
Size len1 = this->length();
Size len2 = other->length();
if (len1 < offset + len2)
return false;
for (Size i = 0; i < len2; i++)
if (this->charAt(offset + i) != other->charAt(i))
return false;
return true;
}
bool endsWith(Cptr other) const {
Size len1 = this->length();
Size len2 = other->length();
if (len1 < len2)
return false;
Size pos = len1 - len2;
for (Size i = 0; i < len2; i++)
if (this->charAt(pos + i) != other->charAt(i))
return false;
return true;
}
Size indexOf(Char c, Size offset) const {
Size len = length();
for (Size i = offset; i < len; i++)
if (charAt(i) == c)
return i;
return NO_POS;
}
Size indexOf(Cptr other, Size offset) const {
// TODO(PL): make it more efficient
Size len1 = this->length();
Size len2 = other->length();
if (len1 < offset + len2)
return NO_POS;
Size n = len1 - len2 + 1;
for (Size i = offset; i < n; i++)
if (startsWith(other, i))
return i;
return NO_POS;
}
Size lastIndexOf(Char c, Size offset) const {
Size len = length();
if (len == 0)
return NO_POS;
for (Size i = offset < len ? offset : len-1; ; i--) {
if (charAt(i) == c)
return i;
if (i == 0)
break;
}
return NO_POS;
}
Size lastIndexOf(Cptr other, Size offset) const {
// TODO(PL): make it more efficient
Size len1 = this->length();
Size len2 = other->length();
if (len1 < offset + len2)
return NO_POS;
Size from = len1 - len2;
from = offset < from ? offset : from;
for (Size i = from; ; i--) {
if (startsWith(other, i))
return i;
if (i == 0)
break;
}
return NO_POS;
}
bool isEmpty() const {
return length() == 0;
}
bool isAscii() const {
return str8_ ? true : str32_ ? false : true;
}
Cptr toString() const {
Cptr p(new StringImpl(this));
return p;
}
public:
static Cptr create() {
Cptr p(new StringImpl());
return p;
}
static Cptr create(const void* data, Encoding enc, Size max) {
// TODO(PL): temp
if (enc == ASCII) {
Cptr p(new StringImpl(static_cast<const int8_t*>(data), max));
return p;
} else if (enc == UTF8) {
// TODO(PL): use ConvertUTF8toUTF32
Cptr p(new StringImpl());
return p;
} else {
Cptr p(new StringImpl());
return p;
}
}
private:
typedef std::basic_string<int8_t> Str8;
typedef std::basic_string<int32_t> Str32;
Str8* str8_;
Str32* str32_;
StringImpl()
: str8_(0)
, str32_(0) {}
StringImpl(const Str8* s)
: str8_(s ? new Str8(*s) : 0)
, str32_(0) {}
StringImpl(const Str32* s)
: str8_(0)
, str32_(s ? new Str32(*s) : 0) {}
StringImpl(const Str8* s, Size pos, Size count = NO_POS)
: str8_(s ? new Str8(*s, pos, count) : 0)
, str32_(0) {}
StringImpl(const Str32* s, Size pos, Size count = NO_POS)
: str8_(0)
, str32_(s ? new Str32(*s, pos, count) : 0) {}
StringImpl(const int8_t* data, Size count = NO_POS)
: str8_(0)
, str32_(0) {
if (!data)
return;
for (Size i = 0; i < count; i++) {
if (data[i] == 0) {
str8_ = new Str8(data);
return;
}
}
str8_ = new Str8(data, count);
}
StringImpl(const int32_t* data, Size count = NO_POS)
: str8_(0)
, str32_(0) {
if (!data)
return;
for (Size i = 0; i < count; i++) {
if (data[i] == 0) {
str32_ = new Str32(data);
return;
}
}
str32_ = new Str32(data, count);
}
StringImpl(const StringImpl* s)
: str8_(s->str8_ ? new Str8(*(s->str8_)) : 0)
, str32_(s->str32_ ? new Str32(*(s->str32_)) : 0) {
}
public:
~StringImpl() {
delete str8_;
delete str32_;
}
};
Type<String>::Cptr String::create() {
return StringImpl::create();
}
Type<String>::Cptr String::create(const void* data, Encoding enc, Size max) {
return StringImpl::create(data, enc, max);
}
} // namespace libj
<|endoftext|> |
<commit_before>#include "safe_debug_print.h" // we implement this
#include "basic_int_to_string.h" // for [un]signed_integer_to_string_{dec|hex}
#include "assert.h"
#include <cstdio>
#include <cstring>
#include <cctype>
#include <algorithm>
using tinfra::signed_integer_to_string_dec;
using tinfra::unsigned_integer_to_string_dec;
using tinfra::unsigned_integer_to_string_hex;
void tinfra_safe_debug_print(tinfra::output_stream& out, char const* v) {
char buf[16];
const int len = signed_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, signed char const* v) {
char buf[16];
const int len = signed_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, unsigned char const* v) {
char buf[16];
const int len = unsigned_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, short const* v) {
char buf[16];
const int len = signed_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, unsigned short const* v) {
char buf[16];
const int len = unsigned_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, int const* v) {
char buf[24];
const int len = signed_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, unsigned int const* v) {
char buf[24];
const int len = unsigned_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, long const* v) {
char buf[48];
const int len = signed_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, unsigned long const* v) {
char buf[48];
const int len = unsigned_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, long long const* v) {
char buf[48];
const int len = signed_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, unsigned long long const* v) {
char buf[48];
const int len = unsigned_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, void const* const* v) {
char buf[48] = {"0x"};
const int len = unsigned_integer_to_string_hex((long long)*v, buf+2, sizeof(buf)-2);
TINFRA_ASSERT(len > 0);
out.write(buf, len+2);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, void* const* v) {
char buf[48] = {"0x"};
const int len = unsigned_integer_to_string_hex((long long)*v, buf+2, sizeof(buf)-2);
TINFRA_ASSERT(len > 0);
out.write(buf, len+2);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, const char** foo)
{
const char* i = *foo;
const char* ib = i;
while( *i ) {
if( *i == '\n' ) {
if( i != ib ) out.write(ib, (i-ib));
out.write("\\n",2);
ib = i+1;
} else if( *i == '\r' ) {
if( i != ib ) out.write(ib, (i-ib));
out.write("\\r",2);
ib = i+1;
} else if( !std::isprint(*i) ) {
if( i != ib ) out.write(ib, (i-ib));
char buf[20] = "\\x";
const int len = unsigned_integer_to_string_hex(*i, buf+2, sizeof(buf)-2);
TINFRA_ASSERT(len > 0);
out.write(buf, len + 2);
ib = i+1;
}
i++;
}
if( i != ib ) out.write(ib, (i-ib));
}
template<>
void tinfra_safe_debug_print<std::string>(tinfra::output_stream& out, std::string const* foo)
{
const char* i = foo->data();
const char* e = foo->data() + foo->size();
const char* ib = i;
while( i < e ) {
if( *i == '\n' ) {
if( i != ib ) out.write(ib, (i-ib));
out.write("\\n",2);
ib = i+1;
} else if( *i == '\r' ) {
if( i != ib ) out.write(ib, (i-ib));
out.write("\\r",2);
ib = i+1;
} else if( !std::isprint(*i) ) {
if( i != ib ) out.write(ib, (i-ib));
char buf[20] = "\\x";
const int len = unsigned_integer_to_string_hex(*i, buf+2, sizeof(buf)-2);
TINFRA_ASSERT(len > 0);
out.write(buf, len + 2);
ib = i+1;
}
i++;
}
if( i != ib ) out.write(ib, (i-ib));
}
<commit_msg>tinfra_safe_debug_print(...., void*): fixed (on mingw) by using uintptr_t<commit_after>#include "safe_debug_print.h" // we implement this
#include "basic_int_to_string.h" // for [un]signed_integer_to_string_{dec|hex}
#include "assert.h"
#include <cstdio>
#include <cstring>
#include <cctype>
#include <algorithm>
#include "stdint.h"
using tinfra::signed_integer_to_string_dec;
using tinfra::unsigned_integer_to_string_dec;
using tinfra::unsigned_integer_to_string_hex;
void tinfra_safe_debug_print(tinfra::output_stream& out, char const* v) {
char buf[16];
const int len = signed_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, signed char const* v) {
char buf[16];
const int len = signed_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, unsigned char const* v) {
char buf[16];
const int len = unsigned_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, short const* v) {
char buf[16];
const int len = signed_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, unsigned short const* v) {
char buf[16];
const int len = unsigned_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, int const* v) {
char buf[24];
const int len = signed_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, unsigned int const* v) {
char buf[24];
const int len = unsigned_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, long const* v) {
char buf[48];
const int len = signed_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, unsigned long const* v) {
char buf[48];
const int len = unsigned_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, long long const* v) {
char buf[48];
const int len = signed_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, unsigned long long const* v) {
char buf[48];
const int len = unsigned_integer_to_string_dec(*v, buf, sizeof(buf));
TINFRA_ASSERT(len > 0);
out.write(buf, len);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, void const* const* v) {
char buf[48] = {"0x"};
uintptr_t vi = (uintptr_t)*v;
const int len = unsigned_integer_to_string_hex(vi, buf+2, sizeof(buf)-2);
TINFRA_ASSERT(len > 0);
out.write(buf, len+2);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, void* const* v) {
char buf[48] = {"0x"};
uintptr_t vi = (uintptr_t)*v;
const int len = unsigned_integer_to_string_hex(vi, buf+2, sizeof(buf)-2);
TINFRA_ASSERT(len > 0);
out.write(buf, len+2);
}
void tinfra_safe_debug_print(tinfra::output_stream& out, const char** foo)
{
const char* i = *foo;
const char* ib = i;
while( *i ) {
if( *i == '\n' ) {
if( i != ib ) out.write(ib, (i-ib));
out.write("\\n",2);
ib = i+1;
} else if( *i == '\r' ) {
if( i != ib ) out.write(ib, (i-ib));
out.write("\\r",2);
ib = i+1;
} else if( !std::isprint(*i) ) {
if( i != ib ) out.write(ib, (i-ib));
char buf[20] = "\\x";
const int len = unsigned_integer_to_string_hex(*i, buf+2, sizeof(buf)-2);
TINFRA_ASSERT(len > 0);
out.write(buf, len + 2);
ib = i+1;
}
i++;
}
if( i != ib ) out.write(ib, (i-ib));
}
template<>
void tinfra_safe_debug_print<std::string>(tinfra::output_stream& out, std::string const* foo)
{
const char* i = foo->data();
const char* e = foo->data() + foo->size();
const char* ib = i;
while( i < e ) {
if( *i == '\n' ) {
if( i != ib ) out.write(ib, (i-ib));
out.write("\\n",2);
ib = i+1;
} else if( *i == '\r' ) {
if( i != ib ) out.write(ib, (i-ib));
out.write("\\r",2);
ib = i+1;
} else if( !std::isprint(*i) ) {
if( i != ib ) out.write(ib, (i-ib));
char buf[20] = "\\x";
const int len = unsigned_integer_to_string_hex(*i, buf+2, sizeof(buf)-2);
TINFRA_ASSERT(len > 0);
out.write(buf, len + 2);
ib = i+1;
}
i++;
}
if( i != ib ) out.write(ib, (i-ib));
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: unosrch.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2003-04-01 15:27:39 $
*
* 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 _UNOSRCH_HXX
#define _UNOSRCH_HXX
#ifndef _COM_SUN_STAR_UTIL_XPROPERTYREPLACE_HPP_
#include <com/sun/star/util/XPropertyReplace.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx> // helper for implementations
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
/******************************************************************************
*
******************************************************************************/
struct SfxItemPropertyMap;
class SwXTextDocument;
class SwSearchProperties_Impl;
class SfxItemSet;
namespace com{namespace sun{namespace star{namespace util{
struct SearchOptions;
}}}}
/*-----------------19.12.97 12:58-------------------
--------------------------------------------------*/
class SwXTextSearch : public cppu::WeakImplHelper3
<
::com::sun::star::util::XPropertyReplace,
::com::sun::star::lang::XServiceInfo,
::com::sun::star::lang::XUnoTunnel
>
{
friend class SwXTextDocument;
String sSearchText;
String sReplaceText;
SwSearchProperties_Impl* pSearchProperties;
SwSearchProperties_Impl* pReplaceProperties;
const SfxItemPropertyMap* _pMap;
sal_Bool bAll : 1;
sal_Bool bWord : 1;
sal_Bool bBack : 1;
sal_Bool bExpr : 1;
sal_Bool bCase : 1;
// sal_Bool bInSel: 1; // wie geht Suchen in Selektionen?
sal_Bool bStyles:1;
sal_Bool bSimilarity : 1;
sal_Bool bLevRelax :1;
sal_Int16 nLevExchange;
sal_Int16 nLevAdd;
sal_Int16 nLevRemove;
sal_Bool bIsValueSearch :1;
protected:
virtual ~SwXTextSearch();
public:
SwXTextSearch();
static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId();
//XUnoTunnel
virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
//XSearchDescriptor
virtual ::rtl::OUString SAL_CALL getSearchString( ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setSearchString( const ::rtl::OUString& aString ) throw(::com::sun::star::uno::RuntimeException);
//XReplaceDescriptor
virtual ::rtl::OUString SAL_CALL getReplaceString(void) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setReplaceString(const ::rtl::OUString& aReplaceString) throw( ::com::sun::star::uno::RuntimeException );
//XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
//XPropertyReplace
virtual sal_Bool SAL_CALL getValueSearch(void) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setValueSearch(sal_Bool ValueSearch_) throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > SAL_CALL getSearchAttributes(void) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setSearchAttributes(const ::com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& aSearchAttribs) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > SAL_CALL getReplaceAttributes(void) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setReplaceAttributes(const ::com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& aSearchAttribs) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );
//XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName(void) throw( ::com::sun::star::uno::RuntimeException );
virtual BOOL SAL_CALL supportsService(const ::rtl::OUString& ServiceName) throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(void) throw( ::com::sun::star::uno::RuntimeException );
void FillSearchItemSet(SfxItemSet& rSet) const;
void FillReplaceItemSet(SfxItemSet& rSet) const;
sal_Bool HasSearchAttributes() const;
sal_Bool HasReplaceAttributes() const;
void FillSearchOptions( ::com::sun::star::util::SearchOptions&
rSearchOpt ) const;
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.1288); FILE MERGED 2005/09/05 13:36:59 rt 1.3.1288.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unosrch.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 02:29:00 $
*
* 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 _UNOSRCH_HXX
#define _UNOSRCH_HXX
#ifndef _COM_SUN_STAR_UTIL_XPROPERTYREPLACE_HPP_
#include <com/sun/star/util/XPropertyReplace.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx> // helper for implementations
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
/******************************************************************************
*
******************************************************************************/
struct SfxItemPropertyMap;
class SwXTextDocument;
class SwSearchProperties_Impl;
class SfxItemSet;
namespace com{namespace sun{namespace star{namespace util{
struct SearchOptions;
}}}}
/*-----------------19.12.97 12:58-------------------
--------------------------------------------------*/
class SwXTextSearch : public cppu::WeakImplHelper3
<
::com::sun::star::util::XPropertyReplace,
::com::sun::star::lang::XServiceInfo,
::com::sun::star::lang::XUnoTunnel
>
{
friend class SwXTextDocument;
String sSearchText;
String sReplaceText;
SwSearchProperties_Impl* pSearchProperties;
SwSearchProperties_Impl* pReplaceProperties;
const SfxItemPropertyMap* _pMap;
sal_Bool bAll : 1;
sal_Bool bWord : 1;
sal_Bool bBack : 1;
sal_Bool bExpr : 1;
sal_Bool bCase : 1;
// sal_Bool bInSel: 1; // wie geht Suchen in Selektionen?
sal_Bool bStyles:1;
sal_Bool bSimilarity : 1;
sal_Bool bLevRelax :1;
sal_Int16 nLevExchange;
sal_Int16 nLevAdd;
sal_Int16 nLevRemove;
sal_Bool bIsValueSearch :1;
protected:
virtual ~SwXTextSearch();
public:
SwXTextSearch();
static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId();
//XUnoTunnel
virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
//XSearchDescriptor
virtual ::rtl::OUString SAL_CALL getSearchString( ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setSearchString( const ::rtl::OUString& aString ) throw(::com::sun::star::uno::RuntimeException);
//XReplaceDescriptor
virtual ::rtl::OUString SAL_CALL getReplaceString(void) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setReplaceString(const ::rtl::OUString& aReplaceString) throw( ::com::sun::star::uno::RuntimeException );
//XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
//XPropertyReplace
virtual sal_Bool SAL_CALL getValueSearch(void) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setValueSearch(sal_Bool ValueSearch_) throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > SAL_CALL getSearchAttributes(void) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setSearchAttributes(const ::com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& aSearchAttribs) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > SAL_CALL getReplaceAttributes(void) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setReplaceAttributes(const ::com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& aSearchAttribs) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );
//XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName(void) throw( ::com::sun::star::uno::RuntimeException );
virtual BOOL SAL_CALL supportsService(const ::rtl::OUString& ServiceName) throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(void) throw( ::com::sun::star::uno::RuntimeException );
void FillSearchItemSet(SfxItemSet& rSet) const;
void FillReplaceItemSet(SfxItemSet& rSet) const;
sal_Bool HasSearchAttributes() const;
sal_Bool HasReplaceAttributes() const;
void FillSearchOptions( ::com::sun::star::util::SearchOptions&
rSearchOpt ) const;
};
#endif
<|endoftext|> |
<commit_before>/*
* String hash map.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#ifndef BENG_PROXY_STRMAP_HXX
#define BENG_PROXY_STRMAP_HXX
#include <inline/compiler.h>
#include <boost/intrusive/set.hpp>
struct pool;
struct strmap {
struct Item {
typedef boost::intrusive::set_member_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> Hook;
Hook hook;
const char *key, *value;
Item(const char *_key, const char *_value)
:key(_key), value(_value) {}
class Compare {
gcc_pure
bool Less(const char *a, const char *b) const;
public:
gcc_pure
bool operator()(const char *a, const Item &b) const {
return Less(a, b.key);
}
gcc_pure
bool operator()(const Item &a, const char *b) const {
return Less(a.key, b);
}
gcc_pure
bool operator()(const Item &a, const Item &b) const {
return Less(a.key, b.key);
}
};
};
struct pool &pool;
typedef boost::intrusive::multiset<Item,
boost::intrusive::member_hook<Item, Item::Hook, &Item::hook>,
boost::intrusive::compare<Item::Compare>,
boost::intrusive::constant_time_size<false>> Map;
typedef Map::const_iterator const_iterator;
Map map;
explicit strmap(struct pool &_pool):pool(_pool) {}
strmap(struct pool &_pool, const strmap &src);
strmap(const strmap &) = delete;
const_iterator begin() const {
return map.begin();
}
const_iterator end() const {
return map.end();
}
void Add(const char *key, const char *value);
const char *Set(const char *key, const char *value);
const char *Remove(const char *key);
gcc_pure
const char *Get(const char *key) const;
gcc_pure
std::pair<const_iterator, const_iterator> EqualRange(const char *key) const;
};
struct strmap *gcc_malloc
strmap_new(struct pool *pool);
struct strmap *gcc_malloc
strmap_dup(struct pool *pool, struct strmap *src);
static inline const char *
strmap_get(const struct strmap *map, const char *key)
{
return map->Get(key);
}
/**
* This variation of strmap::Remove() allows the caller to pass
* map=nullptr.
*/
static inline const char *
strmap_remove_checked(struct strmap *map, const char *key)
{
return map != nullptr
? map->Remove(key)
: nullptr;
}
/**
* This variation of strmap_get() allows the caller to pass map=nullptr.
*/
gcc_pure
static inline const char *
strmap_get_checked(const struct strmap *map, const char *key)
{
return map != nullptr
? strmap_get(map, key)
: nullptr;
}
#endif
<commit_msg>strmap: use the base hook<commit_after>/*
* String hash map.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#ifndef BENG_PROXY_STRMAP_HXX
#define BENG_PROXY_STRMAP_HXX
#include <inline/compiler.h>
#include <boost/intrusive/set.hpp>
struct pool;
struct strmap {
struct Item : boost::intrusive::set_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> {
const char *key, *value;
Item(const char *_key, const char *_value)
:key(_key), value(_value) {}
class Compare {
gcc_pure
bool Less(const char *a, const char *b) const;
public:
gcc_pure
bool operator()(const char *a, const Item &b) const {
return Less(a, b.key);
}
gcc_pure
bool operator()(const Item &a, const char *b) const {
return Less(a.key, b);
}
gcc_pure
bool operator()(const Item &a, const Item &b) const {
return Less(a.key, b.key);
}
};
};
struct pool &pool;
typedef boost::intrusive::multiset<Item,
boost::intrusive::compare<Item::Compare>,
boost::intrusive::constant_time_size<false>> Map;
typedef Map::const_iterator const_iterator;
Map map;
explicit strmap(struct pool &_pool):pool(_pool) {}
strmap(struct pool &_pool, const strmap &src);
strmap(const strmap &) = delete;
const_iterator begin() const {
return map.begin();
}
const_iterator end() const {
return map.end();
}
void Add(const char *key, const char *value);
const char *Set(const char *key, const char *value);
const char *Remove(const char *key);
gcc_pure
const char *Get(const char *key) const;
gcc_pure
std::pair<const_iterator, const_iterator> EqualRange(const char *key) const;
};
struct strmap *gcc_malloc
strmap_new(struct pool *pool);
struct strmap *gcc_malloc
strmap_dup(struct pool *pool, struct strmap *src);
static inline const char *
strmap_get(const struct strmap *map, const char *key)
{
return map->Get(key);
}
/**
* This variation of strmap::Remove() allows the caller to pass
* map=nullptr.
*/
static inline const char *
strmap_remove_checked(struct strmap *map, const char *key)
{
return map != nullptr
? map->Remove(key)
: nullptr;
}
/**
* This variation of strmap_get() allows the caller to pass map=nullptr.
*/
gcc_pure
static inline const char *
strmap_get_checked(const struct strmap *map, const char *key)
{
return map != nullptr
? strmap_get(map, key)
: nullptr;
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2010-2012 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "CSSInputStream.h"
#include <assert.h>
#include <string.h>
#include <unicode/ucnv.h>
#include <algorithm>
namespace {
const char* const CSSDefaultEncoding = "utf-8";
}
CSSInputStream::CSSInputStream(std::istream& stream, const std::string& optionalEncoding) :
U16InputStream(stream, optionalEncoding)
{
}
bool CSSInputStream::detect(const char* p)
{
static char be[] = { 0x00, 0x40, 0x00, 0x63, 0x00, 0x68, 0x00, 0x61, 0x00, 0x72, 0x00, 0x73, 0x00, 0x65, 0x00, 0x74 };
static char le[] = { 0x40, 0x00, 0x63, 0x00, 0x68, 0x00, 0x61, 0x00, 0x72, 0x00, 0x73, 0x00, 0x65, 0x00, 0x74, 0x00 };
std::string u16 = "";
if (confidence == Certain)
return false;
if (strncmp(p, "\xfe\xff", 2) == 0 || strncmp(p, be, sizeof(be)) == 0) {
encoding = "utf-16be";
confidence = Irrelevant;
u16 = beToAscii((*p == '\xfe') ? p + 2 : p);
p = u16.c_str();
} else if (strncmp(p, "\xff\xfe", 2) == 0 || strncmp(p, le, sizeof(le)) == 0) {
encoding = "utf-16le";
confidence = Irrelevant;
u16 = leToAscii((*p == '\xff') ? p + 2 : p);
p = u16.c_str();
} else if (strncmp(p, "\xef\xbb\xbf", 3) == 0) {
encoding = "utf-8";
confidence = Irrelevant;
p += 3;
}
if (strncmp(p, "@charset", 8) != 0) {
if (confidence == Tentative)
encoding = CSSDefaultEncoding;
return false;
}
std::string tentative;
p += 8;
if (*p++ != ' ' || *p++ != '"') {
encoding = "";
return false;
}
for (;;) {
if (!*p) {
encoding = "";
return false;
}
if (*p == '"') {
if (*++p != ';') {
encoding = "";
return false;
}
break;
}
tentative += *p++;
}
if (confidence == Tentative) {
encoding = tentative;
return false;
}
if (strcasecmp(tentative.c_str(), "utf-16") == 0 && strncmp(encoding.c_str(), "utf-16", 6) == 0 ||
strcasecmp(encoding.c_str(), tentative.c_str()) == 0)
return false;
encoding = "";
return false;
}
<commit_msg>(CSSInputStream::detect) : Ignore malformed @charset rule.<commit_after>/*
* Copyright 2010-2012 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "CSSInputStream.h"
#include <assert.h>
#include <string.h>
#include <unicode/ucnv.h>
#include <algorithm>
namespace {
const char* const CSSDefaultEncoding = "utf-8";
}
CSSInputStream::CSSInputStream(std::istream& stream, const std::string& optionalEncoding) :
U16InputStream(stream, optionalEncoding)
{
}
bool CSSInputStream::detect(const char* p)
{
static char be[] = { 0x00, 0x40, 0x00, 0x63, 0x00, 0x68, 0x00, 0x61, 0x00, 0x72, 0x00, 0x73, 0x00, 0x65, 0x00, 0x74 };
static char le[] = { 0x40, 0x00, 0x63, 0x00, 0x68, 0x00, 0x61, 0x00, 0x72, 0x00, 0x73, 0x00, 0x65, 0x00, 0x74, 0x00 };
std::string u16 = "";
if (confidence == Certain)
return false;
if (strncmp(p, "\xfe\xff", 2) == 0 || strncmp(p, be, sizeof(be)) == 0) {
encoding = "utf-16be";
confidence = Irrelevant;
u16 = beToAscii((*p == '\xfe') ? p + 2 : p);
p = u16.c_str();
} else if (strncmp(p, "\xff\xfe", 2) == 0 || strncmp(p, le, sizeof(le)) == 0) {
encoding = "utf-16le";
confidence = Irrelevant;
u16 = leToAscii((*p == '\xff') ? p + 2 : p);
p = u16.c_str();
} else if (strncmp(p, "\xef\xbb\xbf", 3) == 0) {
encoding = "utf-8";
confidence = Irrelevant;
p += 3;
}
if (strncmp(p, "@charset", 8) != 0) {
if (confidence == Tentative)
encoding = CSSDefaultEncoding;
return false;
}
std::string tentative;
p += 8;
if (*p++ != ' ' || *p++ != '"')
tentative = CSSDefaultEncoding;
else {
for (;;) {
if (!*p) {
encoding = "";
return false;
}
if (*p == '"') {
if (*++p != ';')
tentative = CSSDefaultEncoding;
break;
}
tentative += *p++;
}
}
if (confidence == Tentative) {
encoding = tentative;
return false;
}
if (strcasecmp(tentative.c_str(), "utf-16") == 0 && strncmp(encoding.c_str(), "utf-16", 6) == 0 ||
strcasecmp(encoding.c_str(), tentative.c_str()) == 0)
return false;
encoding = "";
return false;
}
<|endoftext|> |
<commit_before>//
// TestGraph.cpp
// Graphs
//
// Created by Viktoras Laukevičius on 21/03/15.
// Copyright (c) 2015 Viktoras Laukevicius. All rights reserved.
//
#include <iostream>
#include "Graph.h"
#include "Vertex.h"
using namespace std;
class TestGraph
{
public:
TestGraph()
{
Graph graph;
int sCount = 4;
int dCount = 4;
Vertex *s[sCount];
for (int i = 0; i < sCount; i++) {
s[i] = new Vertex(VertexTypeSource, i, 0);
graph.sourceVertexes.push_back(s[i]);
}
Vertex *d[dCount];
for (int i = 0; i < sCount; i++) {
d[i] = new Vertex(VertexTypeDestination, i, 0);
graph.destinationVertexes.push_back(d[i]);
}
connectEachOther(s[0], d[0]);
connectEachOther(s[0], d[1]);
connectEachOther(s[1], d[1]);
connectEachOther(s[1], d[2]);
connectEachOther(s[2], d[3]);
connectEachOther(s[3], d[3]);
tout << ":test1: " << ((graph.isConnected() == false)? "passed" : "failed") << endl;
connectEachOther(s[2], d[1]);
tout << ":test2: " << ((graph.isConnected() == true)? "passed" : "failed") << endl;
graph.connectSourcesToEachOther();
tout << ":test3: " << (((s[0]->connections.size() == 4) && isConnected(s[0], new Vertex*[2]{s[1], s[2]}, 2))? "passed" : "failed") << endl;
tout << ":test4: " << (((s[1]->connections.size() == 4) && isConnected(s[1], new Vertex*[2]{s[0], s[2]}, 2))? "passed" : "failed") << endl;
tout << ":test5: " << (((s[2]->connections.size() == 5) && isConnected(s[2], new Vertex*[3]{s[0], s[1], s[3]}, 3))? "passed" : "failed") << endl;
tout << ":test6: " << (((s[3]->connections.size() == 2) && isConnected(s[3], new Vertex*[1]{s[2]}, 1))? "passed" : "failed") << endl;
}
private:
void connectEachOther(Vertex *v1, Vertex *v2)
{
v1->connectToVertex(v2);
v2->connectToVertex(v1);
}
bool isConnected(Vertex *main, Vertex *vertexes[], long size)
{
for (int i = 0; i < size; i++) {
if (find(main->connections.begin(), main->connections.end(), vertexes[i]) == main->connections.end()) {
return false;
}
}
return true;
}
};
<commit_msg>Unit-test covered source degrees histogram generator<commit_after>//
// TestGraph.cpp
// Graphs
//
// Created by Viktoras Laukevičius on 21/03/15.
// Copyright (c) 2015 Viktoras Laukevicius. All rights reserved.
//
#include <iostream>
#include "Graph.h"
#include "Vertex.h"
using namespace std;
class TestGraph
{
public:
TestGraph()
{
Graph graph;
int sCount = 4;
int dCount = 4;
Vertex *s[sCount];
for (int i = 0; i < sCount; i++) {
s[i] = new Vertex(VertexTypeSource, i, 0);
graph.sourceVertexes.push_back(s[i]);
}
Vertex *d[dCount];
for (int i = 0; i < sCount; i++) {
d[i] = new Vertex(VertexTypeDestination, i, 0);
graph.destinationVertexes.push_back(d[i]);
}
connectEachOther(s[0], d[0]);
connectEachOther(s[0], d[1]);
connectEachOther(s[1], d[1]);
connectEachOther(s[1], d[2]);
connectEachOther(s[2], d[3]);
connectEachOther(s[3], d[3]);
tout << ":test1: " << ((graph.isConnected() == false)? "passed" : "failed") << endl;
connectEachOther(s[2], d[1]);
tout << ":test2: " << ((graph.isConnected() == true)? "passed" : "failed") << endl;
graph.connectSourcesToEachOther();
tout << ":test3: " << (((s[0]->connections.size() == 4) && isConnected(s[0], new Vertex*[2]{s[1], s[2]}, 2))? "passed" : "failed") << endl;
tout << ":test4: " << (((s[1]->connections.size() == 4) && isConnected(s[1], new Vertex*[2]{s[0], s[2]}, 2))? "passed" : "failed") << endl;
tout << ":test5: " << (((s[2]->connections.size() == 5) && isConnected(s[2], new Vertex*[3]{s[0], s[1], s[3]}, 3))? "passed" : "failed") << endl;
tout << ":test6: " << (((s[3]->connections.size() == 2) && isConnected(s[3], new Vertex*[1]{s[2]}, 1))? "passed" : "failed") << endl;
long *sd = graph.getSourceDegrees(4);
tout << ":test7: " << (((sd[0] == 0) && (sd[1] == 1) && (sd[2] == 2) && (sd[3] == 1))? "passed" : "failed") << endl;
}
private:
void connectEachOther(Vertex *v1, Vertex *v2)
{
v1->connectToVertex(v2);
v2->connectToVertex(v1);
}
bool isConnected(Vertex *main, Vertex *vertexes[], long size)
{
for (int i = 0; i < size; i++) {
if (find(main->connections.begin(), main->connections.end(), vertexes[i]) == main->connections.end()) {
return false;
}
}
return true;
}
};
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/system_wrappers/include/rtp_to_ntp_estimator.h"
#include "webrtc/rtc_base/logging.h"
#include "webrtc/system_wrappers/include/clock.h"
namespace webrtc {
namespace {
// Number of RTCP SR reports to use to map between RTP and NTP.
const size_t kNumRtcpReportsToUse = 2;
// Calculates the RTP timestamp frequency from two pairs of NTP/RTP timestamps.
bool CalculateFrequency(int64_t ntp_ms1,
uint32_t rtp_timestamp1,
int64_t ntp_ms2,
uint32_t rtp_timestamp2,
double* frequency_khz) {
if (ntp_ms1 <= ntp_ms2)
return false;
*frequency_khz = static_cast<double>(rtp_timestamp1 - rtp_timestamp2) /
static_cast<double>(ntp_ms1 - ntp_ms2);
return true;
}
// Detects if there has been a wraparound between |old_timestamp| and
// |new_timestamp|, and compensates by adding 2^32 if that is the case.
bool CompensateForWrapAround(uint32_t new_timestamp,
uint32_t old_timestamp,
int64_t* compensated_timestamp) {
int64_t wraps = CheckForWrapArounds(new_timestamp, old_timestamp);
if (wraps < 0) {
// Reordering, don't use this packet.
return false;
}
*compensated_timestamp = new_timestamp + (wraps << 32);
return true;
}
bool Contains(const std::list<RtpToNtpEstimator::RtcpMeasurement>& measurements,
const RtpToNtpEstimator::RtcpMeasurement& other) {
for (const auto& measurement : measurements) {
if (measurement.IsEqual(other))
return true;
}
return false;
}
} // namespace
RtpToNtpEstimator::RtcpMeasurement::RtcpMeasurement(uint32_t ntp_secs,
uint32_t ntp_frac,
uint32_t timestamp)
: ntp_time(ntp_secs, ntp_frac), rtp_timestamp(timestamp) {}
bool RtpToNtpEstimator::RtcpMeasurement::IsEqual(
const RtcpMeasurement& other) const {
// Use || since two equal timestamps will result in zero frequency and in
// RtpToNtpMs, |rtp_timestamp_ms| is estimated by dividing by the frequency.
return (ntp_time == other.ntp_time) || (rtp_timestamp == other.rtp_timestamp);
}
// Class for converting an RTP timestamp to the NTP domain.
RtpToNtpEstimator::RtpToNtpEstimator() : consecutive_invalid_samples_(0) {}
RtpToNtpEstimator::~RtpToNtpEstimator() {}
void RtpToNtpEstimator::UpdateParameters() {
if (measurements_.size() != kNumRtcpReportsToUse)
return;
int64_t timestamp_new = measurements_.front().rtp_timestamp;
int64_t timestamp_old = measurements_.back().rtp_timestamp;
if (!CompensateForWrapAround(timestamp_new, timestamp_old, ×tamp_new))
return;
int64_t ntp_ms_new = measurements_.front().ntp_time.ToMs();
int64_t ntp_ms_old = measurements_.back().ntp_time.ToMs();
if (!CalculateFrequency(ntp_ms_new, timestamp_new, ntp_ms_old, timestamp_old,
¶ms_.frequency_khz)) {
return;
}
params_.offset_ms = timestamp_new - params_.frequency_khz * ntp_ms_new;
params_.calculated = true;
}
bool RtpToNtpEstimator::UpdateMeasurements(uint32_t ntp_secs,
uint32_t ntp_frac,
uint32_t rtp_timestamp,
bool* new_rtcp_sr) {
*new_rtcp_sr = false;
RtcpMeasurement new_measurement(ntp_secs, ntp_frac, rtp_timestamp);
if (Contains(measurements_, new_measurement)) {
// RTCP SR report already added.
return true;
}
if (!new_measurement.ntp_time.Valid())
return false;
int64_t ntp_ms_new = new_measurement.ntp_time.ToMs();
bool invalid_sample = false;
for (const auto& measurement : measurements_) {
if (ntp_ms_new <= measurement.ntp_time.ToMs()) {
// Old report.
invalid_sample = true;
break;
}
int64_t timestamp_new = new_measurement.rtp_timestamp;
if (!CompensateForWrapAround(timestamp_new, measurement.rtp_timestamp,
×tamp_new)) {
invalid_sample = true;
break;
}
if (timestamp_new <= measurement.rtp_timestamp) {
LOG(LS_WARNING)
<< "Newer RTCP SR report with older RTP timestamp, dropping";
invalid_sample = true;
break;
}
}
if (invalid_sample) {
++consecutive_invalid_samples_;
if (consecutive_invalid_samples_ < kMaxInvalidSamples) {
return false;
}
LOG(LS_WARNING) << "Multiple consecutively invalid RTCP SR reports, "
"clearing measurements.";
measurements_.clear();
}
consecutive_invalid_samples_ = 0;
// Insert new RTCP SR report.
if (measurements_.size() == kNumRtcpReportsToUse)
measurements_.pop_back();
measurements_.push_front(new_measurement);
*new_rtcp_sr = true;
// List updated, calculate new parameters.
UpdateParameters();
return true;
}
bool RtpToNtpEstimator::Estimate(int64_t rtp_timestamp,
int64_t* rtp_timestamp_ms) const {
if (!params_.calculated || measurements_.empty())
return false;
uint32_t rtp_timestamp_old = measurements_.back().rtp_timestamp;
int64_t rtp_timestamp_unwrapped;
if (!CompensateForWrapAround(rtp_timestamp, rtp_timestamp_old,
&rtp_timestamp_unwrapped)) {
return false;
}
double rtp_ms =
(static_cast<double>(rtp_timestamp_unwrapped) - params_.offset_ms) /
params_.frequency_khz +
0.5f;
if (rtp_ms < 0)
return false;
*rtp_timestamp_ms = rtp_ms;
return true;
}
int CheckForWrapArounds(uint32_t new_timestamp, uint32_t old_timestamp) {
if (new_timestamp < old_timestamp) {
// This difference should be less than -2^31 if we have had a wrap around
// (e.g. |new_timestamp| = 1, |rtcp_rtp_timestamp| = 2^32 - 1). Since it is
// cast to a int32_t, it should be positive.
if (static_cast<int32_t>(new_timestamp - old_timestamp) > 0) {
// Forward wrap around.
return 1;
}
} else if (static_cast<int32_t>(old_timestamp - new_timestamp) > 0) {
// This difference should be less than -2^31 if we have had a backward wrap
// around. Since it is cast to a int32_t, it should be positive.
return -1;
}
return 0;
}
} // namespace webrtc
<commit_msg>RtpToNtpEstimator:: Add a DCHECK to avoid div-by-0<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/system_wrappers/include/rtp_to_ntp_estimator.h"
#include "webrtc/rtc_base/checks.h"
#include "webrtc/rtc_base/logging.h"
#include "webrtc/system_wrappers/include/clock.h"
namespace webrtc {
namespace {
// Number of RTCP SR reports to use to map between RTP and NTP.
const size_t kNumRtcpReportsToUse = 2;
// Calculates the RTP timestamp frequency from two pairs of NTP/RTP timestamps.
bool CalculateFrequency(int64_t ntp_ms1,
uint32_t rtp_timestamp1,
int64_t ntp_ms2,
uint32_t rtp_timestamp2,
double* frequency_khz) {
if (ntp_ms1 <= ntp_ms2)
return false;
*frequency_khz = static_cast<double>(rtp_timestamp1 - rtp_timestamp2) /
static_cast<double>(ntp_ms1 - ntp_ms2);
return true;
}
// Detects if there has been a wraparound between |old_timestamp| and
// |new_timestamp|, and compensates by adding 2^32 if that is the case.
bool CompensateForWrapAround(uint32_t new_timestamp,
uint32_t old_timestamp,
int64_t* compensated_timestamp) {
int64_t wraps = CheckForWrapArounds(new_timestamp, old_timestamp);
if (wraps < 0) {
// Reordering, don't use this packet.
return false;
}
*compensated_timestamp = new_timestamp + (wraps << 32);
return true;
}
bool Contains(const std::list<RtpToNtpEstimator::RtcpMeasurement>& measurements,
const RtpToNtpEstimator::RtcpMeasurement& other) {
for (const auto& measurement : measurements) {
if (measurement.IsEqual(other))
return true;
}
return false;
}
} // namespace
RtpToNtpEstimator::RtcpMeasurement::RtcpMeasurement(uint32_t ntp_secs,
uint32_t ntp_frac,
uint32_t timestamp)
: ntp_time(ntp_secs, ntp_frac), rtp_timestamp(timestamp) {}
bool RtpToNtpEstimator::RtcpMeasurement::IsEqual(
const RtcpMeasurement& other) const {
// Use || since two equal timestamps will result in zero frequency and in
// RtpToNtpMs, |rtp_timestamp_ms| is estimated by dividing by the frequency.
return (ntp_time == other.ntp_time) || (rtp_timestamp == other.rtp_timestamp);
}
// Class for converting an RTP timestamp to the NTP domain.
RtpToNtpEstimator::RtpToNtpEstimator() : consecutive_invalid_samples_(0) {}
RtpToNtpEstimator::~RtpToNtpEstimator() {}
void RtpToNtpEstimator::UpdateParameters() {
if (measurements_.size() != kNumRtcpReportsToUse)
return;
int64_t timestamp_new = measurements_.front().rtp_timestamp;
int64_t timestamp_old = measurements_.back().rtp_timestamp;
if (!CompensateForWrapAround(timestamp_new, timestamp_old, ×tamp_new))
return;
int64_t ntp_ms_new = measurements_.front().ntp_time.ToMs();
int64_t ntp_ms_old = measurements_.back().ntp_time.ToMs();
if (!CalculateFrequency(ntp_ms_new, timestamp_new, ntp_ms_old, timestamp_old,
¶ms_.frequency_khz)) {
return;
}
params_.offset_ms = timestamp_new - params_.frequency_khz * ntp_ms_new;
params_.calculated = true;
}
bool RtpToNtpEstimator::UpdateMeasurements(uint32_t ntp_secs,
uint32_t ntp_frac,
uint32_t rtp_timestamp,
bool* new_rtcp_sr) {
*new_rtcp_sr = false;
RtcpMeasurement new_measurement(ntp_secs, ntp_frac, rtp_timestamp);
if (Contains(measurements_, new_measurement)) {
// RTCP SR report already added.
return true;
}
if (!new_measurement.ntp_time.Valid())
return false;
int64_t ntp_ms_new = new_measurement.ntp_time.ToMs();
bool invalid_sample = false;
for (const auto& measurement : measurements_) {
if (ntp_ms_new <= measurement.ntp_time.ToMs()) {
// Old report.
invalid_sample = true;
break;
}
int64_t timestamp_new = new_measurement.rtp_timestamp;
if (!CompensateForWrapAround(timestamp_new, measurement.rtp_timestamp,
×tamp_new)) {
invalid_sample = true;
break;
}
if (timestamp_new <= measurement.rtp_timestamp) {
LOG(LS_WARNING)
<< "Newer RTCP SR report with older RTP timestamp, dropping";
invalid_sample = true;
break;
}
}
if (invalid_sample) {
++consecutive_invalid_samples_;
if (consecutive_invalid_samples_ < kMaxInvalidSamples) {
return false;
}
LOG(LS_WARNING) << "Multiple consecutively invalid RTCP SR reports, "
"clearing measurements.";
measurements_.clear();
}
consecutive_invalid_samples_ = 0;
// Insert new RTCP SR report.
if (measurements_.size() == kNumRtcpReportsToUse)
measurements_.pop_back();
measurements_.push_front(new_measurement);
*new_rtcp_sr = true;
// List updated, calculate new parameters.
UpdateParameters();
return true;
}
bool RtpToNtpEstimator::Estimate(int64_t rtp_timestamp,
int64_t* rtp_timestamp_ms) const {
if (!params_.calculated || measurements_.empty())
return false;
uint32_t rtp_timestamp_old = measurements_.back().rtp_timestamp;
int64_t rtp_timestamp_unwrapped;
if (!CompensateForWrapAround(rtp_timestamp, rtp_timestamp_old,
&rtp_timestamp_unwrapped)) {
return false;
}
// params_.calculated should not be true unless params_.frequency_khz has been
// set to something non-zero.
RTC_DCHECK_NE(params_.frequency_khz, 0.0);
double rtp_ms =
(static_cast<double>(rtp_timestamp_unwrapped) - params_.offset_ms) /
params_.frequency_khz +
0.5f;
if (rtp_ms < 0)
return false;
*rtp_timestamp_ms = rtp_ms;
return true;
}
int CheckForWrapArounds(uint32_t new_timestamp, uint32_t old_timestamp) {
if (new_timestamp < old_timestamp) {
// This difference should be less than -2^31 if we have had a wrap around
// (e.g. |new_timestamp| = 1, |rtcp_rtp_timestamp| = 2^32 - 1). Since it is
// cast to a int32_t, it should be positive.
if (static_cast<int32_t>(new_timestamp - old_timestamp) > 0) {
// Forward wrap around.
return 1;
}
} else if (static_cast<int32_t>(old_timestamp - new_timestamp) > 0) {
// This difference should be less than -2^31 if we have had a backward wrap
// around. Since it is cast to a int32_t, it should be positive.
return -1;
}
return 0;
}
} // namespace webrtc
<|endoftext|> |
<commit_before>/******************************************************************************\
* File: frame.cpp
* Purpose: Implementation of wxExFrame class and support classes
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/tooltip.h> // for GetTip
#include <wx/extension/frame.h>
#include <wx/extension/app.h>
#include <wx/extension/art.h>
#include <wx/extension/fdrepdlg.h> // for wxExFindReplaceDialog
#include <wx/extension/frd.h>
#include <wx/extension/listview.h>
#include <wx/extension/stc.h>
#include <wx/extension/tool.h>
using namespace std;
#if wxUSE_GUI
#if wxUSE_STATUSBAR
wxExStatusBar* wxExFrame::m_StatusBar = NULL;
map<wxString, wxExPane> wxExFrame::m_Panes;
#endif
BEGIN_EVENT_TABLE(wxExFrame, wxFrame)
EVT_CLOSE(wxExFrame::OnClose)
EVT_FIND(wxID_ANY, wxExFrame::OnFindDialog)
EVT_FIND_CLOSE(wxID_ANY, wxExFrame::OnFindDialog)
EVT_FIND_NEXT(wxID_ANY, wxExFrame::OnFindDialog)
EVT_FIND_REPLACE(wxID_ANY, wxExFrame::OnFindDialog)
EVT_FIND_REPLACE_ALL(wxID_ANY, wxExFrame::OnFindDialog)
EVT_MENU(wxID_FIND, wxExFrame::OnCommand)
EVT_MENU(wxID_REPLACE, wxExFrame::OnCommand)
#if wxUSE_STATUSBAR
EVT_UPDATE_UI(ID_EDIT_STATUS_BAR, wxExFrame::OnUpdateUI)
#endif
END_EVENT_TABLE()
wxExFrame::wxExFrame(wxWindow* parent,
wxWindowID id,
const wxString& title,
long style,
const wxString& name)
: wxFrame(parent, id, title, wxDefaultPosition, wxDefaultSize, style, name)
, m_FindReplaceDialog(NULL)
, m_KeepPosAndSize(true)
{
if (wxExApp::GetConfig("Frame/Maximized", 0l))
{
Maximize(true);
}
SetSize(
wxExApp::GetConfig("Frame/X", 100),
wxExApp::GetConfig("Frame/Y", 100),
wxExApp::GetConfig("Frame/Width", 450),
wxExApp::GetConfig("Frame/Height", 350));
}
wxExFrame::wxExFrame(wxWindow* parent,
wxWindowID id,
const wxString& title,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString& name)
: wxFrame(parent, id, title, pos, size, style, name)
, m_FindReplaceDialog(NULL)
, m_KeepPosAndSize(false)
{
}
wxExFrame::~wxExFrame()
{
#if wxUSE_STATUSBAR
delete m_StatusBar;
#endif
}
wxExListView* wxExFrame::GetFocusedListView()
{
wxWindow* win = wxWindow::FindFocus();
if (win == NULL)
{
return NULL;
}
return wxDynamicCast(win, wxExListView);
}
wxExSTC* wxExFrame::GetFocusedSTC()
{
wxWindow* win = wxWindow::FindFocus();
if (win == NULL)
{
return NULL;
}
return wxDynamicCast(win, wxExSTC);
}
#if wxUSE_STATUSBAR
const wxExPane wxExFrame::GetPane(int pane) const
{
for (
map<wxString, wxExPane>::const_iterator it = m_Panes.begin();
it != m_Panes.end();
++it)
{
if (it->second.m_No == pane)
{
return it->second;
}
}
return wxExPane();
}
// TODO: Implement this.
void wxExFrame::GetSearchText()
{
}
// This is a static method, so no const possible.
int wxExFrame::GetPaneField(const wxString& pane)
{
map<wxString, wxExPane>::const_iterator it = m_Panes.find(pane);
if (it != m_Panes.end())
{
return it->second.m_No;
}
return -1;
}
#endif // wxUSE_STATUSBAR
void wxExFrame::OnClose(wxCloseEvent& event)
{
if (m_KeepPosAndSize)
{
// Set config values that might have changed.
if (IsMaximized())
{
wxExApp::SetConfig("Frame/Maximized", 1);
}
else
{
wxExApp::SetConfig("Frame/Maximized", 0);
const wxRect rect = GetRect();
wxExApp::SetConfig("Frame/X", rect.GetX());
wxExApp::SetConfig("Frame/Y", rect.GetY());
wxExApp::SetConfig("Frame/Width", rect.GetWidth());
wxExApp::SetConfig("Frame/Height", rect.GetHeight());
}
}
event.Skip();
}
void wxExFrame::OnCommand(wxCommandEvent& command)
{
switch (command.GetId())
{
case wxID_FIND:
if (m_FindReplaceDialog != NULL)
{
m_FindReplaceDialog->Destroy();
}
GetSearchText();
m_FindReplaceDialog = new wxExFindReplaceDialog(this, _("Find"));
m_FindReplaceDialog->Show();
break;
case wxID_REPLACE:
if (m_FindReplaceDialog != NULL)
{
m_FindReplaceDialog->Destroy();
}
GetSearchText();
m_FindReplaceDialog = new wxExFindReplaceDialog(
this,
_("Replace"),
wxFR_REPLACEDIALOG);
m_FindReplaceDialog->Show();
break;
default: wxFAIL; break;
}
}
#if wxUSE_STATUSBAR
wxStatusBar* wxExFrame::OnCreateStatusBar(
int number,
long style,
wxWindowID id,
const wxString& name)
{
m_StatusBar = new wxExStatusBar(this, id, style, name);
m_StatusBar->SetFieldsCount(number);
return m_StatusBar;
}
#endif
#if wxUSE_TOOLBAR
wxToolBar* wxExFrame::OnCreateToolBar(
long style,
wxWindowID id,
const wxString& name)
{
m_ToolBar = new wxExToolBar(this,
id,
wxDefaultPosition,
wxDefaultSize,
style,
wxSize(16, 15),
name);
return m_ToolBar;
}
#endif
void wxExFrame::OnFindDialog(wxFindDialogEvent& event)
{
if (event.GetEventType() == wxEVT_COMMAND_FIND_CLOSE)
{
m_FindReplaceDialog->Destroy();
m_FindReplaceDialog = NULL;
return;
}
wxExFindReplaceData* frd = wxExApp::GetConfig()->GetFindReplaceData();
const bool find_next = (frd->GetFlags() & wxFR_DOWN);
wxExSTC* stc = GetSTC();
if (stc != NULL)
{
stc->GetSearchText();
if (event.GetEventType() == wxEVT_COMMAND_FIND)
{
stc->FindNext(frd->GetFindString(), find_next);
}
else if (event.GetEventType() == wxEVT_COMMAND_FIND_NEXT)
{
stc->FindNext(frd->GetFindString(), find_next);
}
else if (event.GetEventType() == wxEVT_COMMAND_FIND_REPLACE)
{
stc->Replace(
frd->GetFindString(),
frd->GetReplaceString(),
frd->IsRegularExpression(),
find_next);
}
else if (event.GetEventType() == wxEVT_COMMAND_FIND_REPLACE_ALL)
{
stc->ReplaceAll(frd->GetFindString(), frd->GetReplaceString(), frd->IsRegularExpression());
}
else
{
wxFAIL;
}
}
wxExListView* lv = GetListView();
if (lv != NULL)
{
if (event.GetEventType() == wxEVT_COMMAND_FIND)
{
lv ->FindNext(frd->GetFindString(), find_next);
}
else if (event.GetEventType() == wxEVT_COMMAND_FIND_NEXT)
{
lv->FindNext(frd->GetFindString(), find_next);
}
else
{
wxFAIL;
}
}
// TODO: Add grid.
}
void wxExFrame::OnUpdateUI(wxUpdateUIEvent& event)
{
wxExSTC* stc = GetFocusedSTC();
if (stc == NULL) return;
switch (event.GetId())
{
#if wxUSE_STATUSBAR
case ID_EDIT_STATUS_BAR: stc->UpdateStatusBar("PaneLines"); break;
#endif
default:
wxFAIL;
break;
}
}
bool wxExFrame::OpenFile(
const wxExFileName& filename,
int line_number,
const wxString& match,
long flags)
{
wxExSTC* stc = GetFocusedSTC();
if (stc != NULL)
{
// Remove link flags;
const long new_flags = 0;
return stc->Open(filename, line_number, match, new_flags);
}
return false;
}
#if wxUSE_STATUSBAR
void wxExFrame::SetupStatusBar(
const vector<wxExPane>& panes,
long style,
wxWindowID id,
const wxString& name)
{
wxFrame::CreateStatusBar(panes.size(), style, id, name);
int* styles = new int[panes.size()];
int* widths = new int[panes.size()];
for (
vector<wxExPane>::const_iterator it = panes.begin();
it != panes.end();
++it)
{
m_Panes[it->m_Name] = *it;
styles[it->m_No] = it->GetStyle();
widths[it->m_No] = it->GetWidth();
}
m_StatusBar->SetStatusStyles(panes.size(), styles);
m_StatusBar->SetStatusWidths(panes.size(), widths);
delete[] styles;
delete[] widths;
}
#endif // wxUSE_STATUSBAR
#if wxUSE_STATUSBAR
void wxExFrame::StatusBarDoubleClicked(int field, const wxPoint& point)
{
if (field == GetPaneField("PaneLines"))
{
wxExSTC* stc = GetSTC();
if (stc != NULL) stc->GotoDialog();
}
else if (field == GetPaneField("PaneLexer"))
{
wxExSTC* stc = GetSTC();
if (stc != NULL) stc->LexerDialog();
}
else if (field == GetPaneField("PaneFileType"))
{
wxExSTC* stc = GetSTC();
if (stc != NULL) stc->FileTypeMenu();
}
else if (field == GetPaneField("PaneItems"))
{
wxExListView* list = GetListView();
if (list != NULL) list->GotoDialog();
}
else
{
// Clicking on another field, do nothing.
}
}
// This is a static method, so you cannot call wxFrame::SetStatusText.
void wxExFrame::StatusText(const wxString& text, const wxString& pane)
{
if (m_StatusBar == NULL || m_Panes.empty())
{
// You did not ask for a status bar, so ignore all.
return;
}
const int field = GetPaneField(pane);
if (field >= 0)
{
// wxStatusBar checks whether new text differs from current,
// and does nothing if the same to avoid flicker.
m_StatusBar->SetStatusText(text, field);
}
}
void wxExFrame::StatusText(const wxExFileName& filename, long flags)
{
wxString text; // clear status bar for empty or not existing or not initialized file names
if (filename.IsOk())
{
const wxString path = (flags & STAT_FULLPATH
? filename.GetFullPath(): filename.GetFullName());
text += path;
if (filename.GetStat().IsOk())
{
const wxString what = (flags & STAT_SYNC
? _("Synchronized"): _("Modified"));
const wxString time = (flags & STAT_SYNC
? wxDateTime::Now().Format(): filename.GetStat().GetModificationTime());
text += " " + what + " " + time;
}
}
StatusText(text);
}
#endif // wxUSE_STATUSBAR
wxExManagedFrame::wxExManagedFrame(wxWindow* parent,
wxWindowID id,
const wxString& title,
long style,
const wxString& name)
: wxExFrame(parent, id, title, style, name)
{
m_Manager.SetManagedWindow(this);
#if wxUSE_HTML & wxUSE_PRINTING_ARCHITECTURE
wxExApp::GetPrinter()->SetParentWindow(this);
#endif
}
wxExManagedFrame::~wxExManagedFrame()
{
m_Manager.UnInit();
}
void wxExManagedFrame::TogglePane(const wxString& pane)
{
wxAuiPaneInfo& info = m_Manager.GetPane(pane);
wxASSERT(info.IsOk());
info.IsShown() ? info.Hide(): info.Show();
m_Manager.Update();
}
int wxExPane::m_Total = 0;
#if wxUSE_STATUSBAR
BEGIN_EVENT_TABLE(wxExStatusBar, wxStatusBar)
EVT_LEFT_DOWN(wxExStatusBar::OnMouse)
EVT_LEFT_DCLICK(wxExStatusBar::OnMouse)
EVT_MOTION(wxExStatusBar::OnMouse)
END_EVENT_TABLE()
wxExStatusBar::wxExStatusBar(
wxExFrame* parent,
wxWindowID id,
long style,
const wxString& name)
: wxStatusBar(parent, id, style, name)
, m_Frame(parent)
{
}
void wxExStatusBar::OnMouse(wxMouseEvent& event)
{
bool found = false;
for (int i = 0; i < GetFieldsCount() && !found; i++)
{
wxRect rect;
if (GetFieldRect(i, rect))
{
if (rect.Contains(event.GetPosition()))
{
if (event.ButtonDClick())
{
m_Frame->StatusBarDoubleClicked(i, event.GetPosition());
}
else if (event.ButtonDown())
{
m_Frame->StatusBarClicked(i, event.GetPosition());
}
// Show tooltip if tooltip is available, and not yet tooltip presented.
else if (event.Moving())
{
if (!m_Frame->m_Panes.empty())
{
const wxString tooltip =
(GetToolTip() != NULL ? GetToolTip()->GetTip(): wxString(wxEmptyString));
if (tooltip != m_Frame->GetPane(i).m_Helptext)
{
SetToolTip(m_Frame->GetPane(i).m_Helptext);
}
}
}
else
{
wxFAIL;
}
found = true;
}
}
}
event.Skip();
}
#endif //wxUSE_STATUSBAR
#if wxUSE_TOOLBAR
wxExToolBar::wxExToolBar(wxWindow* parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style,
const wxSize& bitmap_size,
const wxString& name)
: wxToolBar(parent, id, pos, size, style, name)
{
SetToolBitmapSize(bitmap_size);
}
wxToolBarToolBase* wxExToolBar::AddCheckTool(int toolId)
{
const wxExStockArt art(toolId);
return wxToolBar::AddCheckTool(
toolId,
wxEmptyString,
art.GetBitmap(GetToolBitmapSize()),
wxNullBitmap,
art.GetLabel(wxSTOCK_NOFLAGS));
}
wxToolBarToolBase* wxExToolBar::AddTool(int toolId)
{
const wxExStockArt art(toolId);
return wxToolBar::AddTool(
toolId,
wxEmptyString,
art.GetBitmap(GetToolBitmapSize()),
art.GetLabel(wxSTOCK_NOFLAGS));
}
#endif // wxUSE_TOOLBAR
#endif // wxUSE_GUI
<commit_msg>fixed the todo's for grid and implemented GetSearchText<commit_after>/******************************************************************************\
* File: frame.cpp
* Purpose: Implementation of wxExFrame class and support classes
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/tooltip.h> // for GetTip
#include <wx/extension/frame.h>
#include <wx/extension/app.h>
#include <wx/extension/art.h>
#include <wx/extension/fdrepdlg.h> // for wxExFindReplaceDialog
#include <wx/extension/frd.h>
#include <wx/extension/grid.h>
#include <wx/extension/listview.h>
#include <wx/extension/stc.h>
#include <wx/extension/tool.h>
using namespace std;
#if wxUSE_GUI
#if wxUSE_STATUSBAR
wxExStatusBar* wxExFrame::m_StatusBar = NULL;
map<wxString, wxExPane> wxExFrame::m_Panes;
#endif
BEGIN_EVENT_TABLE(wxExFrame, wxFrame)
EVT_CLOSE(wxExFrame::OnClose)
EVT_FIND(wxID_ANY, wxExFrame::OnFindDialog)
EVT_FIND_CLOSE(wxID_ANY, wxExFrame::OnFindDialog)
EVT_FIND_NEXT(wxID_ANY, wxExFrame::OnFindDialog)
EVT_FIND_REPLACE(wxID_ANY, wxExFrame::OnFindDialog)
EVT_FIND_REPLACE_ALL(wxID_ANY, wxExFrame::OnFindDialog)
EVT_MENU(wxID_FIND, wxExFrame::OnCommand)
EVT_MENU(wxID_REPLACE, wxExFrame::OnCommand)
#if wxUSE_STATUSBAR
EVT_UPDATE_UI(ID_EDIT_STATUS_BAR, wxExFrame::OnUpdateUI)
#endif
END_EVENT_TABLE()
wxExFrame::wxExFrame(wxWindow* parent,
wxWindowID id,
const wxString& title,
long style,
const wxString& name)
: wxFrame(parent, id, title, wxDefaultPosition, wxDefaultSize, style, name)
, m_FindReplaceDialog(NULL)
, m_KeepPosAndSize(true)
{
if (wxExApp::GetConfig("Frame/Maximized", 0l))
{
Maximize(true);
}
SetSize(
wxExApp::GetConfig("Frame/X", 100),
wxExApp::GetConfig("Frame/Y", 100),
wxExApp::GetConfig("Frame/Width", 450),
wxExApp::GetConfig("Frame/Height", 350));
}
wxExFrame::wxExFrame(wxWindow* parent,
wxWindowID id,
const wxString& title,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString& name)
: wxFrame(parent, id, title, pos, size, style, name)
, m_FindReplaceDialog(NULL)
, m_KeepPosAndSize(false)
{
}
wxExFrame::~wxExFrame()
{
#if wxUSE_STATUSBAR
delete m_StatusBar;
#endif
}
wxExListView* wxExFrame::GetFocusedListView()
{
wxWindow* win = wxWindow::FindFocus();
if (win == NULL)
{
return NULL;
}
return wxDynamicCast(win, wxExListView);
}
wxExSTC* wxExFrame::GetFocusedSTC()
{
wxWindow* win = wxWindow::FindFocus();
if (win == NULL)
{
return NULL;
}
return wxDynamicCast(win, wxExSTC);
}
#if wxUSE_STATUSBAR
const wxExPane wxExFrame::GetPane(int pane) const
{
for (
map<wxString, wxExPane>::const_iterator it = m_Panes.begin();
it != m_Panes.end();
++it)
{
if (it->second.m_No == pane)
{
return it->second;
}
}
return wxExPane();
}
void wxExFrame::GetSearchText()
{
wxExSTC* stc = GetSTC();
if (stc != NULL)
{
stc->GetSearchText();
}
}
// This is a static method, so no const possible.
int wxExFrame::GetPaneField(const wxString& pane)
{
map<wxString, wxExPane>::const_iterator it = m_Panes.find(pane);
if (it != m_Panes.end())
{
return it->second.m_No;
}
return -1;
}
#endif // wxUSE_STATUSBAR
void wxExFrame::OnClose(wxCloseEvent& event)
{
if (m_KeepPosAndSize)
{
// Set config values that might have changed.
if (IsMaximized())
{
wxExApp::SetConfig("Frame/Maximized", 1);
}
else
{
wxExApp::SetConfig("Frame/Maximized", 0);
const wxRect rect = GetRect();
wxExApp::SetConfig("Frame/X", rect.GetX());
wxExApp::SetConfig("Frame/Y", rect.GetY());
wxExApp::SetConfig("Frame/Width", rect.GetWidth());
wxExApp::SetConfig("Frame/Height", rect.GetHeight());
}
}
event.Skip();
}
void wxExFrame::OnCommand(wxCommandEvent& command)
{
switch (command.GetId())
{
case wxID_FIND:
if (m_FindReplaceDialog != NULL)
{
m_FindReplaceDialog->Destroy();
}
GetSearchText();
m_FindReplaceDialog = new wxExFindReplaceDialog(this, _("Find"));
m_FindReplaceDialog->Show();
break;
case wxID_REPLACE:
if (m_FindReplaceDialog != NULL)
{
m_FindReplaceDialog->Destroy();
}
GetSearchText();
m_FindReplaceDialog = new wxExFindReplaceDialog(
this,
_("Replace"),
wxFR_REPLACEDIALOG);
m_FindReplaceDialog->Show();
break;
default: wxFAIL; break;
}
}
#if wxUSE_STATUSBAR
wxStatusBar* wxExFrame::OnCreateStatusBar(
int number,
long style,
wxWindowID id,
const wxString& name)
{
m_StatusBar = new wxExStatusBar(this, id, style, name);
m_StatusBar->SetFieldsCount(number);
return m_StatusBar;
}
#endif
#if wxUSE_TOOLBAR
wxToolBar* wxExFrame::OnCreateToolBar(
long style,
wxWindowID id,
const wxString& name)
{
m_ToolBar = new wxExToolBar(this,
id,
wxDefaultPosition,
wxDefaultSize,
style,
wxSize(16, 15),
name);
return m_ToolBar;
}
#endif
void wxExFrame::OnFindDialog(wxFindDialogEvent& event)
{
if (event.GetEventType() == wxEVT_COMMAND_FIND_CLOSE)
{
wxASSERT(m_FindReplaceDialog != NULL);
m_FindReplaceDialog->Destroy();
m_FindReplaceDialog = NULL;
return;
}
wxExFindReplaceData* frd = wxExApp::GetConfig()->GetFindReplaceData();
const bool find_next = (frd->GetFlags() & wxFR_DOWN);
wxExSTC* stc = GetSTC();
if (stc != NULL)
{
stc->GetSearchText();
if (event.GetEventType() == wxEVT_COMMAND_FIND)
{
stc->FindNext(frd->GetFindString(), find_next);
}
else if (event.GetEventType() == wxEVT_COMMAND_FIND_NEXT)
{
stc->FindNext(frd->GetFindString(), find_next);
}
else if (event.GetEventType() == wxEVT_COMMAND_FIND_REPLACE)
{
stc->Replace(
frd->GetFindString(),
frd->GetReplaceString(),
frd->IsRegularExpression(),
find_next);
}
else if (event.GetEventType() == wxEVT_COMMAND_FIND_REPLACE_ALL)
{
stc->ReplaceAll(
frd->GetFindString(),
frd->GetReplaceString(),
frd->IsRegularExpression());
}
else
{
wxFAIL;
}
}
wxExListView* lv = GetListView();
if (lv != NULL)
{
if (event.GetEventType() == wxEVT_COMMAND_FIND)
{
lv ->FindNext(frd->GetFindString(), find_next);
}
else if (event.GetEventType() == wxEVT_COMMAND_FIND_NEXT)
{
lv->FindNext(frd->GetFindString(), find_next);
}
else
{
wxFAIL;
}
}
wxWindow* win = wxWindow::FindFocus();
if (win != NULL)
{
wxExGrid* grid = wxDynamicCast(win, wxExGrid);
if (grid != NULL)
{
grid->FindNext(frd->GetFindString(), find_next);
}
}
}
void wxExFrame::OnUpdateUI(wxUpdateUIEvent& event)
{
wxExSTC* stc = GetFocusedSTC();
if (stc == NULL) return;
switch (event.GetId())
{
#if wxUSE_STATUSBAR
case ID_EDIT_STATUS_BAR: stc->UpdateStatusBar("PaneLines"); break;
#endif
default:
wxFAIL;
break;
}
}
bool wxExFrame::OpenFile(
const wxExFileName& filename,
int line_number,
const wxString& match,
long flags)
{
wxExSTC* stc = GetFocusedSTC();
if (stc != NULL)
{
// Remove link flags;
const long new_flags = 0;
return stc->Open(filename, line_number, match, new_flags);
}
return false;
}
#if wxUSE_STATUSBAR
void wxExFrame::SetupStatusBar(
const vector<wxExPane>& panes,
long style,
wxWindowID id,
const wxString& name)
{
wxFrame::CreateStatusBar(panes.size(), style, id, name);
int* styles = new int[panes.size()];
int* widths = new int[panes.size()];
for (
vector<wxExPane>::const_iterator it = panes.begin();
it != panes.end();
++it)
{
m_Panes[it->m_Name] = *it;
styles[it->m_No] = it->GetStyle();
widths[it->m_No] = it->GetWidth();
}
m_StatusBar->SetStatusStyles(panes.size(), styles);
m_StatusBar->SetStatusWidths(panes.size(), widths);
delete[] styles;
delete[] widths;
}
#endif // wxUSE_STATUSBAR
#if wxUSE_STATUSBAR
void wxExFrame::StatusBarDoubleClicked(int field, const wxPoint& point)
{
if (field == GetPaneField("PaneLines"))
{
wxExSTC* stc = GetSTC();
if (stc != NULL) stc->GotoDialog();
}
else if (field == GetPaneField("PaneLexer"))
{
wxExSTC* stc = GetSTC();
if (stc != NULL) stc->LexerDialog();
}
else if (field == GetPaneField("PaneFileType"))
{
wxExSTC* stc = GetSTC();
if (stc != NULL) stc->FileTypeMenu();
}
else if (field == GetPaneField("PaneItems"))
{
wxExListView* list = GetListView();
if (list != NULL) list->GotoDialog();
}
else
{
// Clicking on another field, do nothing.
}
}
// This is a static method, so you cannot call wxFrame::SetStatusText.
void wxExFrame::StatusText(const wxString& text, const wxString& pane)
{
if (m_StatusBar == NULL || m_Panes.empty())
{
// You did not ask for a status bar, so ignore all.
return;
}
const int field = GetPaneField(pane);
if (field >= 0)
{
// wxStatusBar checks whether new text differs from current,
// and does nothing if the same to avoid flicker.
m_StatusBar->SetStatusText(text, field);
}
}
void wxExFrame::StatusText(const wxExFileName& filename, long flags)
{
wxString text; // clear status bar for empty or not existing or not initialized file names
if (filename.IsOk())
{
const wxString path = (flags & STAT_FULLPATH
? filename.GetFullPath(): filename.GetFullName());
text += path;
if (filename.GetStat().IsOk())
{
const wxString what = (flags & STAT_SYNC
? _("Synchronized"): _("Modified"));
const wxString time = (flags & STAT_SYNC
? wxDateTime::Now().Format(): filename.GetStat().GetModificationTime());
text += " " + what + " " + time;
}
}
StatusText(text);
}
#endif // wxUSE_STATUSBAR
wxExManagedFrame::wxExManagedFrame(wxWindow* parent,
wxWindowID id,
const wxString& title,
long style,
const wxString& name)
: wxExFrame(parent, id, title, style, name)
{
m_Manager.SetManagedWindow(this);
#if wxUSE_HTML & wxUSE_PRINTING_ARCHITECTURE
wxExApp::GetPrinter()->SetParentWindow(this);
#endif
}
wxExManagedFrame::~wxExManagedFrame()
{
m_Manager.UnInit();
}
void wxExManagedFrame::TogglePane(const wxString& pane)
{
wxAuiPaneInfo& info = m_Manager.GetPane(pane);
wxASSERT(info.IsOk());
info.IsShown() ? info.Hide(): info.Show();
m_Manager.Update();
}
int wxExPane::m_Total = 0;
#if wxUSE_STATUSBAR
BEGIN_EVENT_TABLE(wxExStatusBar, wxStatusBar)
EVT_LEFT_DOWN(wxExStatusBar::OnMouse)
EVT_LEFT_DCLICK(wxExStatusBar::OnMouse)
EVT_MOTION(wxExStatusBar::OnMouse)
END_EVENT_TABLE()
wxExStatusBar::wxExStatusBar(
wxExFrame* parent,
wxWindowID id,
long style,
const wxString& name)
: wxStatusBar(parent, id, style, name)
, m_Frame(parent)
{
}
void wxExStatusBar::OnMouse(wxMouseEvent& event)
{
bool found = false;
for (int i = 0; i < GetFieldsCount() && !found; i++)
{
wxRect rect;
if (GetFieldRect(i, rect))
{
if (rect.Contains(event.GetPosition()))
{
if (event.ButtonDClick())
{
m_Frame->StatusBarDoubleClicked(i, event.GetPosition());
}
else if (event.ButtonDown())
{
m_Frame->StatusBarClicked(i, event.GetPosition());
}
// Show tooltip if tooltip is available, and not yet tooltip presented.
else if (event.Moving())
{
if (!m_Frame->m_Panes.empty())
{
const wxString tooltip =
(GetToolTip() != NULL ? GetToolTip()->GetTip(): wxString(wxEmptyString));
if (tooltip != m_Frame->GetPane(i).m_Helptext)
{
SetToolTip(m_Frame->GetPane(i).m_Helptext);
}
}
}
else
{
wxFAIL;
}
found = true;
}
}
}
event.Skip();
}
#endif //wxUSE_STATUSBAR
#if wxUSE_TOOLBAR
wxExToolBar::wxExToolBar(wxWindow* parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style,
const wxSize& bitmap_size,
const wxString& name)
: wxToolBar(parent, id, pos, size, style, name)
{
SetToolBitmapSize(bitmap_size);
}
wxToolBarToolBase* wxExToolBar::AddCheckTool(int toolId)
{
const wxExStockArt art(toolId);
return wxToolBar::AddCheckTool(
toolId,
wxEmptyString,
art.GetBitmap(GetToolBitmapSize()),
wxNullBitmap,
art.GetLabel(wxSTOCK_NOFLAGS));
}
wxToolBarToolBase* wxExToolBar::AddTool(int toolId)
{
const wxExStockArt art(toolId);
return wxToolBar::AddTool(
toolId,
wxEmptyString,
art.GetBitmap(GetToolBitmapSize()),
art.GetLabel(wxSTOCK_NOFLAGS));
}
#endif // wxUSE_TOOLBAR
#endif // wxUSE_GUI
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLSectionFootnoteConfigImport.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2006-06-19 18:44: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 _XMLOFF_XMLSECTIONFOOTNOTECONFIGIMPORT_HXX
#include "XMLSectionFootnoteConfigImport.hxx"
#endif
#ifndef _RTL_USTRING
#include <rtl/ustring.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif
#ifndef _COM_SUN_STAR_STYLE_NUMBERINGTYPE_HPP_
#include <com/sun/star/style/NumberingType.hpp>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
#include "xmlprmap.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_PROPMAPPINGTYPES_HXX
#include "maptype.hxx"
#endif
#ifndef _XMLOFF_XMLNUMI_HXX
#include "xmlnumi.hxx"
#endif
#ifndef _XMLOFF_TEXTPRMAP_HXX_
#include "txtprmap.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#include <vector>
using namespace ::xmloff::token;
using namespace ::com::sun::star::style;
using ::rtl::OUString;
using ::std::vector;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::xml::sax::XAttributeList;
TYPEINIT1(XMLSectionFootnoteConfigImport, SvXMLImportContext);
XMLSectionFootnoteConfigImport::XMLSectionFootnoteConfigImport(
SvXMLImport& rImport,
sal_uInt16 nPrefix,
const OUString& rLocalName,
vector<XMLPropertyState> & rProps,
const UniReference<XMLPropertySetMapper> & rMapperRef) :
SvXMLImportContext(rImport, nPrefix, rLocalName),
rProperties(rProps),
rMapper(rMapperRef)
{
}
XMLSectionFootnoteConfigImport::~XMLSectionFootnoteConfigImport()
{
}
void XMLSectionFootnoteConfigImport::StartElement(
const Reference<XAttributeList> & xAttrList)
{
sal_Bool bEnd = sal_True; // we're inside the element, so this is true
sal_Bool bNumOwn = sal_False;
sal_Bool bNumRestart = sal_False;
sal_Bool bEndnote = sal_False;
sal_Int16 nNumRestartAt = 0;
OUString sNumPrefix;
OUString sNumSuffix;
OUString sNumFormat;
OUString sNumLetterSync;
// iterate over xattribute list and fill values
sal_Int16 nLength = xAttrList->getLength();
for(sal_Int16 nAttr = 0; nAttr < nLength; nAttr++)
{
OUString sLocalName;
sal_uInt16 nPrefix = GetImport().GetNamespaceMap().
GetKeyByAttrName( xAttrList->getNameByIndex(nAttr),
&sLocalName );
OUString sAttrValue = xAttrList->getValueByIndex(nAttr);
if (XML_NAMESPACE_TEXT == nPrefix)
{
if (IsXMLToken(sLocalName, XML_START_VALUE))
{
sal_Int32 nTmp;
if (SvXMLUnitConverter::convertNumber(nTmp, sAttrValue))
{
nNumRestartAt = static_cast< sal_Int16 >( nTmp ) - 1;
bNumRestart = sal_True;
}
}
else if( IsXMLToken( sLocalName, XML_NOTE_CLASS ) )
{
if( IsXMLToken( sAttrValue, XML_ENDNOTE ) )
bEndnote = sal_True;
}
}
else if (XML_NAMESPACE_STYLE == nPrefix)
{
if (IsXMLToken(sLocalName, XML_NUM_PREFIX))
{
sNumPrefix = sAttrValue;
bNumOwn = sal_True;
}
else if (IsXMLToken(sLocalName, XML_NUM_SUFFIX))
{
sNumSuffix = sAttrValue;
bNumOwn = sal_True;
}
else if (IsXMLToken(sLocalName, XML_NUM_FORMAT))
{
sNumFormat = sAttrValue;
bNumOwn = sal_True;
}
else if (IsXMLToken(sLocalName, XML_NUM_LETTER_SYNC))
{
sNumLetterSync = sAttrValue;
bNumOwn = sal_True;
}
}
}
// OK, now we have all values and can fill the XMLPropertyState vector
Any aAny;
aAny.setValue( &bNumOwn, ::getBooleanCppuType() );
sal_Int32 nIndex = rMapper->FindEntryIndex( bEndnote ?
CTF_SECTION_ENDNOTE_NUM_OWN : CTF_SECTION_FOOTNOTE_NUM_OWN );
XMLPropertyState aNumOwn( nIndex, aAny );
rProperties.push_back( aNumOwn );
aAny.setValue( &bNumRestart, ::getBooleanCppuType() );
nIndex = rMapper->FindEntryIndex( bEndnote ?
CTF_SECTION_ENDNOTE_NUM_RESTART : CTF_SECTION_FOOTNOTE_NUM_RESTART );
XMLPropertyState aNumRestart( nIndex, aAny );
rProperties.push_back( aNumRestart );
aAny <<= nNumRestartAt;
nIndex = rMapper->FindEntryIndex( bEndnote ?
CTF_SECTION_ENDNOTE_NUM_RESTART_AT :
CTF_SECTION_FOOTNOTE_NUM_RESTART_AT );
XMLPropertyState aNumRestartAtState( nIndex, aAny );
rProperties.push_back( aNumRestartAtState );
sal_Int16 nNumType = NumberingType::ARABIC;
GetImport().GetMM100UnitConverter().convertNumFormat( nNumType,
sNumFormat,
sNumLetterSync );
aAny <<= nNumType;
nIndex = rMapper->FindEntryIndex( bEndnote ?
CTF_SECTION_ENDNOTE_NUM_TYPE : CTF_SECTION_FOOTNOTE_NUM_TYPE );
XMLPropertyState aNumFormatState( nIndex, aAny );
rProperties.push_back( aNumFormatState );
aAny <<= sNumPrefix;
nIndex = rMapper->FindEntryIndex( bEndnote ?
CTF_SECTION_ENDNOTE_NUM_PREFIX : CTF_SECTION_FOOTNOTE_NUM_PREFIX );
XMLPropertyState aPrefixState( nIndex, aAny );
rProperties.push_back( aPrefixState );
aAny <<= sNumSuffix;
nIndex = rMapper->FindEntryIndex( bEndnote ?
CTF_SECTION_ENDNOTE_NUM_SUFFIX : CTF_SECTION_FOOTNOTE_NUM_SUFFIX );
XMLPropertyState aSuffixState( nIndex, aAny );
rProperties.push_back( aSuffixState );
aAny.setValue( &bEnd, ::getBooleanCppuType() );
nIndex = rMapper->FindEntryIndex( bEndnote ?
CTF_SECTION_ENDNOTE_END : CTF_SECTION_FOOTNOTE_END );
XMLPropertyState aEndState( nIndex, aAny );
rProperties.push_back( aEndState );
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.7.34); FILE MERGED 2006/09/01 18:00:05 kaib 1.7.34.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLSectionFootnoteConfigImport.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-17 11:11:08 $
*
* 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_xmloff.hxx"
#ifndef _XMLOFF_XMLSECTIONFOOTNOTECONFIGIMPORT_HXX
#include "XMLSectionFootnoteConfigImport.hxx"
#endif
#ifndef _RTL_USTRING
#include <rtl/ustring.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif
#ifndef _COM_SUN_STAR_STYLE_NUMBERINGTYPE_HPP_
#include <com/sun/star/style/NumberingType.hpp>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
#include "xmlprmap.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_PROPMAPPINGTYPES_HXX
#include "maptype.hxx"
#endif
#ifndef _XMLOFF_XMLNUMI_HXX
#include "xmlnumi.hxx"
#endif
#ifndef _XMLOFF_TEXTPRMAP_HXX_
#include "txtprmap.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#include <vector>
using namespace ::xmloff::token;
using namespace ::com::sun::star::style;
using ::rtl::OUString;
using ::std::vector;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::xml::sax::XAttributeList;
TYPEINIT1(XMLSectionFootnoteConfigImport, SvXMLImportContext);
XMLSectionFootnoteConfigImport::XMLSectionFootnoteConfigImport(
SvXMLImport& rImport,
sal_uInt16 nPrefix,
const OUString& rLocalName,
vector<XMLPropertyState> & rProps,
const UniReference<XMLPropertySetMapper> & rMapperRef) :
SvXMLImportContext(rImport, nPrefix, rLocalName),
rProperties(rProps),
rMapper(rMapperRef)
{
}
XMLSectionFootnoteConfigImport::~XMLSectionFootnoteConfigImport()
{
}
void XMLSectionFootnoteConfigImport::StartElement(
const Reference<XAttributeList> & xAttrList)
{
sal_Bool bEnd = sal_True; // we're inside the element, so this is true
sal_Bool bNumOwn = sal_False;
sal_Bool bNumRestart = sal_False;
sal_Bool bEndnote = sal_False;
sal_Int16 nNumRestartAt = 0;
OUString sNumPrefix;
OUString sNumSuffix;
OUString sNumFormat;
OUString sNumLetterSync;
// iterate over xattribute list and fill values
sal_Int16 nLength = xAttrList->getLength();
for(sal_Int16 nAttr = 0; nAttr < nLength; nAttr++)
{
OUString sLocalName;
sal_uInt16 nPrefix = GetImport().GetNamespaceMap().
GetKeyByAttrName( xAttrList->getNameByIndex(nAttr),
&sLocalName );
OUString sAttrValue = xAttrList->getValueByIndex(nAttr);
if (XML_NAMESPACE_TEXT == nPrefix)
{
if (IsXMLToken(sLocalName, XML_START_VALUE))
{
sal_Int32 nTmp;
if (SvXMLUnitConverter::convertNumber(nTmp, sAttrValue))
{
nNumRestartAt = static_cast< sal_Int16 >( nTmp ) - 1;
bNumRestart = sal_True;
}
}
else if( IsXMLToken( sLocalName, XML_NOTE_CLASS ) )
{
if( IsXMLToken( sAttrValue, XML_ENDNOTE ) )
bEndnote = sal_True;
}
}
else if (XML_NAMESPACE_STYLE == nPrefix)
{
if (IsXMLToken(sLocalName, XML_NUM_PREFIX))
{
sNumPrefix = sAttrValue;
bNumOwn = sal_True;
}
else if (IsXMLToken(sLocalName, XML_NUM_SUFFIX))
{
sNumSuffix = sAttrValue;
bNumOwn = sal_True;
}
else if (IsXMLToken(sLocalName, XML_NUM_FORMAT))
{
sNumFormat = sAttrValue;
bNumOwn = sal_True;
}
else if (IsXMLToken(sLocalName, XML_NUM_LETTER_SYNC))
{
sNumLetterSync = sAttrValue;
bNumOwn = sal_True;
}
}
}
// OK, now we have all values and can fill the XMLPropertyState vector
Any aAny;
aAny.setValue( &bNumOwn, ::getBooleanCppuType() );
sal_Int32 nIndex = rMapper->FindEntryIndex( bEndnote ?
CTF_SECTION_ENDNOTE_NUM_OWN : CTF_SECTION_FOOTNOTE_NUM_OWN );
XMLPropertyState aNumOwn( nIndex, aAny );
rProperties.push_back( aNumOwn );
aAny.setValue( &bNumRestart, ::getBooleanCppuType() );
nIndex = rMapper->FindEntryIndex( bEndnote ?
CTF_SECTION_ENDNOTE_NUM_RESTART : CTF_SECTION_FOOTNOTE_NUM_RESTART );
XMLPropertyState aNumRestart( nIndex, aAny );
rProperties.push_back( aNumRestart );
aAny <<= nNumRestartAt;
nIndex = rMapper->FindEntryIndex( bEndnote ?
CTF_SECTION_ENDNOTE_NUM_RESTART_AT :
CTF_SECTION_FOOTNOTE_NUM_RESTART_AT );
XMLPropertyState aNumRestartAtState( nIndex, aAny );
rProperties.push_back( aNumRestartAtState );
sal_Int16 nNumType = NumberingType::ARABIC;
GetImport().GetMM100UnitConverter().convertNumFormat( nNumType,
sNumFormat,
sNumLetterSync );
aAny <<= nNumType;
nIndex = rMapper->FindEntryIndex( bEndnote ?
CTF_SECTION_ENDNOTE_NUM_TYPE : CTF_SECTION_FOOTNOTE_NUM_TYPE );
XMLPropertyState aNumFormatState( nIndex, aAny );
rProperties.push_back( aNumFormatState );
aAny <<= sNumPrefix;
nIndex = rMapper->FindEntryIndex( bEndnote ?
CTF_SECTION_ENDNOTE_NUM_PREFIX : CTF_SECTION_FOOTNOTE_NUM_PREFIX );
XMLPropertyState aPrefixState( nIndex, aAny );
rProperties.push_back( aPrefixState );
aAny <<= sNumSuffix;
nIndex = rMapper->FindEntryIndex( bEndnote ?
CTF_SECTION_ENDNOTE_NUM_SUFFIX : CTF_SECTION_FOOTNOTE_NUM_SUFFIX );
XMLPropertyState aSuffixState( nIndex, aAny );
rProperties.push_back( aSuffixState );
aAny.setValue( &bEnd, ::getBooleanCppuType() );
nIndex = rMapper->FindEntryIndex( bEndnote ?
CTF_SECTION_ENDNOTE_END : CTF_SECTION_FOOTNOTE_END );
XMLPropertyState aEndState( nIndex, aAny );
rProperties.push_back( aEndState );
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: XMLSectionFootnoteConfigImport.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2004-11-09 12:19:06 $
*
* 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 _XMLOFF_XMLSECTIONFOOTNOTECONFIGIMPORT_HXX
#define _XMLOFF_XMLSECTIONFOOTNOTECONFIGIMPORT_HXX
#ifndef _XMLOFF_XMLICTXT_HXX
#include "xmlictxt.hxx"
#endif
#ifndef _UNIVERSALL_REFERENCE_HXX
#include "uniref.hxx"
#endif
#include <vector>
class SvXMLImport;
struct XMLPropertyState;
class XMLPropertySetMapper;
namespace rtl { class OUString; }
namespace com { namespace sun { namespace star {
namespace uno { template<class X> class Reference; }
namespace xml { namespace sax { class XAttributeList; } }
} } }
/**
* Import the footnote-/endnote-configuration element in section styles.
*/
class XMLSectionFootnoteConfigImport : public SvXMLImportContext
{
::std::vector<XMLPropertyState> & rProperties;
UniReference<XMLPropertySetMapper> rMapper;
public:
TYPEINFO();
XMLSectionFootnoteConfigImport(
SvXMLImport& rImport,
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
::std::vector<XMLPropertyState> & rProperties,
const UniReference<XMLPropertySetMapper> & rMapperRef);
~XMLSectionFootnoteConfigImport();
virtual void StartElement(
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList> & xAttrList );
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.220); FILE MERGED 2005/09/05 14:39:59 rt 1.3.220.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLSectionFootnoteConfigImport.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 15:17:18 $
*
* 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 _XMLOFF_XMLSECTIONFOOTNOTECONFIGIMPORT_HXX
#define _XMLOFF_XMLSECTIONFOOTNOTECONFIGIMPORT_HXX
#ifndef _XMLOFF_XMLICTXT_HXX
#include "xmlictxt.hxx"
#endif
#ifndef _UNIVERSALL_REFERENCE_HXX
#include "uniref.hxx"
#endif
#include <vector>
class SvXMLImport;
struct XMLPropertyState;
class XMLPropertySetMapper;
namespace rtl { class OUString; }
namespace com { namespace sun { namespace star {
namespace uno { template<class X> class Reference; }
namespace xml { namespace sax { class XAttributeList; } }
} } }
/**
* Import the footnote-/endnote-configuration element in section styles.
*/
class XMLSectionFootnoteConfigImport : public SvXMLImportContext
{
::std::vector<XMLPropertyState> & rProperties;
UniReference<XMLPropertySetMapper> rMapper;
public:
TYPEINFO();
XMLSectionFootnoteConfigImport(
SvXMLImport& rImport,
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
::std::vector<XMLPropertyState> & rProperties,
const UniReference<XMLPropertySetMapper> & rMapperRef);
~XMLSectionFootnoteConfigImport();
virtual void StartElement(
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList> & xAttrList );
};
#endif
<|endoftext|> |
<commit_before>#include <Arduino.h>
#include "system.h"
void lwmqtt_arduino_timer_set(lwmqtt_client_t *client, void *ref, int timeout) {
// cast timer reference
lwmqtt_arduino_timer_t *t = (lwmqtt_arduino_timer_t *)ref;
// set future end time
t->end = millis() + timeout;
}
int lwmqtt_arduino_timer_get(lwmqtt_client_t *client, void *ref) {
// cast timer reference
lwmqtt_arduino_timer_t *t = (lwmqtt_arduino_timer_t *)ref;
// get difference to end time
return (int)(t->end - millis());
}
lwmqtt_err_t lwmqtt_arduino_network_read(lwmqtt_client_t *client, void *ref, uint8_t *buffer, size_t len, size_t *read,
int timeout) {
// cast network reference
lwmqtt_arduino_network_t *n = (lwmqtt_arduino_network_t *)ref;
// set timeout
n->client->setTimeout((unsigned long)timeout);
// read bytes
*read = n->client->readBytes(buffer, len);
if (*read <= 0) {
return LWMQTT_NETWORK_FAILED_READ;
}
return LWMQTT_SUCCESS;
}
lwmqtt_err_t lwmqtt_arduino_network_write(lwmqtt_client_t *client, void *ref, uint8_t *buffer, size_t len, size_t *sent,
int timeout) {
// cast network reference
lwmqtt_arduino_network_t *n = (lwmqtt_arduino_network_t *)ref;
// write bytes
*sent = n->client->write(buffer, len);
if (*sent <= 0) {
return LWMQTT_NETWORK_FAILED_WRITE;
};
return LWMQTT_SUCCESS;
}
<commit_msg>simplified<commit_after>#include <Arduino.h>
#include "system.h"
void lwmqtt_arduino_timer_set(lwmqtt_client_t *client, void *ref, int timeout) {
// cast timer reference
auto *t = (lwmqtt_arduino_timer_t *)ref;
// set future end time
t->end = millis() + timeout;
}
int lwmqtt_arduino_timer_get(lwmqtt_client_t *client, void *ref) {
// cast timer reference
auto *t = (lwmqtt_arduino_timer_t *)ref;
// get difference to end time
return (int)(t->end - millis());
}
lwmqtt_err_t lwmqtt_arduino_network_read(lwmqtt_client_t *client, void *ref, uint8_t *buffer, size_t len, size_t *read,
int timeout) {
// cast network reference
auto *n = (lwmqtt_arduino_network_t *)ref;
// set timeout
n->client->setTimeout((unsigned long)timeout);
// read bytes
*read = n->client->readBytes(buffer, len);
if (*read <= 0) {
return LWMQTT_NETWORK_FAILED_READ;
}
return LWMQTT_SUCCESS;
}
lwmqtt_err_t lwmqtt_arduino_network_write(lwmqtt_client_t *client, void *ref, uint8_t *buffer, size_t len, size_t *sent,
int timeout) {
// cast network reference
auto *n = (lwmqtt_arduino_network_t *)ref;
// write bytes
*sent = n->client->write(buffer, len);
if (*sent <= 0) {
return LWMQTT_NETWORK_FAILED_WRITE;
};
return LWMQTT_SUCCESS;
}
<|endoftext|> |
<commit_before>/**
* @copyright Copyright 2016 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 JPetWriter.cpp
*/
#include "JPetWriter.h"
#include "../JPetUserInfoStructure/JPetUserInfoStructure.h"
JPetWriter::JPetWriter(const char* p_fileName) :
fFileName(p_fileName), // string z nazwą pliku
fFile(0), // plik
fIsBranchCreated(false),
fTree(0)
{
fFile = new TFile(fFileName.c_str(), "RECREATE");
if (!isOpen()) {
ERROR("Could not open file to write.");
} else {
fTree = new TTree("tree", "tree");
fTree->SetAutoSave(10000);
}
}
JPetWriter::~JPetWriter()
{
DEBUG("destructor of JPetWriter");
if (isOpen()) {
fTree->AutoSave("SaveSelf");
if (fFile) {
delete fFile;
fFile = 0;
}
fTree = 0;
}
DEBUG("exiting destructor of JPetWriter");
}
void JPetWriter::closeFile()
{
if (isOpen() ) {
fTree->AutoSave("SaveSelf");
delete fFile;
fFile = 0;
}
fFileName.clear();
fIsBranchCreated = false;
}
void JPetWriter::writeHeader(TObject* header)
{
// @todo as the second argument should be passed some enum to indicate position of header
fTree->GetUserInfo()->AddAt(header, JPetUserInfoStructure::kHeader);
}
void JPetWriter::writeCollection(const TCollection * col, const char* dirname, const char* subdirname){
TDirectory * current = fFile->GetDirectory(dirname);
if(!current){
current = fFile->mkdir(dirname);
}
assert(current);
// use a subdirectory if requested by user
if(!std::string(subdirname).empty()){
if(current->GetDirectory(subdirname)){
current = current->GetDirectory(subdirname);
}else{
current = current->mkdir(subdirname);
}
}
assert(current);
current->cd();
TIterator * it = col->MakeIterator();
TObject * obj;
while((obj = it->Next())){
obj->Write();
}
fFile->cd();
}
<commit_msg>Add method documentation; clean up newlines<commit_after>/**
* @copyright Copyright 2016 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 JPetWriter.cpp
*/
#include "JPetWriter.h"
#include "../JPetUserInfoStructure/JPetUserInfoStructure.h"
JPetWriter::JPetWriter(const char* p_fileName) :
fFileName(p_fileName), // string z nazwą pliku
fFile(0), // plik
fIsBranchCreated(false),
fTree(0)
{
fFile = new TFile(fFileName.c_str(), "RECREATE");
if (!isOpen()) {
ERROR("Could not open file to write.");
} else {
fTree = new TTree("tree", "tree");
fTree->SetAutoSave(10000);
}
}
JPetWriter::~JPetWriter()
{
DEBUG("destructor of JPetWriter");
if (isOpen()) {
fTree->AutoSave("SaveSelf");
if (fFile) {
delete fFile;
fFile = 0;
}
fTree = 0;
}
DEBUG("exiting destructor of JPetWriter");
}
void JPetWriter::closeFile()
{
if (isOpen() ) {
fTree->AutoSave("SaveSelf");
delete fFile;
fFile = 0;
}
fFileName.clear();
fIsBranchCreated = false;
}
void JPetWriter::writeHeader(TObject* header)
{
// @todo as the second argument should be passed some enum to indicate position of header
fTree->GetUserInfo()->AddAt(header, JPetUserInfoStructure::kHeader);
}
/**
* @brief Write all TObjects from a given TCollection into a certain directory structure in the file
*
* @param col pointer to a TCollection-based container
* @param dirname name of a directory inside the output file to which the objects should be written
* @param subdirname optional name of a subdirectory inside dirname to which the objects should be written
*
* This method whites all TObject-based objects contained in the TCollection-based container (see ROOT documentation)
* into a directory whose name is given by dirname inside the output file. If dirname does not exist
* in the output file, it will be created. Otherwise, contents of the col collection will be appended to an existing
* directory.
*
* If the optional subdirectory name is specified (subdirname parameter, defaults to empty string) then the
* contents of the collection will be written to "dirname/subdirname". If the "subdirname" directory does not
* exist inside the "dirname" directory, it will be created.
*
*/
void JPetWriter::writeCollection(const TCollection * col, const char* dirname, const char* subdirname){
TDirectory * current = fFile->GetDirectory(dirname);
if(!current){
current = fFile->mkdir(dirname);
}
assert(current);
// use a subdirectory if requested by user
if(!std::string(subdirname).empty()){
if(current->GetDirectory(subdirname)){
current = current->GetDirectory(subdirname);
}else{
current = current->mkdir(subdirname);
}
}
assert(current);
current->cd();
TIterator * it = col->MakeIterator();
TObject * obj;
while((obj = it->Next())){
obj->Write();
}
fFile->cd();
}
<|endoftext|> |
<commit_before>// Copyright 2019 Google LLC
//
// 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
//
// https://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 "marl/thread.h"
#include "marl/trace.h"
#include <cstdarg>
#include <cstdio>
#if defined(_WIN32)
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
#elif defined(__APPLE__)
# include <pthread.h>
# include <mach/thread_act.h>
# include <unistd.h>
#else
# include <pthread.h>
# include <unistd.h>
#endif
namespace marl {
#if defined(_WIN32)
void Thread::setName(const char* fmt, ...)
{
static auto setThreadDescription = reinterpret_cast<HRESULT(WINAPI*)(HANDLE, PCWSTR)>(GetProcAddress(GetModuleHandle("kernelbase.dll"), "SetThreadDescription"));
if (setThreadDescription == nullptr)
{
return;
}
char name[1024];
va_list vararg;
va_start(vararg, fmt);
vsnprintf(name, sizeof(name), fmt, vararg);
va_end(vararg);
wchar_t wname[1024];
mbstowcs(wname, name, 1024);
setThreadDescription(GetCurrentThread(), wname);
MARL_NAME_THREAD("%s", name);
}
unsigned int Thread::numLogicalCPUs()
{
DWORD_PTR processAffinityMask = 1;
DWORD_PTR systemAffinityMask = 1;
GetProcessAffinityMask(GetCurrentProcess(), &processAffinityMask, &systemAffinityMask);
auto count = 0;
while (processAffinityMask > 0)
{
if (processAffinityMask & 1)
{
count++;
}
processAffinityMask >>= 1;
}
return count;
}
#else
void Thread::setName(const char* fmt, ...)
{
char name[1024];
va_list vararg;
va_start(vararg, fmt);
vsnprintf(name, sizeof(name), fmt, vararg);
va_end(vararg);
#if defined(__APPLE__)
pthread_setname_np(name);
#else
pthread_setname_np(pthread_self(), name);
#endif
MARL_NAME_THREAD("%s", name);
}
unsigned int Thread::numLogicalCPUs()
{
return sysconf(_SC_NPROCESSORS_ONLN);
}
#endif
} // namespace marl
<commit_msg>Fix Fuchsia build.<commit_after>// Copyright 2019 Google LLC
//
// 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
//
// https://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 "marl/thread.h"
#include "marl/trace.h"
#include <cstdarg>
#include <cstdio>
#if defined(_WIN32)
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
#elif defined(__APPLE__)
# include <pthread.h>
# include <mach/thread_act.h>
# include <unistd.h>
#else
# include <pthread.h>
# include <unistd.h>
#endif
namespace marl {
#if defined(_WIN32)
void Thread::setName(const char* fmt, ...)
{
static auto setThreadDescription = reinterpret_cast<HRESULT(WINAPI*)(HANDLE, PCWSTR)>(GetProcAddress(GetModuleHandle("kernelbase.dll"), "SetThreadDescription"));
if (setThreadDescription == nullptr)
{
return;
}
char name[1024];
va_list vararg;
va_start(vararg, fmt);
vsnprintf(name, sizeof(name), fmt, vararg);
va_end(vararg);
wchar_t wname[1024];
mbstowcs(wname, name, 1024);
setThreadDescription(GetCurrentThread(), wname);
MARL_NAME_THREAD("%s", name);
}
unsigned int Thread::numLogicalCPUs()
{
DWORD_PTR processAffinityMask = 1;
DWORD_PTR systemAffinityMask = 1;
GetProcessAffinityMask(GetCurrentProcess(), &processAffinityMask, &systemAffinityMask);
auto count = 0;
while (processAffinityMask > 0)
{
if (processAffinityMask & 1)
{
count++;
}
processAffinityMask >>= 1;
}
return count;
}
#else
void Thread::setName(const char* fmt, ...)
{
char name[1024];
va_list vararg;
va_start(vararg, fmt);
vsnprintf(name, sizeof(name), fmt, vararg);
va_end(vararg);
#if defined(__APPLE__)
pthread_setname_np(name);
#elif !defined(__Fuchsia__)
pthread_setname_np(pthread_self(), name);
#endif
MARL_NAME_THREAD("%s", name);
}
unsigned int Thread::numLogicalCPUs()
{
return sysconf(_SC_NPROCESSORS_ONLN);
}
#endif
} // namespace marl
<|endoftext|> |
<commit_before>#include "coverage.h"
#include "location.h"
#include "geos/geom/Coordinate.h"
#include "coordinate.h"
#include "box.h"
#include "coordinatesystem.h"
#include "georeference.h"
//#include "cornersgeoreference.h"
#include "rootdrawer.h"
#include "spatialdatadrawer.h"
#include "layersrenderer.h"
using namespace Ilwis;
using namespace Geodrawer;
RootDrawer::RootDrawer(const QQuickFramebufferObject *fbo, const IOOptions& options) : ComplexDrawer("RootDrawer",0,0, options), _frameBufferObject(fbo)
{
valid(true);
_screenGrf = new GeoReference();
_screenGrf->create("corners");
}
RootDrawer::~RootDrawer()
{
cleanUp();
}
void RootDrawer::addSpatialDrawer(DrawerInterface *newdrawer, bool overrule)
{
overrule = drawerCount(ComplexDrawer::dtMAIN) == 0 || overrule;
SpatialDataDrawer *datadrawer = dynamic_cast<SpatialDataDrawer *>(newdrawer);
if ( overrule && datadrawer && datadrawer->coverage().isValid()) {
ICoordinateSystem cs = datadrawer->coverage()->coordinateSystem();
Envelope envelope = envelope2RootEnvelope(cs, datadrawer->envelope());
Envelope viewEnv = _zoomRect;
bool setViewEnv = envelope != viewEnv;
viewEnv += envelope;
_coverageRect = datadrawer->envelope();
if ( setViewEnv)
applyEnvelopeView(viewEnv, true);
}
return ComplexDrawer::addDrawer(newdrawer);
}
void RootDrawer::addEnvelope(const ICoordinateSystem &csSource, const Envelope &env, bool overrule)
{
if ( overrule || !_coverageRect.isValid() || _coverageRect.isNull()) {
Envelope newEnvelope = envelope2RootEnvelope(csSource, env);
_coverageRect += newEnvelope;
}
applyEnvelopeView(_coverageRect, overrule);
}
Envelope RootDrawer::viewEnvelope() const
{
return _viewEnvelope;
}
Envelope RootDrawer::zoomEnvelope() const
{
return _zoomRect;
}
Envelope RootDrawer::coverageEnvelope() const
{
return _coverageRect;
}
void RootDrawer::applyEnvelopeView(const Envelope &viewRect, bool overrule)
{
if ( !_coverageRect.isValid() || _coverageRect.isNull()){
ERROR2(ERR_NO_INITIALIZED_2,TR("Coverage area"), TR("Visualization"));
return;
}
if ( !_pixelAreaSize.isValid()) {
ERROR2(ERR_NO_INITIALIZED_2,TR("Pixel area"), TR("Visualization"));
return;
}
if ( overrule)
_viewEnvelope = Envelope();
double w = viewRect.xlength() - 1;
double h = viewRect.ylength() - 1;
_aspectRatioCoverage = w / h;
double deltax = 0, deltay = 0;
Envelope env;
if ( _aspectRatioCoverage <= 1.0) { // coverage is higher than it is wide)
double pixwidth = (double)_pixelAreaSize.ysize() * _aspectRatioCoverage;
if ( pixwidth > _pixelAreaSize.xsize()) {
deltay = (_coverageRect.ylength() - 1) * ( pixwidth / _pixelAreaSize.xsize() - 1.0);
pixwidth = _pixelAreaSize.xsize();
}
double fractioOffWidth = 1.0 - (_pixelAreaSize.xsize() - pixwidth) / (double)_pixelAreaSize.xsize();
double crdWidth = w / fractioOffWidth;
deltax = (crdWidth - w) / 2.0;
_zoomRect = Envelope(Coordinate(viewRect.min_corner().x - deltax,viewRect.min_corner().y - deltay/2.0,0),
Coordinate(viewRect.max_corner().x + deltax,viewRect.max_corner().y + deltay/2.0,0));
} else {
double pixheight = _pixelAreaSize.xsize() / _aspectRatioCoverage;
if ( pixheight > _pixelAreaSize.ysize()){
deltax = (_coverageRect.xlength() - 1) * ( pixheight / _pixelAreaSize.ysize() - 1.0);; //_aspectRatioCoverage;
pixheight = _pixelAreaSize.ysize();
}
double fractionOfHeight = 1.0 - std::abs(_pixelAreaSize.ysize() - pixheight)/(double)_pixelAreaSize.ysize();
double crdHeight = h / fractionOfHeight;
deltay = (crdHeight - h)/ 2.0;
_zoomRect = Envelope(Coordinate(viewRect.min_corner().x - deltax /2.0,viewRect.min_corner().y - deltay,0),
Coordinate(viewRect.max_corner().x + deltax /2.0,viewRect.max_corner().y + deltay,0));
}
viewPoint(_zoomRect.center(), true);
setMVP();
}
void RootDrawer::applyEnvelopeZoom(const Envelope &zoomRect)
{
if ( zoomRect.area() == 1) // we dont zoom in on pointsize area
return;
Envelope envelope = zoomRect;
if ( _zoomRect.isValid()) {
// zooming never changes the shape of the mapwindow so any incomming zoom rectangle must conform to the shape of the existing mapwindow
double factCur = (_zoomRect.xlength() - 1.0) / (_zoomRect.ylength() - 1.0);
double factIn = (zoomRect.xlength() - 1.0) / (zoomRect.ylength() - 1.0);
double delta = std::abs(factCur - factIn);
if ( delta > 0.01 ) {
if ( factCur < 1.0) {
double newHeight = (zoomRect.xlength() - 1) / ( factCur * 2.0);
Coordinate center = zoomRect.center();
envelope = Envelope(Coordinate(zoomRect.min_corner().x, center.y - newHeight), Coordinate(zoomRect.max_corner().x, center.y - newHeight));
} else {
double newWidth = (zoomRect.ylength() - 1) * factCur / 2.0;
Coordinate center = zoomRect.center();
envelope = Envelope(Coordinate(center.x - newWidth, zoomRect.min_corner().y), Coordinate(center.x + newWidth, zoomRect.max_corner().y));
}
}
}
_zoomRect = envelope;
viewPoint(_zoomRect.center(), true);
setMVP();
}
void RootDrawer::setMVP()
{
_projection.setToIdentity();
QRectF rct(_zoomRect.min_corner().x, _zoomRect.min_corner().y,_zoomRect.xlength() -1,_zoomRect.ylength() - 1);
_projection.ortho(rct);
_mvp = _model * _view * _projection;
if ( _coverageRect.xlength() > 0 && _coverageRect.ylength() > 0) {
double xscale = (_zoomRect.xlength() - 1) / (_coverageRect.xlength() - 1);
double yscale = (_zoomRect.ylength() - 1) /(_coverageRect.ylength() - 1);
_zoomScale = std::min(xscale, yscale);
}
if ( _viewEnvelope.isNull() && _zoomRect.isValid() && !_zoomRect.isNull())
_viewEnvelope = _zoomRect;
_screenGrf->envelope(_zoomRect);
_screenGrf->size(_pixelAreaSize);
_screenGrf->compute();
unprepare(DrawerInterface::ptMVP); // we reset the mvp so for all drawers a new value has to be set to the graphics card
}
void RootDrawer::pixelAreaSize(const Size<>& size)
{
if ( size == _pixelAreaSize || size.ysize() == 0 || size.xsize() == 0)
return;
_aspectRatioView = (double)size.xsize() / (double)size.ysize();
if ( _aspectRatioCoverage != 0 && !_zoomRect.isNull()){
double fx = (double)size.xsize() / _pixelAreaSize.xsize();
double fy = (double)size.ysize() / _pixelAreaSize.ysize();
double w = _zoomRect.xlength() - 1;
double h = _zoomRect.ylength() - 1;
Coordinate center = _zoomRect.center();
if ( size.xsize() != _pixelAreaSize.xsize() && size.ysize() != _pixelAreaSize.ysize()){
double dx = w * fx;
double dy = h * fy;
_zoomRect = Envelope(Coordinate(center.x - dx / 2.0, center.y - dy / 2.0), Coordinate(center.x + dx / 2.0, center.y + dy / 2.0));
}else {
if ( size.xsize() != _pixelAreaSize.xsize()) {
double dx = w * fx;
_zoomRect = Envelope(Coordinate(center.x - dx / 2.0, center.y - h / 2.0), Coordinate(center.x + dx / 2.0, center.y + h / 2.0));
}
if ( size.ysize() != _pixelAreaSize.ysize()) {
double dy = h * fy;
_zoomRect = Envelope(Coordinate(center.x - w / 2.0, center.y - dy / 2.0), Coordinate(center.x + w / 2.0, center.y + dy / 2.0));
}
}
}
setMVP();
// auto env = normalizedEnveope(_zoomRect);
// // qDebug() << "zoom" << env.toString() << env.xlength() * _pixelAreaSize.xsize() << env.ylength() * _pixelAreaSize.ysize();
// env = normalizedEnveope(_coverageRect);
// //qDebug() << "cov" << env.toString() << ((env.xlength() - 1) / 2.0) * _pixelAreaSize.xsize() << env.ylength() * _pixelAreaSize.ysize();
// qDebug() << "cov" << ((env.xlength() - 1) / 2.0) * _pixelAreaSize.xsize() ;
_pixelAreaSize = size;
}
Size<> RootDrawer::pixelAreaSize() const
{
return _pixelAreaSize;
}
Size<> RootDrawer::coverageAreaSize() const
{
if ( !_screenGrf.isValid())
return Size<>();
auto bb = _screenGrf->coord2Pixel(_coverageRect);
return bb.size();
}
const QMatrix4x4 &RootDrawer::mvpMatrix() const
{
return _mvp;
}
const ICoordinateSystem &RootDrawer::coordinateSystem() const
{
return _coordinateSystem;
}
void RootDrawer::coordinateSystem(const ICoordinateSystem &csy)
{
_coordinateSystem = csy;
}
const IGeoReference &RootDrawer::screenGrf() const
{
return _screenGrf;
}
void RootDrawer::viewPoint(const Coordinate& viewCenter, bool setEyePoint){
_viewPoint = viewCenter;
if ( setEyePoint){
_eyePoint.x = _viewPoint.x;
_eyePoint.y = _viewPoint.y - _zoomRect.ylength() * 1.5;
_eyePoint.z = _zoomRect.xlength() ;
}
}
void RootDrawer::cleanUp()
{
ComplexDrawer::cleanUp();
}
bool RootDrawer::prepare(DrawerInterface::PreparationType prepType, const IOOptions &options)
{
return ComplexDrawer::prepare(prepType, options) ;
}
double RootDrawer::aspectRatioView() const
{
return _aspectRatioView;
}
double RootDrawer::zoomScale() const
{
return _zoomScale;
}
bool RootDrawer::is3D() const
{
return _is3D;
}
void RootDrawer::set3D(bool yesno)
{
_is3D = yesno;
}
const QQuickFramebufferObject *RootDrawer::fbo() const
{
return _frameBufferObject;
}
Envelope RootDrawer::envelope2RootEnvelope(const ICoordinateSystem &csSource, const Envelope &env)
{
Envelope envelope = (!_coordinateSystem.isValid() ||
!csSource.isValid() ||
_coordinateSystem->isEqual(csSource.ptr()) ||
_coordinateSystem->isUnknown() ||
csSource->isUnknown()) ?
env : _coordinateSystem->convertEnvelope(csSource, env);
return envelope;
}
DrawerInterface::DrawerType RootDrawer::drawerType() const
{
return DrawerInterface::dtDONTCARE; // rootdrawer is never child of anything so it never is a pre,post, or main drawer. it is the root
}
QVariant RootDrawer::attribute(const QString &attrNme) const
{
QString attrName = attrNme.toLower();
QVariant var = ComplexDrawer::attribute(attrName);
if ( var.isValid())
return var;
if ( attrName == "coordinatesystem"){
QVariant var = qVariantFromValue(coordinateSystem());
return var;
}
if ( attrName == "coverageenvelope"){
QVariant var = qVariantFromValue(_coverageRect);
return var;
}
if ( attrName == "zoomenvelope"){
QVariant var = qVariantFromValue(_zoomRect);
return var;
}
if ( attrName == "pixelarea"){
QVariant var = qVariantFromValue(_pixelAreaSize);
return var;
}
return QVariant();
}
void RootDrawer::redraw()
{
emit updateRenderer();
}
Ilwis::Coordinate RootDrawer::normalizedCoord(const Coordinate& crd) const{
QVector3D v1( crd.x,crd.y, crd.is3D()? crd.z : 0);
QVector3D a1 = _mvp * v1;
return Ilwis::Coordinate(a1);
}
Envelope RootDrawer::normalizedEnveope(const Envelope& env) const
{
Ilwis::Coordinate v1normalized =normalizedCoord(env.min_corner());
Ilwis::Coordinate v2normalized = normalizedCoord(env.max_corner());
return Envelope(v1normalized, v2normalized);
}
Ilwis::Coordinate RootDrawer::pixel2Coord(const Ilwis::Pixel& pix){
if ( _screenGrf.isValid())
return _screenGrf->pixel2Coord(pix);
return Ilwis::Coordinate();
}
Ilwis::Pixel RootDrawer::coord2Pixel(const Ilwis::Coordinate& crd){
if ( _screenGrf.isValid())
return _screenGrf->coord2Pixel(crd);
return Ilwis::Pixel();
}
<commit_msg>removed unnecassary error message. In initialization phases this error was generated but it had no effect(and shouldnt)<commit_after>#include "coverage.h"
#include "location.h"
#include "geos/geom/Coordinate.h"
#include "coordinate.h"
#include "box.h"
#include "coordinatesystem.h"
#include "georeference.h"
//#include "cornersgeoreference.h"
#include "rootdrawer.h"
#include "spatialdatadrawer.h"
#include "layersrenderer.h"
using namespace Ilwis;
using namespace Geodrawer;
RootDrawer::RootDrawer(const QQuickFramebufferObject *fbo, const IOOptions& options) : ComplexDrawer("RootDrawer",0,0, options), _frameBufferObject(fbo)
{
valid(true);
_screenGrf = new GeoReference();
_screenGrf->create("corners");
}
RootDrawer::~RootDrawer()
{
cleanUp();
}
void RootDrawer::addSpatialDrawer(DrawerInterface *newdrawer, bool overrule)
{
overrule = drawerCount(ComplexDrawer::dtMAIN) == 0 || overrule;
SpatialDataDrawer *datadrawer = dynamic_cast<SpatialDataDrawer *>(newdrawer);
if ( overrule && datadrawer && datadrawer->coverage().isValid()) {
ICoordinateSystem cs = datadrawer->coverage()->coordinateSystem();
Envelope envelope = envelope2RootEnvelope(cs, datadrawer->envelope());
Envelope viewEnv = _zoomRect;
bool setViewEnv = envelope != viewEnv;
viewEnv += envelope;
_coverageRect = datadrawer->envelope();
if ( setViewEnv)
applyEnvelopeView(viewEnv, true);
}
return ComplexDrawer::addDrawer(newdrawer);
}
void RootDrawer::addEnvelope(const ICoordinateSystem &csSource, const Envelope &env, bool overrule)
{
if ( overrule || !_coverageRect.isValid() || _coverageRect.isNull()) {
Envelope newEnvelope = envelope2RootEnvelope(csSource, env);
_coverageRect += newEnvelope;
}
applyEnvelopeView(_coverageRect, overrule);
}
Envelope RootDrawer::viewEnvelope() const
{
return _viewEnvelope;
}
Envelope RootDrawer::zoomEnvelope() const
{
return _zoomRect;
}
Envelope RootDrawer::coverageEnvelope() const
{
return _coverageRect;
}
void RootDrawer::applyEnvelopeView(const Envelope &viewRect, bool overrule)
{
if ( !_coverageRect.isValid() || _coverageRect.isNull()){
return;
}
if ( !_pixelAreaSize.isValid()) {
ERROR2(ERR_NO_INITIALIZED_2,TR("Pixel area"), TR("Visualization"));
return;
}
if ( overrule)
_viewEnvelope = Envelope();
double w = viewRect.xlength() - 1;
double h = viewRect.ylength() - 1;
_aspectRatioCoverage = w / h;
double deltax = 0, deltay = 0;
Envelope env;
if ( _aspectRatioCoverage <= 1.0) { // coverage is higher than it is wide)
double pixwidth = (double)_pixelAreaSize.ysize() * _aspectRatioCoverage;
if ( pixwidth > _pixelAreaSize.xsize()) {
deltay = (_coverageRect.ylength() - 1) * ( pixwidth / _pixelAreaSize.xsize() - 1.0);
pixwidth = _pixelAreaSize.xsize();
}
double fractioOffWidth = 1.0 - (_pixelAreaSize.xsize() - pixwidth) / (double)_pixelAreaSize.xsize();
double crdWidth = w / fractioOffWidth;
deltax = (crdWidth - w) / 2.0;
_zoomRect = Envelope(Coordinate(viewRect.min_corner().x - deltax,viewRect.min_corner().y - deltay/2.0,0),
Coordinate(viewRect.max_corner().x + deltax,viewRect.max_corner().y + deltay/2.0,0));
} else {
double pixheight = _pixelAreaSize.xsize() / _aspectRatioCoverage;
if ( pixheight > _pixelAreaSize.ysize()){
deltax = (_coverageRect.xlength() - 1) * ( pixheight / _pixelAreaSize.ysize() - 1.0);; //_aspectRatioCoverage;
pixheight = _pixelAreaSize.ysize();
}
double fractionOfHeight = 1.0 - std::abs(_pixelAreaSize.ysize() - pixheight)/(double)_pixelAreaSize.ysize();
double crdHeight = h / fractionOfHeight;
deltay = (crdHeight - h)/ 2.0;
_zoomRect = Envelope(Coordinate(viewRect.min_corner().x - deltax /2.0,viewRect.min_corner().y - deltay,0),
Coordinate(viewRect.max_corner().x + deltax /2.0,viewRect.max_corner().y + deltay,0));
}
viewPoint(_zoomRect.center(), true);
setMVP();
}
void RootDrawer::applyEnvelopeZoom(const Envelope &zoomRect)
{
if ( zoomRect.area() == 1) // we dont zoom in on pointsize area
return;
Envelope envelope = zoomRect;
if ( _zoomRect.isValid()) {
// zooming never changes the shape of the mapwindow so any incomming zoom rectangle must conform to the shape of the existing mapwindow
double factCur = (_zoomRect.xlength() - 1.0) / (_zoomRect.ylength() - 1.0);
double factIn = (zoomRect.xlength() - 1.0) / (zoomRect.ylength() - 1.0);
double delta = std::abs(factCur - factIn);
if ( delta > 0.01 ) {
if ( factCur < 1.0) {
double newHeight = (zoomRect.xlength() - 1) / ( factCur * 2.0);
Coordinate center = zoomRect.center();
envelope = Envelope(Coordinate(zoomRect.min_corner().x, center.y - newHeight), Coordinate(zoomRect.max_corner().x, center.y - newHeight));
} else {
double newWidth = (zoomRect.ylength() - 1) * factCur / 2.0;
Coordinate center = zoomRect.center();
envelope = Envelope(Coordinate(center.x - newWidth, zoomRect.min_corner().y), Coordinate(center.x + newWidth, zoomRect.max_corner().y));
}
}
}
_zoomRect = envelope;
viewPoint(_zoomRect.center(), true);
setMVP();
}
void RootDrawer::setMVP()
{
_projection.setToIdentity();
QRectF rct(_zoomRect.min_corner().x, _zoomRect.min_corner().y,_zoomRect.xlength() -1,_zoomRect.ylength() - 1);
_projection.ortho(rct);
_mvp = _model * _view * _projection;
if ( _coverageRect.xlength() > 0 && _coverageRect.ylength() > 0) {
double xscale = (_zoomRect.xlength() - 1) / (_coverageRect.xlength() - 1);
double yscale = (_zoomRect.ylength() - 1) /(_coverageRect.ylength() - 1);
_zoomScale = std::min(xscale, yscale);
}
if ( _viewEnvelope.isNull() && _zoomRect.isValid() && !_zoomRect.isNull())
_viewEnvelope = _zoomRect;
_screenGrf->envelope(_zoomRect);
_screenGrf->size(_pixelAreaSize);
_screenGrf->compute();
unprepare(DrawerInterface::ptMVP); // we reset the mvp so for all drawers a new value has to be set to the graphics card
}
void RootDrawer::pixelAreaSize(const Size<>& size)
{
if ( size == _pixelAreaSize || size.ysize() == 0 || size.xsize() == 0)
return;
_aspectRatioView = (double)size.xsize() / (double)size.ysize();
if ( _aspectRatioCoverage != 0 && !_zoomRect.isNull()){
double fx = (double)size.xsize() / _pixelAreaSize.xsize();
double fy = (double)size.ysize() / _pixelAreaSize.ysize();
double w = _zoomRect.xlength() - 1;
double h = _zoomRect.ylength() - 1;
Coordinate center = _zoomRect.center();
if ( size.xsize() != _pixelAreaSize.xsize() && size.ysize() != _pixelAreaSize.ysize()){
double dx = w * fx;
double dy = h * fy;
_zoomRect = Envelope(Coordinate(center.x - dx / 2.0, center.y - dy / 2.0), Coordinate(center.x + dx / 2.0, center.y + dy / 2.0));
}else {
if ( size.xsize() != _pixelAreaSize.xsize()) {
double dx = w * fx;
_zoomRect = Envelope(Coordinate(center.x - dx / 2.0, center.y - h / 2.0), Coordinate(center.x + dx / 2.0, center.y + h / 2.0));
}
if ( size.ysize() != _pixelAreaSize.ysize()) {
double dy = h * fy;
_zoomRect = Envelope(Coordinate(center.x - w / 2.0, center.y - dy / 2.0), Coordinate(center.x + w / 2.0, center.y + dy / 2.0));
}
}
}
setMVP();
// auto env = normalizedEnveope(_zoomRect);
// // qDebug() << "zoom" << env.toString() << env.xlength() * _pixelAreaSize.xsize() << env.ylength() * _pixelAreaSize.ysize();
// env = normalizedEnveope(_coverageRect);
// //qDebug() << "cov" << env.toString() << ((env.xlength() - 1) / 2.0) * _pixelAreaSize.xsize() << env.ylength() * _pixelAreaSize.ysize();
// qDebug() << "cov" << ((env.xlength() - 1) / 2.0) * _pixelAreaSize.xsize() ;
_pixelAreaSize = size;
}
Size<> RootDrawer::pixelAreaSize() const
{
return _pixelAreaSize;
}
Size<> RootDrawer::coverageAreaSize() const
{
if ( !_screenGrf.isValid())
return Size<>();
auto bb = _screenGrf->coord2Pixel(_coverageRect);
return bb.size();
}
const QMatrix4x4 &RootDrawer::mvpMatrix() const
{
return _mvp;
}
const ICoordinateSystem &RootDrawer::coordinateSystem() const
{
return _coordinateSystem;
}
void RootDrawer::coordinateSystem(const ICoordinateSystem &csy)
{
_coordinateSystem = csy;
}
const IGeoReference &RootDrawer::screenGrf() const
{
return _screenGrf;
}
void RootDrawer::viewPoint(const Coordinate& viewCenter, bool setEyePoint){
_viewPoint = viewCenter;
if ( setEyePoint){
_eyePoint.x = _viewPoint.x;
_eyePoint.y = _viewPoint.y - _zoomRect.ylength() * 1.5;
_eyePoint.z = _zoomRect.xlength() ;
}
}
void RootDrawer::cleanUp()
{
ComplexDrawer::cleanUp();
}
bool RootDrawer::prepare(DrawerInterface::PreparationType prepType, const IOOptions &options)
{
return ComplexDrawer::prepare(prepType, options) ;
}
double RootDrawer::aspectRatioView() const
{
return _aspectRatioView;
}
double RootDrawer::zoomScale() const
{
return _zoomScale;
}
bool RootDrawer::is3D() const
{
return _is3D;
}
void RootDrawer::set3D(bool yesno)
{
_is3D = yesno;
}
const QQuickFramebufferObject *RootDrawer::fbo() const
{
return _frameBufferObject;
}
Envelope RootDrawer::envelope2RootEnvelope(const ICoordinateSystem &csSource, const Envelope &env)
{
Envelope envelope = (!_coordinateSystem.isValid() ||
!csSource.isValid() ||
_coordinateSystem->isEqual(csSource.ptr()) ||
_coordinateSystem->isUnknown() ||
csSource->isUnknown()) ?
env : _coordinateSystem->convertEnvelope(csSource, env);
return envelope;
}
DrawerInterface::DrawerType RootDrawer::drawerType() const
{
return DrawerInterface::dtDONTCARE; // rootdrawer is never child of anything so it never is a pre,post, or main drawer. it is the root
}
QVariant RootDrawer::attribute(const QString &attrNme) const
{
QString attrName = attrNme.toLower();
QVariant var = ComplexDrawer::attribute(attrName);
if ( var.isValid())
return var;
if ( attrName == "coordinatesystem"){
QVariant var = qVariantFromValue(coordinateSystem());
return var;
}
if ( attrName == "latlonenvelope"){
QVariant var;
if ( coordinateSystem()->isLatLon())
var = qVariantFromValue(_coverageRect);
else {
ICoordinateSystem csyWgs84("code=epsg:4326");
Envelope llEnvelope = csyWgs84->convertEnvelope(coordinateSystem(), _coverageRect);
var = qVariantFromValue(llEnvelope);
}
return var;
}
if ( attrName == "coverageenvelope"){
QVariant var = qVariantFromValue(_coverageRect);
return var;
}
if ( attrName == "zoomenvelope"){
QVariant var = qVariantFromValue(_zoomRect);
return var;
}
if ( attrName == "pixelarea"){
QVariant var = qVariantFromValue(_pixelAreaSize);
return var;
}
return QVariant();
}
void RootDrawer::redraw()
{
emit updateRenderer();
}
Ilwis::Coordinate RootDrawer::normalizedCoord(const Coordinate& crd) const{
QVector3D v1( crd.x,crd.y, crd.is3D()? crd.z : 0);
QVector3D a1 = _mvp * v1;
return Ilwis::Coordinate(a1);
}
Envelope RootDrawer::normalizedEnveope(const Envelope& env) const
{
Ilwis::Coordinate v1normalized =normalizedCoord(env.min_corner());
Ilwis::Coordinate v2normalized = normalizedCoord(env.max_corner());
return Envelope(v1normalized, v2normalized);
}
Ilwis::Coordinate RootDrawer::pixel2Coord(const Ilwis::Pixel& pix){
if ( _screenGrf.isValid())
return _screenGrf->pixel2Coord(pix);
return Ilwis::Coordinate();
}
Ilwis::Pixel RootDrawer::coord2Pixel(const Ilwis::Coordinate& crd){
if ( _screenGrf.isValid())
return _screenGrf->coord2Pixel(crd);
return Ilwis::Pixel();
}
<|endoftext|> |
<commit_before>#include "FaultState.h"
#include "utilConstants.h"
#include <sstream>
using std::string;
using std::stringstream;
using std::auto_ptr;
using acsalarm::FaultState;
/**
* Default Constructor
*/
FaultState::FaultState()
{
auto_ptr<Timestamp> tstamp(new Timestamp());
setUserTimestamp(tstamp);
}
/**
* Constructor for initializing a fault state with values
*/
FaultState::FaultState(string theFamily, string theMember, int theCode)
{
setFamily(theFamily);
setMember(theMember);
setCode(theCode);
auto_ptr<Timestamp> tstamp(new Timestamp());
setUserTimestamp(tstamp);
}
/**
* Copy constructor.
*/
FaultState::FaultState(const FaultState & fltState)
{
*this = fltState;
}
/**
* Destructor
*/
FaultState::~FaultState()
{
}
/*
* Assignment operator
*/
FaultState & FaultState::operator=(const FaultState & rhs)
{
setFamily(rhs.getFamily());
setCode(rhs.getCode());
setMember(rhs.getMember());
setDescriptor(rhs.getDescriptor());
setActivatedByBackup(rhs.getActivatedByBackup());
setTerminatedByBackup(rhs.getTerminatedByBackup());
if(NULL != rhs.userTimestamp.get())
{
Timestamp * tstampPtr = new Timestamp(*(rhs.userTimestamp));
auto_ptr<Timestamp> tstampAptr(tstampPtr);
setUserTimestamp(tstampAptr);
}
if(NULL != rhs.userProperties.get())
{
Properties * propsPtr = new Properties(*(rhs.userProperties));
auto_ptr<Properties> propsAptr(propsPtr);
setUserProperties(propsAptr);
}
return *this;
}
/**
* Returns an XML representation of the fault state. NOTE: this
* will not be a complete XML document, but just a fragment.
*
* @param amountToIndent the amount (in spaces) to indent for readability
*
* For example:
*
* <fault-state family="AlarmSource" member="ALARM_SOURCE_ANTENNA" code="1">
* <descriptor>TERMINATE</descriptor>
* <user-properties>
* <property name="ASI_PREFIX" value="prefix"/>
* <property name="TEST_PROPERTY" value="TEST_VALUE"/>
* <property name="ASI_SUFFIX" value="suffix"/>
* </user-properties>
* <user-timestamp seconds="1129902763" microseconds="105000"/>
* </fault-state>
*/
string FaultState::toXML(int amountToIndent)
{
string retVal;
// generate the fault-state opening element
// e.g. <fault-state family="AlarmSource" member="ALARM_SOURCE_ANTENNA" code="1">
for(int x = 0; x < amountToIndent; x++)
{
retVal += SPACE;
}
retVal += LESS_THAN_SIGN;
retVal += FAULT_STATE_ELEMENT_NAME;
retVal += SPACE;
// output the fault's family
retVal += FAULT_STATE_FAMILY_ATTRIBUTE_NAME;
retVal += EQUALS_SIGN;
retVal += DOUBLE_QUOTE;
retVal += getFamily();
retVal += DOUBLE_QUOTE;
retVal += SPACE;
// output the fault's member
retVal += FAULT_STATE_MEMBER_ATTRIBUTE_NAME;
retVal += EQUALS_SIGN;
retVal += DOUBLE_QUOTE;
retVal += getMember();
retVal += DOUBLE_QUOTE;
retVal += SPACE;
// output the fault's code
retVal += FAULT_STATE_CODE_ATTRIBUTE_NAME;
retVal += EQUALS_SIGN;
retVal += DOUBLE_QUOTE;
stringstream strStream;
strStream << getCode();
retVal.append(strStream.str());
retVal += DOUBLE_QUOTE;
retVal += GREATER_THAN_SIGN;
retVal += NEWLINE;
// indent for readability
for(int x = 0; x < amountToIndent+3; x++)
{
retVal += SPACE;
}
// generate the descriptor element
// e.g. <descriptor>TERMINATE</descriptor>
retVal += LESS_THAN_SIGN;
retVal += FAULT_STATE_DESCRIPTOR_ELEMENT_NAME;
retVal += GREATER_THAN_SIGN;
retVal += getDescriptor();
retVal += LESS_THAN_SIGN;
retVal += FORWARD_SLASH;
retVal += FAULT_STATE_DESCRIPTOR_ELEMENT_NAME;
retVal += GREATER_THAN_SIGN;
retVal += NEWLINE;
// generate the properties element
// e.g.
//
// <user-properties>
// <property name="ASI_PREFIX" value="prefix"/>
// <property name="TEST_PROPERTY" value="TEST_VALUE"/>
// <property name="ASI_SUFFIX" value="suffix"/>
// </user-properties>
if(NULL == userProperties.get()) {
// TODO: throw an exception or log an error
}
else {
retVal += userProperties->toXML(amountToIndent+3);
}
// generate the user timestamp element
// e.g. <user-timestamp seconds="1129902763" microseconds="105000"/>
if(NULL == userTimestamp.get()) {
// TODO: throw an exception or log an error
}
else {
retVal += userTimestamp->toXML(USER_TIMESTAMP_ELEMENT_NAME, amountToIndent+3);
}
// generate the fault-state closing element
// e.g. </fault-state>
for(int x = 0; x < amountToIndent; x++)
{
retVal += SPACE;
}
retVal += LESS_THAN_SIGN;
retVal += FORWARD_SLASH;
retVal += FAULT_STATE_ELEMENT_NAME;
retVal += GREATER_THAN_SIGN;
retVal += NEWLINE;
return retVal;
}
/**
* Fault family accessor method.
* @param faultFamily the fault family.
*/
void FaultState::setFamily(const string & faultFamily) {
unsigned int pos;
string nonConstFaultFamily(faultFamily);
do
{
pos = nonConstFaultFamily.find(":");
if (pos != string::npos)
{
nonConstFaultFamily.replace(pos,1,"#");
}
}
while(pos != string::npos);
family = nonConstFaultFamily;
}
/**
* Fault member accessor method.
* @param member the fault member.
*/
void FaultState::setMember(const string & newFaultMember) {
unsigned int pos;
string nonConstFaultMember(newFaultMember);
do
{
pos = nonConstFaultMember.find(":");
if (pos != string::npos)
{
nonConstFaultMember.replace(pos,1,"#");
}
}
while(pos != string::npos);
member = nonConstFaultMember;
}
<commit_msg>Changing int by size_t<commit_after>#include "FaultState.h"
#include "utilConstants.h"
#include <sstream>
using std::string;
using std::stringstream;
using std::auto_ptr;
using acsalarm::FaultState;
/**
* Default Constructor
*/
FaultState::FaultState()
{
auto_ptr<Timestamp> tstamp(new Timestamp());
setUserTimestamp(tstamp);
}
/**
* Constructor for initializing a fault state with values
*/
FaultState::FaultState(string theFamily, string theMember, int theCode)
{
setFamily(theFamily);
setMember(theMember);
setCode(theCode);
auto_ptr<Timestamp> tstamp(new Timestamp());
setUserTimestamp(tstamp);
}
/**
* Copy constructor.
*/
FaultState::FaultState(const FaultState & fltState)
{
*this = fltState;
}
/**
* Destructor
*/
FaultState::~FaultState()
{
}
/*
* Assignment operator
*/
FaultState & FaultState::operator=(const FaultState & rhs)
{
setFamily(rhs.getFamily());
setCode(rhs.getCode());
setMember(rhs.getMember());
setDescriptor(rhs.getDescriptor());
setActivatedByBackup(rhs.getActivatedByBackup());
setTerminatedByBackup(rhs.getTerminatedByBackup());
if(NULL != rhs.userTimestamp.get())
{
Timestamp * tstampPtr = new Timestamp(*(rhs.userTimestamp));
auto_ptr<Timestamp> tstampAptr(tstampPtr);
setUserTimestamp(tstampAptr);
}
if(NULL != rhs.userProperties.get())
{
Properties * propsPtr = new Properties(*(rhs.userProperties));
auto_ptr<Properties> propsAptr(propsPtr);
setUserProperties(propsAptr);
}
return *this;
}
/**
* Returns an XML representation of the fault state. NOTE: this
* will not be a complete XML document, but just a fragment.
*
* @param amountToIndent the amount (in spaces) to indent for readability
*
* For example:
*
* <fault-state family="AlarmSource" member="ALARM_SOURCE_ANTENNA" code="1">
* <descriptor>TERMINATE</descriptor>
* <user-properties>
* <property name="ASI_PREFIX" value="prefix"/>
* <property name="TEST_PROPERTY" value="TEST_VALUE"/>
* <property name="ASI_SUFFIX" value="suffix"/>
* </user-properties>
* <user-timestamp seconds="1129902763" microseconds="105000"/>
* </fault-state>
*/
string FaultState::toXML(int amountToIndent)
{
string retVal;
// generate the fault-state opening element
// e.g. <fault-state family="AlarmSource" member="ALARM_SOURCE_ANTENNA" code="1">
for(int x = 0; x < amountToIndent; x++)
{
retVal += SPACE;
}
retVal += LESS_THAN_SIGN;
retVal += FAULT_STATE_ELEMENT_NAME;
retVal += SPACE;
// output the fault's family
retVal += FAULT_STATE_FAMILY_ATTRIBUTE_NAME;
retVal += EQUALS_SIGN;
retVal += DOUBLE_QUOTE;
retVal += getFamily();
retVal += DOUBLE_QUOTE;
retVal += SPACE;
// output the fault's member
retVal += FAULT_STATE_MEMBER_ATTRIBUTE_NAME;
retVal += EQUALS_SIGN;
retVal += DOUBLE_QUOTE;
retVal += getMember();
retVal += DOUBLE_QUOTE;
retVal += SPACE;
// output the fault's code
retVal += FAULT_STATE_CODE_ATTRIBUTE_NAME;
retVal += EQUALS_SIGN;
retVal += DOUBLE_QUOTE;
stringstream strStream;
strStream << getCode();
retVal.append(strStream.str());
retVal += DOUBLE_QUOTE;
retVal += GREATER_THAN_SIGN;
retVal += NEWLINE;
// indent for readability
for(int x = 0; x < amountToIndent+3; x++)
{
retVal += SPACE;
}
// generate the descriptor element
// e.g. <descriptor>TERMINATE</descriptor>
retVal += LESS_THAN_SIGN;
retVal += FAULT_STATE_DESCRIPTOR_ELEMENT_NAME;
retVal += GREATER_THAN_SIGN;
retVal += getDescriptor();
retVal += LESS_THAN_SIGN;
retVal += FORWARD_SLASH;
retVal += FAULT_STATE_DESCRIPTOR_ELEMENT_NAME;
retVal += GREATER_THAN_SIGN;
retVal += NEWLINE;
// generate the properties element
// e.g.
//
// <user-properties>
// <property name="ASI_PREFIX" value="prefix"/>
// <property name="TEST_PROPERTY" value="TEST_VALUE"/>
// <property name="ASI_SUFFIX" value="suffix"/>
// </user-properties>
if(NULL == userProperties.get()) {
// TODO: throw an exception or log an error
}
else {
retVal += userProperties->toXML(amountToIndent+3);
}
// generate the user timestamp element
// e.g. <user-timestamp seconds="1129902763" microseconds="105000"/>
if(NULL == userTimestamp.get()) {
// TODO: throw an exception or log an error
}
else {
retVal += userTimestamp->toXML(USER_TIMESTAMP_ELEMENT_NAME, amountToIndent+3);
}
// generate the fault-state closing element
// e.g. </fault-state>
for(int x = 0; x < amountToIndent; x++)
{
retVal += SPACE;
}
retVal += LESS_THAN_SIGN;
retVal += FORWARD_SLASH;
retVal += FAULT_STATE_ELEMENT_NAME;
retVal += GREATER_THAN_SIGN;
retVal += NEWLINE;
return retVal;
}
/**
* Fault family accessor method.
* @param faultFamily the fault family.
*/
void FaultState::setFamily(const string & faultFamily) {
size_t pos;
string nonConstFaultFamily(faultFamily);
do
{
pos = nonConstFaultFamily.find(":");
if (pos != string::npos)
{
nonConstFaultFamily.replace(pos,1,"#");
}
}
while(pos != string::npos);
family = nonConstFaultFamily;
}
/**
* Fault member accessor method.
* @param member the fault member.
*/
void FaultState::setMember(const string & newFaultMember) {
size_t pos;
string nonConstFaultMember(newFaultMember);
do
{
pos = nonConstFaultMember.find(":");
if (pos != string::npos)
{
nonConstFaultMember.replace(pos,1,"#");
}
}
while(pos != string::npos);
member = nonConstFaultMember;
}
<|endoftext|> |
<commit_before>/******************************************************************************\
* File: support.cpp
* Purpose: Implementation of support classes
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/config.h>
#include <wx/stockitem.h> // for wxGetStockLabel
#include <wx/extension/filedlg.h>
#include <wx/extension/lexers.h>
#include <wx/extension/vcs.h>
#include <wx/extension/util.h>
#include <wx/extension/report/listviewfile.h>
#include <wx/extension/report/process.h>
#include <wx/extension/report/stc.h>
#ifndef __WXMSW__
#include "app.xpm"
#endif
#include "support.h"
#include "defs.h"
Frame::Frame()
: wxExFrameWithHistory(
NULL,
wxID_ANY,
wxTheApp->GetAppName(), // title
25, // maxFiles
4) // maxProjects
, m_MenuVCS(NULL)
, m_MenuVCSFilled(false)
{
SetIcon(wxICON(app));
#if wxUSE_STATUSBAR
std::vector<wxExPane> panes;
panes.push_back(wxExPane("PaneText", -3));
panes.push_back(wxExPane("PaneFileType", 50, _("File Type")));
panes.push_back(wxExPane("PaneLines", 100, _("Lines")));
// Add the lexer pane only if we have lexers.
wxExLexers* lexers = wxExLexers::Get();
if (lexers->Count() > 0)
{
#ifdef __WXMSW__
const int lexer_size = 60;
#else
const int lexer_size = 75;
#endif
panes.push_back(wxExPane("PaneLexer", lexer_size, _("Lexer")));
}
panes.push_back(wxExPane("PaneItems", 65, _("Items")));
SetupStatusBar(panes);
#endif
wxMenuBar* menubar = new wxMenuBar(wxMB_DOCKABLE); // wxMB_DOCKABLE only used for GTK
SetMenuBar(menubar);
wxExMenu *menuFile = new wxExMenu();
menuFile->Append(wxID_NEW);
menuFile->Append(wxID_OPEN);
UseFileHistory(ID_RECENT_FILE_MENU, menuFile);
menuFile->Append(ID_OPEN_LEXERS, _("Open &Lexers"));
menuFile->Append(ID_OPEN_LOGFILE, _("Open &Logfile"));
menuFile->Append(wxID_CLOSE);
menuFile->Append(ID_ALL_STC_CLOSE, _("Close A&ll"));
menuFile->AppendSeparator();
menuFile->Append(wxID_SAVE);
menuFile->Append(wxID_SAVEAS);
menuFile->Append(ID_ALL_STC_SAVE, _("Save A&ll"), wxEmptyString, wxART_FILE_SAVE);
menuFile->AppendSeparator();
menuFile->AppendPrint();
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
wxExMenu *menuEdit = new wxExMenu();
menuEdit->Append(wxID_UNDO);
menuEdit->Append(wxID_REDO);
menuEdit->AppendSeparator();
menuEdit->Append(wxID_CUT);
menuEdit->Append(wxID_COPY);
menuEdit->Append(wxID_PASTE);
menuEdit->AppendSeparator();
menuEdit->Append(wxID_FIND);
menuEdit->Append(ID_EDIT_FIND_NEXT, _("Find &Next\tF3"));
menuEdit->Append(wxID_REPLACE);
menuEdit->Append(ID_FIND_IN_FILES, wxExEllipsed(_("Find &In Files")));
menuEdit->Append(ID_REPLACE_IN_FILES, wxExEllipsed(_("Replace In File&s")));
menuEdit->AppendSeparator();
menuEdit->AppendTools();
menuEdit->AppendSeparator();
menuEdit->Append(wxID_JUMP_TO);
menuEdit->AppendSeparator();
menuEdit->Append(ID_EDIT_CONTROL_CHAR, wxExEllipsed(_("&Control Char"), "Ctrl-H"));
menuEdit->AppendSeparator();
m_MenuVCS = new wxExMenu;
menuEdit->AppendSubMenu(m_MenuVCS, "&VCS");
menuEdit->AppendSeparator();
if (wxExVCS::Get()->Use())
{
BuildVCSMenu(true);
}
menuEdit->Append(ID_EDIT_MACRO_START_RECORD, _("Start Record"));
menuEdit->Append(ID_EDIT_MACRO_STOP_RECORD, _("Stop Record"));
menuEdit->Append(ID_EDIT_MACRO_PLAYBACK, _("Playback\tCtrl-M"));
wxMenu *menuView = new wxMenu;
menuView->AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar"));
menuView->AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar"));
menuView->AppendCheckItem(ID_VIEW_MENUBAR, _("&Menubar"));
menuView->AppendCheckItem(ID_VIEW_FINDBAR, _("&Findbar"));
menuView->AppendSeparator();
menuView->AppendCheckItem(ID_VIEW_FILES, _("&Files"));
menuView->AppendCheckItem(ID_VIEW_PROJECTS, _("&Projects"));
menuView->AppendCheckItem(ID_VIEW_DIRCTRL, _("&Explorer"));
menuView->AppendCheckItem(ID_VIEW_HISTORY, _("&History"));
menuView->AppendCheckItem(ID_VIEW_OUTPUT, _("&Output"));
menuView->AppendSeparator();
menuView->AppendCheckItem(ID_VIEW_ASCII_TABLE, _("&Ascii Table"));
wxMenu *menuProcess = new wxMenu();
menuProcess->Append(ID_PROCESS_SELECT, wxExEllipsed(_("&Select")));
menuProcess->AppendSeparator();
menuProcess->Append(wxID_EXECUTE);
menuProcess->Append(wxID_STOP);
wxExMenu *menuProject = new wxExMenu();
menuProject->Append(ID_PROJECT_NEW, wxGetStockLabel(wxID_NEW), wxEmptyString, wxART_NEW);
menuProject->Append(ID_PROJECT_OPEN, wxGetStockLabel(wxID_OPEN), wxEmptyString, wxART_FILE_OPEN);
UseProjectHistory(ID_RECENT_PROJECT_MENU, menuProject);
menuProject->Append(ID_PROJECT_OPENTEXT, _("&Open As Text"));
menuProject->Append(ID_PROJECT_CLOSE, wxGetStockLabel(wxID_CLOSE), wxEmptyString, wxART_CLOSE);
menuProject->AppendSeparator();
menuProject->Append(ID_PROJECT_SAVE, wxGetStockLabel(wxID_SAVE), wxEmptyString, wxART_FILE_SAVE);
menuProject->Append(ID_PROJECT_SAVEAS, wxGetStockLabel(wxID_SAVEAS), wxEmptyString, wxART_FILE_SAVE_AS);
menuProject->AppendSeparator();
menuProject->AppendCheckItem(ID_SORT_SYNC, _("&Auto Sort"));
wxMenu *menuWindow = new wxMenu();
menuWindow->Append(ID_SPLIT, _("Split"));
wxMenu* menuOptions = new wxMenu();
menuOptions->Append(ID_OPTION_VCS_AND_COMPARATOR, wxExEllipsed(_("Set VCS And &Comparator")));
menuOptions->AppendSeparator();
menuOptions->Append(ID_OPTION_LIST_FONT, wxExEllipsed(_("Set &List Font")));
// text also used as caption
menuOptions->Append(ID_OPTION_LIST_READONLY_COLOUR, wxExEllipsed(_("Set List Read Only Colour")));
wxMenu *menuListSort = new wxMenu;
menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_ASCENDING, _("&Ascending"));
menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_DESCENDING, _("&Descending"));
menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_TOGGLE, _("&Toggle"));
menuOptions->AppendSubMenu(menuListSort, _("Set &List Sort Method"));
menuOptions->AppendSeparator();
menuOptions->Append(ID_OPTION_EDITOR, wxExEllipsed(_("Set &Editor Options")));
wxMenu *menuHelp = new wxMenu();
menuHelp->Append(wxID_ABOUT);
menubar->Append(menuFile, wxGetStockLabel(wxID_FILE));
menubar->Append(menuEdit, wxGetStockLabel(wxID_EDIT));
menubar->Append(menuView, _("&View"));
menubar->Append(menuProcess, _("&Process"));
menubar->Append(menuProject, _("&Project"));
menubar->Append(menuWindow, _("&Window"));
menubar->Append(menuOptions, _("&Options"));
menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));
CreateToolBar();
m_ToolBar->AddTool(wxID_OPEN);
m_ToolBar->AddTool(wxID_SAVE);
m_ToolBar->AddTool(wxID_PRINT);
m_ToolBar->AddSeparator();
m_ToolBar->AddTool(wxID_FIND);
#ifdef __WXGTK__
// wxID_EXECUTE is not part of art provider, but GTK directly,
// so the following does not present a bitmap.
//m_ToolBar->AddSeparator();
//m_ToolBar->AddTool(wxID_EXECUTE);
#endif
m_ToolBar->AddSeparator();
((wxToolBar*)m_ToolBar)->AddTool(
ID_PROJECT_OPEN,
wxEmptyString,
wxArtProvider::GetBitmap(wxART_FILE_OPEN, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
wxExEllipsed(_("Open project")));
((wxToolBar*)m_ToolBar)->AddTool(
ID_PROJECT_SAVE,
wxEmptyString,
wxArtProvider::GetBitmap(wxART_FILE_SAVE, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
_("Save project"));
#if wxUSE_CHECKBOX
m_ToolBar->AddSeparator();
m_ToolBar->AddControl(
m_HexModeCheckBox = new wxCheckBox(
m_ToolBar,
ID_EDIT_HEX_MODE,
"Hex",
wxDefaultPosition,
wxSize(-1, m_ToolBar->GetToolSize().GetHeight())));
m_ToolBar->AddControl(
m_SyncCheckBox = new wxCheckBox(
m_ToolBar,
ID_SYNC_MODE,
"Sync",
wxDefaultPosition,
wxSize(-1, m_ToolBar->GetToolSize().GetHeight())));
#if wxUSE_TOOLTIPS
m_HexModeCheckBox->SetToolTip(_("View in hex mode"));
#endif
m_HexModeCheckBox->SetValue(wxConfigBase::Get()->ReadBool("HexMode", false)); // default no hex
#if wxUSE_TOOLTIPS
m_SyncCheckBox->SetToolTip(_("Synchronize modified files"));
#endif
m_SyncCheckBox->SetValue(wxConfigBase::Get()->ReadBool("AllowSync", true));
#endif // wxUSE_CHECKBOX
m_ToolBar->Realize();
}
bool Frame::AllowClose(wxWindowID id, wxWindow* page)
{
if (wxExProcess::Get()->IsRunning())
{
return false;
}
else if (id == NOTEBOOK_EDITORS)
{
wxExFileDialog dlg(this, (wxExSTCWithFrame*)page);
return dlg.ShowModalIfChanged() == wxID_OK;
}
else if (id == NOTEBOOK_PROJECTS)
{
wxExFileDialog dlg(this, (wxExListViewFile*)page);
return dlg.ShowModalIfChanged() == wxID_OK;
}
else
{
return wxExFrameWithHistory::AllowClose(id, page);
}
}
void Frame::BuildVCSMenu(bool fill)
{
if (m_MenuVCSFilled)
{
wxMenuItem* item;
while ((item = m_MenuVCS->FindItem(wxID_SEPARATOR)) != NULL)
{
m_MenuVCS->Destroy(item);
}
m_MenuVCS->Destroy(ID_VCS_STAT);
m_MenuVCS->Destroy(ID_VCS_INFO);
m_MenuVCS->Destroy(ID_VCS_LOG);
m_MenuVCS->Destroy(ID_VCS_LS);
m_MenuVCS->Destroy(ID_VCS_DIFF);
m_MenuVCS->Destroy(ID_VCS_HELP);
m_MenuVCS->Destroy(ID_VCS_UPDATE);
m_MenuVCS->Destroy(ID_VCS_COMMIT);
m_MenuVCS->Destroy(ID_VCS_ADD);
}
m_MenuVCS->AppendVCS(ID_VCS_STAT);
m_MenuVCS->AppendVCS(ID_VCS_INFO);
m_MenuVCS->AppendVCS(ID_VCS_LOG);
m_MenuVCS->AppendVCS(ID_VCS_LS);
m_MenuVCS->AppendVCS(ID_VCS_DIFF);
m_MenuVCS->AppendVCS(ID_VCS_HELP);
m_MenuVCS->AppendSeparator();
m_MenuVCS->AppendVCS(ID_VCS_UPDATE);
m_MenuVCS->AppendVCS(ID_VCS_COMMIT);
m_MenuVCS->AppendSeparator();
m_MenuVCS->AppendVCS(ID_VCS_ADD);
m_MenuVCSFilled = fill;
}
void Frame::OnNotebook(wxWindowID id, wxWindow* page)
{
if (id == NOTEBOOK_EDITORS)
{
((wxExSTCWithFrame*)page)->PropertiesMessage();
}
else if (id == NOTEBOOK_PROJECTS)
{
SetTitle(wxEmptyString, ((wxExListViewFile*)page)->GetFileName().GetName());
#if wxUSE_STATUSBAR
StatusText(((wxExListViewFile*)page)->GetFileName());
((wxExListViewFile*)page)->UpdateStatusBar();
#endif
}
else if (id == NOTEBOOK_LISTS)
{
// Do nothing special.
}
else
{
wxFAIL;
}
}
<commit_msg>fixed error<commit_after>/******************************************************************************\
* File: support.cpp
* Purpose: Implementation of support classes
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/config.h>
#include <wx/stockitem.h> // for wxGetStockLabel
#include <wx/extension/filedlg.h>
#include <wx/extension/lexers.h>
#include <wx/extension/vcs.h>
#include <wx/extension/util.h>
#include <wx/extension/report/listviewfile.h>
#include <wx/extension/report/process.h>
#include <wx/extension/report/stc.h>
#ifndef __WXMSW__
#include "app.xpm"
#endif
#include "support.h"
#include "defs.h"
Frame::Frame()
: wxExFrameWithHistory(
NULL,
wxID_ANY,
wxTheApp->GetAppName(), // title
25, // maxFiles
4) // maxProjects
, m_MenuVCS(NULL)
, m_MenuVCSFilled(false)
{
SetIcon(wxICON(app));
#if wxUSE_STATUSBAR
std::vector<wxExPane> panes;
panes.push_back(wxExPane("PaneText", -3));
panes.push_back(wxExPane("PaneFileType", 50, _("File Type")));
panes.push_back(wxExPane("PaneLines", 100, _("Lines")));
// Add the lexer pane only if we have lexers.
wxExLexers* lexers = wxExLexers::Get();
if (lexers->Count() > 0)
{
#ifdef __WXMSW__
const int lexer_size = 60;
#else
const int lexer_size = 75;
#endif
panes.push_back(wxExPane("PaneLexer", lexer_size, _("Lexer")));
}
panes.push_back(wxExPane("PaneItems", 65, _("Items")));
SetupStatusBar(panes);
#endif
wxMenuBar* menubar = new wxMenuBar(wxMB_DOCKABLE); // wxMB_DOCKABLE only used for GTK
SetMenuBar(menubar);
wxExMenu *menuFile = new wxExMenu();
menuFile->Append(wxID_NEW);
menuFile->Append(wxID_OPEN);
UseFileHistory(ID_RECENT_FILE_MENU, menuFile);
menuFile->Append(ID_OPEN_LEXERS, _("Open &Lexers"));
menuFile->Append(ID_OPEN_LOGFILE, _("Open &Logfile"));
menuFile->Append(wxID_CLOSE);
menuFile->Append(ID_ALL_STC_CLOSE, _("Close A&ll"));
menuFile->AppendSeparator();
menuFile->Append(wxID_SAVE);
menuFile->Append(wxID_SAVEAS);
menuFile->Append(ID_ALL_STC_SAVE, _("Save A&ll"), wxEmptyString, wxART_FILE_SAVE);
menuFile->AppendSeparator();
menuFile->AppendPrint();
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
wxExMenu *menuEdit = new wxExMenu();
menuEdit->Append(wxID_UNDO);
menuEdit->Append(wxID_REDO);
menuEdit->AppendSeparator();
menuEdit->Append(wxID_CUT);
menuEdit->Append(wxID_COPY);
menuEdit->Append(wxID_PASTE);
menuEdit->AppendSeparator();
menuEdit->Append(wxID_FIND);
menuEdit->Append(ID_EDIT_FIND_NEXT, _("Find &Next\tF3"));
menuEdit->Append(wxID_REPLACE);
menuEdit->Append(ID_FIND_IN_FILES, wxExEllipsed(_("Find &In Files")));
menuEdit->Append(ID_REPLACE_IN_FILES, wxExEllipsed(_("Replace In File&s")));
menuEdit->AppendSeparator();
menuEdit->AppendTools();
menuEdit->AppendSeparator();
menuEdit->Append(wxID_JUMP_TO);
menuEdit->AppendSeparator();
menuEdit->Append(ID_EDIT_CONTROL_CHAR, wxExEllipsed(_("&Control Char"), "Ctrl-H"));
menuEdit->AppendSeparator();
m_MenuVCS = new wxExMenu;
menuEdit->AppendSubMenu(m_MenuVCS, "&VCS");
menuEdit->AppendSeparator();
if (wxExVCS::Get()->Use())
{
BuildVCSMenu(true);
}
menuEdit->Append(ID_EDIT_MACRO_START_RECORD, _("Start Record"));
menuEdit->Append(ID_EDIT_MACRO_STOP_RECORD, _("Stop Record"));
menuEdit->Append(ID_EDIT_MACRO_PLAYBACK, _("Playback\tCtrl-M"));
wxMenu *menuView = new wxMenu;
menuView->AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar"));
menuView->AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar"));
menuView->AppendCheckItem(ID_VIEW_MENUBAR, _("&Menubar"));
menuView->AppendCheckItem(ID_VIEW_FINDBAR, _("&Findbar"));
menuView->AppendSeparator();
menuView->AppendCheckItem(ID_VIEW_FILES, _("&Files"));
menuView->AppendCheckItem(ID_VIEW_PROJECTS, _("&Projects"));
menuView->AppendCheckItem(ID_VIEW_DIRCTRL, _("&Explorer"));
menuView->AppendCheckItem(ID_VIEW_HISTORY, _("&History"));
menuView->AppendCheckItem(ID_VIEW_OUTPUT, _("&Output"));
menuView->AppendSeparator();
menuView->AppendCheckItem(ID_VIEW_ASCII_TABLE, _("&Ascii Table"));
wxMenu *menuProcess = new wxMenu();
menuProcess->Append(ID_PROCESS_SELECT, wxExEllipsed(_("&Select")));
menuProcess->AppendSeparator();
menuProcess->Append(wxID_EXECUTE);
menuProcess->Append(wxID_STOP);
wxExMenu *menuProject = new wxExMenu();
menuProject->Append(ID_PROJECT_NEW, wxGetStockLabel(wxID_NEW), wxEmptyString, wxART_NEW);
menuProject->Append(ID_PROJECT_OPEN, wxGetStockLabel(wxID_OPEN), wxEmptyString, wxART_FILE_OPEN);
UseProjectHistory(ID_RECENT_PROJECT_MENU, menuProject);
menuProject->Append(ID_PROJECT_OPENTEXT, _("&Open As Text"));
menuProject->Append(ID_PROJECT_CLOSE, wxGetStockLabel(wxID_CLOSE), wxEmptyString, wxART_CLOSE);
menuProject->AppendSeparator();
menuProject->Append(ID_PROJECT_SAVE, wxGetStockLabel(wxID_SAVE), wxEmptyString, wxART_FILE_SAVE);
menuProject->Append(ID_PROJECT_SAVEAS, wxGetStockLabel(wxID_SAVEAS), wxEmptyString, wxART_FILE_SAVE_AS);
menuProject->AppendSeparator();
menuProject->AppendCheckItem(ID_SORT_SYNC, _("&Auto Sort"));
wxMenu *menuWindow = new wxMenu();
menuWindow->Append(ID_SPLIT, _("Split"));
wxMenu* menuOptions = new wxMenu();
menuOptions->Append(ID_OPTION_VCS_AND_COMPARATOR, wxExEllipsed(_("Set VCS And &Comparator")));
menuOptions->AppendSeparator();
menuOptions->Append(ID_OPTION_LIST_FONT, wxExEllipsed(_("Set &List Font")));
// text also used as caption
menuOptions->Append(ID_OPTION_LIST_READONLY_COLOUR, wxExEllipsed(_("Set List Read Only Colour")));
wxMenu *menuListSort = new wxMenu;
menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_ASCENDING, _("&Ascending"));
menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_DESCENDING, _("&Descending"));
menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_TOGGLE, _("&Toggle"));
menuOptions->AppendSubMenu(menuListSort, _("Set &List Sort Method"));
menuOptions->AppendSeparator();
menuOptions->Append(ID_OPTION_EDITOR, wxExEllipsed(_("Set &Editor Options")));
wxMenu *menuHelp = new wxMenu();
menuHelp->Append(wxID_ABOUT);
menubar->Append(menuFile, wxGetStockLabel(wxID_FILE));
menubar->Append(menuEdit, wxGetStockLabel(wxID_EDIT));
menubar->Append(menuView, _("&View"));
menubar->Append(menuProcess, _("&Process"));
menubar->Append(menuProject, _("&Project"));
menubar->Append(menuWindow, _("&Window"));
menubar->Append(menuOptions, _("&Options"));
menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));
CreateToolBar();
m_ToolBar->AddTool(wxID_OPEN);
m_ToolBar->AddTool(wxID_SAVE);
m_ToolBar->AddTool(wxID_PRINT);
m_ToolBar->AddSeparator();
m_ToolBar->AddTool(wxID_FIND);
#ifdef __WXGTK__
// wxID_EXECUTE is not part of art provider, but GTK directly,
// so the following does not present a bitmap.
//m_ToolBar->AddSeparator();
//m_ToolBar->AddTool(wxID_EXECUTE);
#endif
m_ToolBar->AddSeparator();
((wxToolBar*)m_ToolBar)->AddTool(
ID_PROJECT_OPEN,
wxEmptyString,
wxArtProvider::GetBitmap(wxART_FILE_OPEN, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
wxExEllipsed(_("Open project")));
((wxToolBar*)m_ToolBar)->AddTool(
ID_PROJECT_SAVE,
wxEmptyString,
wxArtProvider::GetBitmap(wxART_FILE_SAVE, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
_("Save project"));
#if wxUSE_CHECKBOX
m_ToolBar->AddSeparator();
m_ToolBar->AddControl(
m_HexModeCheckBox = new wxCheckBox(
m_ToolBar,
ID_EDIT_HEX_MODE,
"Hex",
wxDefaultPosition,
wxSize(-1, m_ToolBar->GetToolSize().GetHeight())));
m_ToolBar->AddControl(
m_SyncCheckBox = new wxCheckBox(
m_ToolBar,
ID_SYNC_MODE,
"Sync",
wxDefaultPosition,
wxSize(-1, m_ToolBar->GetToolSize().GetHeight())));
#if wxUSE_TOOLTIPS
m_HexModeCheckBox->SetToolTip(_("View in hex mode"));
#endif
m_HexModeCheckBox->SetValue(wxConfigBase::Get()->ReadBool("HexMode", false)); // default no hex
#if wxUSE_TOOLTIPS
m_SyncCheckBox->SetToolTip(_("Synchronize modified files"));
#endif
m_SyncCheckBox->SetValue(wxConfigBase::Get()->ReadBool("AllowSync", true));
#endif // wxUSE_CHECKBOX
m_ToolBar->Realize();
}
bool Frame::AllowClose(wxWindowID id, wxWindow* page)
{
if (wxExProcess::Get()->IsRunning())
{
return false;
}
else if (id == NOTEBOOK_EDITORS)
{
wxExFileDialog dlg(this, (wxExSTCWithFrame*)page);
return dlg.ShowModalIfChanged() == wxID_OK;
}
else if (id == NOTEBOOK_PROJECTS)
{
wxExFileDialog dlg(this, (wxExListViewFile*)page);
return dlg.ShowModalIfChanged() == wxID_OK;
}
else
{
return wxExFrameWithHistory::AllowClose(id, page);
}
}
void Frame::BuildVCSMenu(bool fill)
{
if (m_MenuVCSFilled)
{
wxMenuItem* item;
while ((item = m_MenuVCS->FindItem(wxID_SEPARATOR)) != NULL)
{
m_MenuVCS->Destroy(item);
}
m_MenuVCS->Destroy(ID_VCS_STAT);
m_MenuVCS->Destroy(ID_VCS_INFO);
m_MenuVCS->Destroy(ID_VCS_LOG);
m_MenuVCS->Destroy(ID_VCS_LS);
m_MenuVCS->Destroy(ID_VCS_DIFF);
m_MenuVCS->Destroy(ID_VCS_HELP);
m_MenuVCS->Destroy(ID_VCS_UPDATE);
m_MenuVCS->Destroy(ID_VCS_COMMIT);
m_MenuVCS->Destroy(ID_VCS_ADD);
}
if (fill)
{
m_MenuVCS->AppendVCS(ID_VCS_STAT);
m_MenuVCS->AppendVCS(ID_VCS_INFO);
m_MenuVCS->AppendVCS(ID_VCS_LOG);
m_MenuVCS->AppendVCS(ID_VCS_LS);
m_MenuVCS->AppendVCS(ID_VCS_DIFF);
m_MenuVCS->AppendVCS(ID_VCS_HELP);
m_MenuVCS->AppendSeparator();
m_MenuVCS->AppendVCS(ID_VCS_UPDATE);
m_MenuVCS->AppendVCS(ID_VCS_COMMIT);
m_MenuVCS->AppendSeparator();
m_MenuVCS->AppendVCS(ID_VCS_ADD);
}
m_MenuVCSFilled = fill;
}
void Frame::OnNotebook(wxWindowID id, wxWindow* page)
{
if (id == NOTEBOOK_EDITORS)
{
((wxExSTCWithFrame*)page)->PropertiesMessage();
}
else if (id == NOTEBOOK_PROJECTS)
{
SetTitle(wxEmptyString, ((wxExListViewFile*)page)->GetFileName().GetName());
#if wxUSE_STATUSBAR
StatusText(((wxExListViewFile*)page)->GetFileName());
((wxExListViewFile*)page)->UpdateStatusBar();
#endif
}
else if (id == NOTEBOOK_LISTS)
{
// Do nothing special.
}
else
{
wxFAIL;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: WW8ResourceModel.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 INCLUDED_WW8_EVENT_HANDLER_HXX
#define INCLUDED_WW8_EVENT_HANDLER_HXX
#include <string>
#include <memory>
#include <boost/shared_ptr.hpp>
#include <sal/types.h>
#include <com/sun/star/uno/Any.hxx>
#include <WriterFilterDllApi.hxx>
#include <resourcemodel/OutputWithDepth.hxx>
/**
@file WW8ResourceModel.hxx
The classes in this file define the interfaces for the resource
model of the DocTokenizer:
@image html doctok.png
A resource is a set of events that describe an object. A resource
is only an abstract concept. It is not instanciated to a class.
A reference to a resource represents the object that the resource
describes. The reference can be resolved thereby generating the
events of the resource.
A handler receives the events generated by resolving a
reference. There are several types of handlers each accepting their
specific set of events.
References always have a parameter determining the kind of handler
they send the events they generate to. The set of events generated
by resolving the reference is a subset of the events received by
the handler.
*/
typedef sal_uInt32 Id;
namespace writerfilter {
using namespace ::com::sun::star;
using namespace ::std;
/**
Reference to an resource that generates events and sends them to a
handler.
The reference can be resolved, i.e. the resource generates its
events. The events must be suitable for the handler type given by
the template parameter.
@attention The parameter of the template does not determine the
type of the reference's target. It determines the type of the handler!
Example:
A Word document can be represented as a stream of events. Event
types in a Word document are text, properties, tables, starts and
ends of groups. These can be handled by a stream handler (@see
Stream). Thus a reference to a Word document is resolved by
sending these events to a stream handler.
*/
template <class T>
class WRITERFILTER_DLLPUBLIC Reference
{
public:
/**
Pointer to reference
@attention The ownership of a reference is transfered when
the reference is passed.
*/
typedef boost::shared_ptr< Reference<T> > Pointer_t;
virtual ~Reference() {}
/**
Resolves the reference.
The events of the references target resource are generated and
send to a handler.
@param rHandler handler which receives the events
*/
virtual void resolve(T & rHandler) = 0;
/**
Returns the type of the reference aka the name of the access class.
*/
virtual string getType() const = 0;
};
class Value;
class Sprm;
/**
Handler for properties.
*/
class WRITERFILTER_DLLPUBLIC Properties
{
public:
/**
Receives an attribute.
@param name name of the attribute
@param val value of the attribute
*/
virtual void attribute(Id name, Value & val) = 0;
/**
Receives a SPRM.
@param sprm the SPRM received
*/
virtual void sprm(Sprm & sprm) = 0;
};
/**
Handler for tables.
*/
class WRITERFILTER_DLLPUBLIC Table
{
public:
/**
Receives an entry of the table.
@param pos position of the entry in the table
@param ref reference to properties of the entry
*/
virtual void entry(int pos, writerfilter::Reference<Properties>::Pointer_t ref) = 0;
};
/**
Handler for binary objects.
*/
class WRITERFILTER_DLLPUBLIC BinaryObj
{
public:
/**
Receives binary data of the object.
@param buf pointer to buffer containing the data
@param len size of buffer
@param ref reference to properties of binary object
*/
virtual void data(const sal_uInt8* buf, size_t len,
writerfilter::Reference<Properties>::Pointer_t ref) = 0;
};
/**
Handler for a stream.
*/
class WRITERFILTER_DLLPUBLIC Stream
{
public:
/**
Pointer to this stream.
*/
typedef boost::shared_ptr<Stream> Pointer_t;
/**
Receives start mark for group with the same section properties.
*/
virtual void startSectionGroup() = 0;
/**
Receives end mark for group with the same section properties.
*/
virtual void endSectionGroup() = 0;
/**
Receives start mark for group with the same paragraph properties.
*/
virtual void startParagraphGroup() = 0;
/**
Receives end mark for group with the same paragraph properties.
*/
virtual void endParagraphGroup() = 0;
/**
Receives start mark for group with the same character properties.
*/
virtual void startCharacterGroup() = 0;
/**
Receives end mark for group with the same character properties.
*/
virtual void endCharacterGroup() = 0;
/**
Receives 8-bit per character text.
@param data buffer containing the text
@param len number of characters in the text
*/
virtual void text(const sal_uInt8 * data, size_t len) = 0;
/**
Receives 16-bit per character text.
@param data buffer containing the text
@param len number of characters in the text.
*/
virtual void utext(const sal_uInt8 * data, size_t len) = 0;
/**
Receives properties of the current run of text.
@param ref reference to the properties
*/
virtual void props(writerfilter::Reference<Properties>::Pointer_t ref) = 0;
/**
Receives table.
@param name name of the table
@param ref referecne to the table
*/
virtual void table(Id name,
writerfilter::Reference<Table>::Pointer_t ref) = 0;
/**
Receives a substream.
@param name name of the substream
@param ref reference to the substream
*/
virtual void substream(Id name,
writerfilter::Reference<Stream>::Pointer_t ref) = 0;
/**
Debugging: Receives information about current point in stream.
@param info the information
*/
virtual void info(const string & info) = 0;
};
/**
A value.
The methods of this class may throw exceptions if a certain aspect
makes no sense for a certain value, e.g. the integer value of a
string.
*/
class WRITERFILTER_DLLPUBLIC Value
{
public:
/**
Pointer to a value.
*/
typedef auto_ptr<Value> Pointer_t;
/**
Returns integer representation of the value.
*/
virtual int getInt() const = 0;
/**
Returns string representation of the value.
*/
virtual ::rtl::OUString getString() const = 0;
/**
Returns representation of the value as uno::Any.
*/
virtual uno::Any getAny() const = 0;
/**
Returns properties of this value.
*/
virtual writerfilter::Reference<Properties>::Pointer_t getProperties() = 0;
/**
Returns stream of this value.
*/
virtual writerfilter::Reference<Stream>::Pointer_t getStream() = 0;
/**
Returns binary object of this value.
*/
virtual writerfilter::Reference<BinaryObj>::Pointer_t getBinary() = 0;
/**
Returns string representation of this value.
*/
virtual string toString() const = 0;
};
/**
An SPRM.
*/
class WRITERFILTER_DLLPUBLIC Sprm
{
public:
typedef auto_ptr<Sprm> Pointer_t;
enum Kind { UNKNOWN, CHARACTER, PARAGRAPH, TABLE };
/**
Returns id of the SPRM.
*/
virtual sal_uInt32 getId() const = 0;
/**
Returns value of the SPRM.
*/
virtual Value::Pointer_t getValue() = 0;
/**
Returns reference to binary object contained in the SPRM.
*/
virtual writerfilter::Reference<BinaryObj>::Pointer_t getBinary() = 0;
/**
Returns reference to stream associated with the SPRM.
*/
virtual writerfilter::Reference<Stream>::Pointer_t getStream() = 0;
/**
Returns reference to properties contained in the SPRM.
*/
virtual writerfilter::Reference<Properties>::Pointer_t getProps() = 0;
/**
Returns the kind of this SPRM.
*/
virtual Kind getKind() = 0;
/**
Returns name of sprm.
*/
virtual string getName() const = 0;
/**
Returns string repesentation of sprm.
*/
virtual string toString() const = 0;
};
/**
Creates handler for a stream.
*/
Stream::Pointer_t WRITERFILTER_DLLPUBLIC createStreamHandler();
void WRITERFILTER_DLLPUBLIC analyzerIds();
Stream::Pointer_t WRITERFILTER_DLLPUBLIC createAnalyzer();
void WRITERFILTER_DLLPUBLIC logger(string prefix, string message);
void WRITERFILTER_DLLPUBLIC dump(OutputWithDepth<string> & o, const char * name, writerfilter::Reference<Properties>::Pointer_t props);
void WRITERFILTER_DLLPUBLIC dump(OutputWithDepth<string> & o, const char * name, sal_uInt32 n);
void WRITERFILTER_DLLPUBLIC dump(OutputWithDepth<string> & /*o*/, const char * /*name*/,
const rtl::OUString & /*str*/);
void WRITERFILTER_DLLPUBLIC dump(OutputWithDepth<string> & o, const char * name, writerfilter::Reference<BinaryObj>::Pointer_t binary);
}
#endif // INCLUDED_WW8_EVENT_HANDLER_HXX
<commit_msg>INTEGRATION: CWS xmlfilter06 (1.3.8); FILE MERGED 2008/05/30 12:10:37 hbrinkm 1.3.8.1: cleanups<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: WW8ResourceModel.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 INCLUDED_WW8_EVENT_HANDLER_HXX
#define INCLUDED_WW8_EVENT_HANDLER_HXX
#include <string>
#include <memory>
#include <boost/shared_ptr.hpp>
#include <sal/types.h>
#include <com/sun/star/uno/Any.hxx>
#include <WriterFilterDllApi.hxx>
#include <resourcemodel/OutputWithDepth.hxx>
/**
@file WW8ResourceModel.hxx
The classes in this file define the interfaces for the resource
model of the DocTokenizer:
@image html doctok.png
A resource is a set of events that describe an object. A resource
is only an abstract concept. It is not instanciated to a class.
A reference to a resource represents the object that the resource
describes. The reference can be resolved thereby generating the
events of the resource.
A handler receives the events generated by resolving a
reference. There are several types of handlers each accepting their
specific set of events.
References always have a parameter determining the kind of handler
they send the events they generate to. The set of events generated
by resolving the reference is a subset of the events received by
the handler.
*/
typedef sal_uInt32 Id;
namespace writerfilter {
using namespace ::com::sun::star;
using namespace ::std;
/**
Reference to an resource that generates events and sends them to a
handler.
The reference can be resolved, i.e. the resource generates its
events. The events must be suitable for the handler type given by
the template parameter.
@attention The parameter of the template does not determine the
type of the reference's target. It determines the type of the handler!
Example:
A Word document can be represented as a stream of events. Event
types in a Word document are text, properties, tables, starts and
ends of groups. These can be handled by a stream handler (@see
Stream). Thus a reference to a Word document is resolved by
sending these events to a stream handler.
*/
template <class T>
class WRITERFILTER_DLLPUBLIC Reference
{
public:
/**
Pointer to reference
@attention The ownership of a reference is transfered when
the reference is passed.
*/
typedef boost::shared_ptr< Reference<T> > Pointer_t;
virtual ~Reference() {}
/**
Resolves the reference.
The events of the references target resource are generated and
send to a handler.
@param rHandler handler which receives the events
*/
virtual void resolve(T & rHandler) = 0;
/**
Returns the type of the reference aka the name of the access class.
*/
virtual string getType() const = 0;
};
class Value;
class Sprm;
/**
Handler for properties.
*/
class WRITERFILTER_DLLPUBLIC Properties
{
public:
/**
Receives an attribute.
@param name name of the attribute
@param val value of the attribute
*/
virtual void attribute(Id name, Value & val) = 0;
/**
Receives a SPRM.
@param sprm the SPRM received
*/
virtual void sprm(Sprm & sprm) = 0;
};
/**
Handler for tables.
*/
class WRITERFILTER_DLLPUBLIC Table
{
public:
/**
Receives an entry of the table.
@param pos position of the entry in the table
@param ref reference to properties of the entry
*/
virtual void entry(int pos, writerfilter::Reference<Properties>::Pointer_t ref) = 0;
};
/**
Handler for binary objects.
*/
class WRITERFILTER_DLLPUBLIC BinaryObj
{
public:
/**
Receives binary data of the object.
@param buf pointer to buffer containing the data
@param len size of buffer
@param ref reference to properties of binary object
*/
virtual void data(const sal_uInt8* buf, size_t len,
writerfilter::Reference<Properties>::Pointer_t ref) = 0;
};
/**
Handler for a stream.
*/
class WRITERFILTER_DLLPUBLIC Stream
{
public:
/**
Pointer to this stream.
*/
typedef boost::shared_ptr<Stream> Pointer_t;
/**
Receives start mark for group with the same section properties.
*/
virtual void startSectionGroup() = 0;
/**
Receives end mark for group with the same section properties.
*/
virtual void endSectionGroup() = 0;
/**
Receives start mark for group with the same paragraph properties.
*/
virtual void startParagraphGroup() = 0;
/**
Receives end mark for group with the same paragraph properties.
*/
virtual void endParagraphGroup() = 0;
/**
Receives start mark for group with the same character properties.
*/
virtual void startCharacterGroup() = 0;
/**
Receives end mark for group with the same character properties.
*/
virtual void endCharacterGroup() = 0;
/**
Receives 8-bit per character text.
@param data buffer containing the text
@param len number of characters in the text
*/
virtual void text(const sal_uInt8 * data, size_t len) = 0;
/**
Receives 16-bit per character text.
@param data buffer containing the text
@param len number of characters in the text.
*/
virtual void utext(const sal_uInt8 * data, size_t len) = 0;
/**
Receives properties of the current run of text.
@param ref reference to the properties
*/
virtual void props(writerfilter::Reference<Properties>::Pointer_t ref) = 0;
/**
Receives table.
@param name name of the table
@param ref referecne to the table
*/
virtual void table(Id name,
writerfilter::Reference<Table>::Pointer_t ref) = 0;
/**
Receives a substream.
@param name name of the substream
@param ref reference to the substream
*/
virtual void substream(Id name,
writerfilter::Reference<Stream>::Pointer_t ref) = 0;
/**
Debugging: Receives information about current point in stream.
@param info the information
*/
virtual void info(const string & info) = 0;
};
/**
A value.
The methods of this class may throw exceptions if a certain aspect
makes no sense for a certain value, e.g. the integer value of a
string.
*/
class WRITERFILTER_DLLPUBLIC Value
{
public:
/**
Pointer to a value.
*/
typedef auto_ptr<Value> Pointer_t;
/**
Returns integer representation of the value.
*/
virtual int getInt() const = 0;
/**
Returns string representation of the value.
*/
virtual ::rtl::OUString getString() const = 0;
/**
Returns representation of the value as uno::Any.
*/
virtual uno::Any getAny() const = 0;
/**
Returns properties of this value.
*/
virtual writerfilter::Reference<Properties>::Pointer_t getProperties() = 0;
/**
Returns stream of this value.
*/
virtual writerfilter::Reference<Stream>::Pointer_t getStream() = 0;
/**
Returns binary object of this value.
*/
virtual writerfilter::Reference<BinaryObj>::Pointer_t getBinary() = 0;
/**
Returns string representation of this value.
*/
virtual string toString() const = 0;
};
/**
An SPRM.
*/
class WRITERFILTER_DLLPUBLIC Sprm
{
public:
typedef auto_ptr<Sprm> Pointer_t;
enum Kind { UNKNOWN, CHARACTER, PARAGRAPH, TABLE };
/**
Returns id of the SPRM.
*/
virtual sal_uInt32 getId() const = 0;
/**
Returns value of the SPRM.
*/
virtual Value::Pointer_t getValue() = 0;
/**
Returns reference to binary object contained in the SPRM.
*/
virtual writerfilter::Reference<BinaryObj>::Pointer_t getBinary() = 0;
/**
Returns reference to stream associated with the SPRM.
*/
virtual writerfilter::Reference<Stream>::Pointer_t getStream() = 0;
/**
Returns reference to properties contained in the SPRM.
*/
virtual writerfilter::Reference<Properties>::Pointer_t getProps() = 0;
/**
Returns the kind of this SPRM.
*/
virtual Kind getKind() = 0;
/**
Returns name of sprm.
*/
virtual string getName() const = 0;
/**
Returns string repesentation of sprm.
*/
virtual string toString() const = 0;
};
/**
Creates handler for a stream.
*/
Stream::Pointer_t WRITERFILTER_DLLPUBLIC createStreamHandler();
void WRITERFILTER_DLLPUBLIC analyzerIds();
Stream::Pointer_t WRITERFILTER_DLLPUBLIC createAnalyzer();
void WRITERFILTER_DLLPUBLIC logger(string prefix, string message);
void WRITERFILTER_DLLPUBLIC dump(OutputWithDepth<string> & o, const char * name, writerfilter::Reference<Properties>::Pointer_t props);
void WRITERFILTER_DLLPUBLIC dump(OutputWithDepth<string> & o, const char * name, sal_uInt32 n);
void WRITERFILTER_DLLPUBLIC dump(OutputWithDepth<string> & /*o*/, const char * /*name*/,
const rtl::OUString & /*str*/);
void WRITERFILTER_DLLPUBLIC dump(OutputWithDepth<string> & o, const char * name, writerfilter::Reference<BinaryObj>::Pointer_t binary);
}
#endif // INCLUDED_WW8_EVENT_HANDLER_HXX
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2017 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 "default.h"
#include "distribution2d.h"
#include "../common/scenegraph/scenegraph.h"
#include "../common/image/image.h"
namespace embree
{
/* name of the tutorial */
bool embedTextures = true;
float centerScale = 0.0f;
Vec3fa centerTranslate(0.0f,0.0f,0.0f);
struct HeightField : public RefCount
{
ALIGNED_STRUCT;
HeightField (Ref<Image> texture, const BBox3fa& bounds)
: texture(texture), bounds(bounds) {}
const Vec3fa at(const size_t x, const size_t y)
{
const size_t width = texture->width;
const size_t height = texture->height;
const Color4 c = texture->get(x,y);
const Vec2f p(x/float(width-1),y/float(height-1));
const float px = p.x*(bounds.upper.x-bounds.lower.x) + bounds.lower.x;
const float py = c.r*(bounds.upper.y-bounds.lower.y) + bounds.lower.y;
const float pz = p.y*(bounds.upper.z-bounds.lower.z) + bounds.lower.z;
return Vec3fa(px,py,pz);
}
const AffineSpace3fa get(Vec2f p)
{
const size_t width = texture->width;
const size_t height = texture->height;
const size_t x = clamp((size_t)(p.x*(width-1)),(size_t)0,width-1);
const size_t y = clamp((size_t)(p.y*(height-1)),(size_t)0,height-1);
const Color4 c = texture->get(x,y);
const float px = p.x*(bounds.upper.x-bounds.lower.x) + bounds.lower.x;
const float py = c.r*(bounds.upper.y-bounds.lower.y) + bounds.lower.y;
const float pz = p.y*(bounds.upper.z-bounds.lower.z) + bounds.lower.z;
return AffineSpace3fa::translate(Vec3fa(px,py,pz));
}
Ref<SceneGraph::Node> geometry()
{
OBJMaterial material(1.0f,Vec3fa(1.0f),Vec3fa(0.0f),1.0f);
Ref<SceneGraph::MaterialNode> mnode = new SceneGraph::MaterialNode((Material&)material);
Ref<SceneGraph::TriangleMeshNode> mesh = new SceneGraph::TriangleMeshNode(mnode,1);
const size_t width = texture->width;
const size_t height = texture->height;
mesh->positions[0].resize(height*width);
for (size_t y=0; y<height; y++)
for (size_t x=0; x<width; x++)
mesh->positions[0][y*width+x] = at(x,y);
mesh->triangles.resize(2*(height-1)*(width-1));
for (size_t y=0; y<height-1; y++) {
for (size_t x=0; x<width-1; x++) {
const size_t p00 = (y+0)*width+(x+0);
const size_t p01 = (y+0)*width+(x+1);
const size_t p10 = (y+1)*width+(x+0);
const size_t p11 = (y+1)*width+(x+1);
const size_t tri = y*(width-1)+x;
mesh->triangles[2*tri+0] = SceneGraph::TriangleMeshNode::Triangle(unsigned(p00),unsigned(p01),unsigned(p10));
mesh->triangles[2*tri+1] = SceneGraph::TriangleMeshNode::Triangle(unsigned(p01),unsigned(p11),unsigned(p10));
}
}
return mesh.dynamicCast<SceneGraph::Node>();
}
private:
Ref<Image> texture;
BBox3fa bounds;
};
struct Instantiator : public RefCount
{
Instantiator(const Ref<HeightField>& heightField,
const Ref<SceneGraph::Node>& object, const Ref<Image>& distribution, float minDistance, size_t N)
: heightField(heightField), object(object), /*minDistance(minDistance),*/ N(N)
{
/* create distribution */
size_t width = distribution->width;
size_t height = distribution->height;
float* values = new float[width*height];
for (size_t y=0; y<height; y++)
for (size_t x=0; x<width; x++)
values[y*width+x] = luminance(distribution->get(x,y));
dist = std::make_shared<Distribution2D>(values,width,height);
delete[] values;
}
void instantiate(Ref<SceneGraph::GroupNode>& group)
{
for (size_t i=0; i<N; i++)
{
Vec2f r = Vec2f(random<float>(),random<float>());
Vec2f p = dist->sample(r);
p.x *= rcp(float(dist->width)); p.y *= rcp(float(dist->height));
float angle = 2.0f*float(pi)*random<float>();
const AffineSpace3fa space = heightField->get(p)*AffineSpace3fa::rotate(Vec3fa(0,1,0),angle);
group->add(new SceneGraph::TransformNode(space,object));
}
}
private:
Ref<HeightField> heightField;
Ref<SceneGraph::Node> object;
std::shared_ptr<Distribution2D> dist;
//float MAYBE_UNUSED minDistance;
size_t N;
};
/* scene */
Ref<SceneGraph::GroupNode> g_scene = new SceneGraph::GroupNode;
Ref<HeightField> g_height_field = nullptr;
static void parseCommandLine(Ref<ParseStream> cin, const FileName& path)
{
while (true)
{
std::string tag = cin->getString();
if (tag == "") return;
/* parse command line parameters from a file */
else if (tag == "-c") {
FileName file = path + cin->getFileName();
parseCommandLine(new ParseStream(new LineCommentFilter(file, "#")), file.path());
}
/* load model */
else if (tag == "-i") {
Ref<SceneGraph::Node> object = SceneGraph::load(path + cin->getFileName());
if (centerScale != 0.0f)
{
BBox3fa bb = object->bounds();
Vec3fa center = bb.center();
const AffineSpace3fa space = AffineSpace3fa::translate(centerTranslate)*AffineSpace3fa::scale(Vec3fa(centerScale))*AffineSpace3fa::translate(-center);
g_scene->add(new SceneGraph::TransformNode(space,object));
}
else
g_scene->add(object);
}
/* convert triangles to quads */
else if (tag == "-convert-triangles-to-quads") {
g_scene->triangles_to_quads();
}
/* convert to subdivs */
else if (tag == "-convert-to-subdivs") {
g_scene->triangles_to_quads();
g_scene->quads_to_subdivs();
}
/* convert bezier to lines */
else if (tag == "-convert-bezier-to-lines") {
g_scene->bezier_to_lines();
}
/* load terrain */
else if (tag == "-terrain")
{
Ref<Image> tex = loadImage(path + cin->getFileName());
const Vec3fa lower = cin->getVec3fa();
const Vec3fa upper = cin->getVec3fa();
g_height_field = new HeightField(tex,BBox3fa(lower,upper));
g_scene->add(g_height_field->geometry());
}
/* distribute model */
else if (tag == "-distribute") {
Ref<SceneGraph::Node> object = SceneGraph::load(path + cin->getFileName());
Ref<Image> distribution = loadImage(path + cin->getFileName());
const float minDistance = cin->getFloat();
const size_t N = cin->getInt();
Ref<Instantiator> instantiator = new Instantiator(g_height_field,object,distribution,minDistance,N);
instantiator->instantiate(g_scene);
}
/* instantiate model a single time */
else if (tag == "-instantiate") {
Ref<SceneGraph::Node> object = SceneGraph::load(path + cin->getFileName());
const float px = cin->getFloat();
const float py = cin->getFloat();
const Vec2f p(px,py);
const float angle = cin->getFloat()/180.0f*float(pi);
const AffineSpace3fa space = g_height_field->get(p)*AffineSpace3fa::rotate(Vec3fa(0,1,0),angle);
g_scene->add(new SceneGraph::TransformNode(space,object));
}
/* enable texture embedding */
else if (tag == "-embed-textures") {
embedTextures = true;
}
/* enable texture referencing */
else if (tag == "-reference-textures") {
embedTextures = false;
}
else if (tag == "-centerScaleTranslate") {
centerScale = cin->getFloat();
centerTranslate.x = cin->getFloat();
centerTranslate.y = cin->getFloat();
centerTranslate.z = cin->getFloat();
}
/* output filename */
else if (tag == "-o") {
SceneGraph::store(g_scene.dynamicCast<SceneGraph::Node>(),path + cin->getFileName(),embedTextures);
}
/* skip unknown command line parameter */
else {
std::cerr << "unknown command line parameter: " << tag << " ";
while (cin->peek() != "" && cin->peek()[0] != '-') std::cerr << cin->getString() << " ";
std::cerr << std::endl;
}
}
}
/* main function in embree namespace */
int main(int argc, char** argv)
{
/* create stream for parsing */
Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv));
/* parse command line */
parseCommandLine(stream, FileName());
return 0;
}
}
int main(int argc, char** argv)
{
try {
return embree::main(argc, argv);
}
catch (const std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
return 1;
}
catch (...) {
std::cout << "Error: unknown exception caught." << std::endl;
return 1;
}
}
<commit_msg>added code to generate msmblur barbarian scene<commit_after>// ======================================================================== //
// Copyright 2009-2017 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 "default.h"
#include "distribution2d.h"
#include "../common/scenegraph/scenegraph.h"
#include "../common/image/image.h"
namespace embree
{
/* name of the tutorial */
bool embedTextures = true;
float centerScale = 0.0f;
Vec3fa centerTranslate(0.0f,0.0f,0.0f);
struct HeightField : public RefCount
{
ALIGNED_STRUCT;
HeightField (Ref<Image> texture, const BBox3fa& bounds)
: texture(texture), bounds(bounds) {}
const Vec3fa at(const size_t x, const size_t y)
{
const size_t width = texture->width;
const size_t height = texture->height;
const Color4 c = texture->get(x,y);
const Vec2f p(x/float(width-1),y/float(height-1));
const float px = p.x*(bounds.upper.x-bounds.lower.x) + bounds.lower.x;
const float py = c.r*(bounds.upper.y-bounds.lower.y) + bounds.lower.y;
const float pz = p.y*(bounds.upper.z-bounds.lower.z) + bounds.lower.z;
return Vec3fa(px,py,pz);
}
const AffineSpace3fa get(Vec2f p)
{
const size_t width = texture->width;
const size_t height = texture->height;
const size_t x = clamp((size_t)(p.x*(width-1)),(size_t)0,width-1);
const size_t y = clamp((size_t)(p.y*(height-1)),(size_t)0,height-1);
const Color4 c = texture->get(x,y);
const float px = p.x*(bounds.upper.x-bounds.lower.x) + bounds.lower.x;
const float py = c.r*(bounds.upper.y-bounds.lower.y) + bounds.lower.y;
const float pz = p.y*(bounds.upper.z-bounds.lower.z) + bounds.lower.z;
return AffineSpace3fa::translate(Vec3fa(px,py,pz));
}
Ref<SceneGraph::Node> geometry()
{
OBJMaterial material(1.0f,Vec3fa(1.0f),Vec3fa(0.0f),1.0f);
Ref<SceneGraph::MaterialNode> mnode = new SceneGraph::MaterialNode((Material&)material);
Ref<SceneGraph::TriangleMeshNode> mesh = new SceneGraph::TriangleMeshNode(mnode,1);
const size_t width = texture->width;
const size_t height = texture->height;
mesh->positions[0].resize(height*width);
for (size_t y=0; y<height; y++)
for (size_t x=0; x<width; x++)
mesh->positions[0][y*width+x] = at(x,y);
mesh->triangles.resize(2*(height-1)*(width-1));
for (size_t y=0; y<height-1; y++) {
for (size_t x=0; x<width-1; x++) {
const size_t p00 = (y+0)*width+(x+0);
const size_t p01 = (y+0)*width+(x+1);
const size_t p10 = (y+1)*width+(x+0);
const size_t p11 = (y+1)*width+(x+1);
const size_t tri = y*(width-1)+x;
mesh->triangles[2*tri+0] = SceneGraph::TriangleMeshNode::Triangle(unsigned(p00),unsigned(p01),unsigned(p10));
mesh->triangles[2*tri+1] = SceneGraph::TriangleMeshNode::Triangle(unsigned(p01),unsigned(p11),unsigned(p10));
}
}
return mesh.dynamicCast<SceneGraph::Node>();
}
private:
Ref<Image> texture;
BBox3fa bounds;
};
struct Instantiator : public RefCount
{
Instantiator(const Ref<HeightField>& heightField,
const Ref<SceneGraph::Node>& object, const Ref<Image>& distribution, float minDistance, size_t N)
: heightField(heightField), object(object), /*minDistance(minDistance),*/ N(N)
{
/* create distribution */
size_t width = distribution->width;
size_t height = distribution->height;
float* values = new float[width*height];
for (size_t y=0; y<height; y++)
for (size_t x=0; x<width; x++)
values[y*width+x] = luminance(distribution->get(x,y));
dist = std::make_shared<Distribution2D>(values,width,height);
delete[] values;
}
void instantiate(Ref<SceneGraph::GroupNode>& group)
{
for (size_t i=0; i<N; i++)
{
Vec2f r = Vec2f(random<float>(),random<float>());
Vec2f p = dist->sample(r);
p.x *= rcp(float(dist->width)); p.y *= rcp(float(dist->height));
float angle = 2.0f*float(pi)*random<float>();
const AffineSpace3fa space = heightField->get(p)*AffineSpace3fa::rotate(Vec3fa(0,1,0),angle);
group->add(new SceneGraph::TransformNode(space,object));
}
}
private:
Ref<HeightField> heightField;
Ref<SceneGraph::Node> object;
std::shared_ptr<Distribution2D> dist;
//float MAYBE_UNUSED minDistance;
size_t N;
};
/* scene */
Ref<SceneGraph::GroupNode> g_scene = new SceneGraph::GroupNode;
Ref<HeightField> g_height_field = nullptr;
static void parseCommandLine(Ref<ParseStream> cin, const FileName& path)
{
while (true)
{
std::string tag = cin->getString();
if (tag == "") return;
/* parse command line parameters from a file */
else if (tag == "-c") {
FileName file = path + cin->getFileName();
parseCommandLine(new ParseStream(new LineCommentFilter(file, "#")), file.path());
}
/* load model */
else if (tag == "-i") {
Ref<SceneGraph::Node> object = SceneGraph::load(path + cin->getFileName());
if (centerScale != 0.0f)
{
BBox3fa bb = object->bounds();
Vec3fa center = bb.center();
const AffineSpace3fa space = AffineSpace3fa::translate(centerTranslate)*AffineSpace3fa::scale(Vec3fa(centerScale))*AffineSpace3fa::translate(-center);
g_scene->add(new SceneGraph::TransformNode(space,object));
}
else
g_scene->add(object);
}
/* used to generate some test scene automatically */
else if (tag == "-special-barbarian-instantiate") {
for (int x=0; x<10; x++) {
for (int y=0; y<10; y++) {
const char* model = "barbarian_mblur.xml";
if (random<int>()%4 == 0) model = "barbarian_msmblur_translate.xml";
else if (random<int>()%32 == 0) model = "barbarian_msmblur_rotate0_5.xml";
else if (random<int>()%32 == 0) model = "barbarian_msmblur.xml";
printf("<Transform><AffineSpace translate=\"%7.2f %7.2f %7.2f\"/><extern src=\"%s\"/></Transform>\n",float(x*400)+200.0f*drand48(),0.0f,float(y*400)+200.0f*drand48(),model);
}
}
}
/* convert triangles to quads */
else if (tag == "-convert-triangles-to-quads") {
g_scene->triangles_to_quads();
}
/* convert to subdivs */
else if (tag == "-convert-to-subdivs") {
g_scene->triangles_to_quads();
g_scene->quads_to_subdivs();
}
/* convert bezier to lines */
else if (tag == "-convert-bezier-to-lines") {
g_scene->bezier_to_lines();
}
/* load terrain */
else if (tag == "-terrain")
{
Ref<Image> tex = loadImage(path + cin->getFileName());
const Vec3fa lower = cin->getVec3fa();
const Vec3fa upper = cin->getVec3fa();
g_height_field = new HeightField(tex,BBox3fa(lower,upper));
g_scene->add(g_height_field->geometry());
}
/* distribute model */
else if (tag == "-distribute") {
Ref<SceneGraph::Node> object = SceneGraph::load(path + cin->getFileName());
Ref<Image> distribution = loadImage(path + cin->getFileName());
const float minDistance = cin->getFloat();
const size_t N = cin->getInt();
Ref<Instantiator> instantiator = new Instantiator(g_height_field,object,distribution,minDistance,N);
instantiator->instantiate(g_scene);
}
/* instantiate model a single time */
else if (tag == "-instantiate") {
Ref<SceneGraph::Node> object = SceneGraph::load(path + cin->getFileName());
const float px = cin->getFloat();
const float py = cin->getFloat();
const Vec2f p(px,py);
const float angle = cin->getFloat()/180.0f*float(pi);
const AffineSpace3fa space = g_height_field->get(p)*AffineSpace3fa::rotate(Vec3fa(0,1,0),angle);
g_scene->add(new SceneGraph::TransformNode(space,object));
}
/* enable texture embedding */
else if (tag == "-embed-textures") {
embedTextures = true;
}
/* enable texture referencing */
else if (tag == "-reference-textures") {
embedTextures = false;
}
else if (tag == "-centerScaleTranslate") {
centerScale = cin->getFloat();
centerTranslate.x = cin->getFloat();
centerTranslate.y = cin->getFloat();
centerTranslate.z = cin->getFloat();
}
/* output filename */
else if (tag == "-o") {
SceneGraph::store(g_scene.dynamicCast<SceneGraph::Node>(),path + cin->getFileName(),embedTextures);
}
/* skip unknown command line parameter */
else {
std::cerr << "unknown command line parameter: " << tag << " ";
while (cin->peek() != "" && cin->peek()[0] != '-') std::cerr << cin->getString() << " ";
std::cerr << std::endl;
}
}
}
/* main function in embree namespace */
int main(int argc, char** argv)
{
/* create stream for parsing */
Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv));
/* parse command line */
parseCommandLine(stream, FileName());
return 0;
}
}
int main(int argc, char** argv)
{
try {
return embree::main(argc, argv);
}
catch (const std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
return 1;
}
catch (...) {
std::cout << "Error: unknown exception caught." << std::endl;
return 1;
}
}
<|endoftext|> |
<commit_before>// make a contour plot and get the first contour in a TPolyMarker
void FirstContour()
{
//this macro generates a color contour plot by selecting entries
//from an ntuple file.
//The TGraph object corresponding to the first contour line is
//accessed and displayed into a separate canvas.
//Author: Rene Brun
TString dir = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName());
dir.ReplaceAll("FirstContour.C","../hsimple.C");
dir.ReplaceAll("/./","/");
if (!gInterpreter->IsLoaded(dir.Data())) gInterpreter->LoadMacro(dir.Data());
TFile *file = (TFile*)gROOT->ProcessLineFast("hsimple(1)");
if (!file) return;
TTree *ntuple = (TTree*)file->Get("ntuple");
TCanvas *c1 = new TCanvas("c1","Contours",10,10,800,600);
gStyle->SetPalette(1);
ntuple->Draw("py:px","px*px+py*py < 20", "contz,list");
//we must call Update to force the canvas to be painted. When
//painting the contour plot, the list of contours is generated
//and a reference to it added to the Root list of special objects
c1->Update();
TCanvas *c2 = new TCanvas("c2","First contour",100,100,800,600);
TObjArray *contours =
(TObjArray*)gROOT->GetListOfSpecials()->FindObject("contours");
TList *lcontour1 = (TList*)contours->At(0);
TGraph *gc1 = (TGraph*)lcontour1->First();
gc1->SetMarkerStyle(21);
gc1->Draw("alp");
//We make a TCutG object with the array obtained from this graph
TCutG *cutg = new TCutG("cutg",gc1->GetN(),gc1->GetX(),gc1->GetY());
//We create a polymarker object with npmax points.
const Int_t npmax = 50000;
TPolyMarker *pm = new TPolyMarker(npmax);
Int_t np = 0;
while(1) {
Double_t x = -4 +8*gRandom->Rndm();
Double_t y = -4 +8*gRandom->Rndm();
if (cutg->IsInside(x,y)) {
pm->SetPoint(np,x,y);
np++;
if (np == npmax) break;
}
}
pm->Draw();
}
//--------------end of script contours.C
<commit_msg>Add some protections in case the input file is missing or contains a wrong information.<commit_after>// make a contour plot and get the first contour in a TPolyMarker
void FirstContour()
{
//this macro generates a color contour plot by selecting entries
//from an ntuple file.
//The TGraph object corresponding to the first contour line is
//accessed and displayed into a separate canvas.
//Author: Rene Brun
TString dir = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName());
dir.ReplaceAll("FirstContour.C","../hsimple.C");
dir.ReplaceAll("/./","/");
if (!gInterpreter->IsLoaded(dir.Data())) gInterpreter->LoadMacro(dir.Data());
TFile *file = (TFile*)gROOT->ProcessLineFast("hsimple(1)");
if (!file) return;
TTree *ntuple = (TTree*)file->Get("ntuple");
TCanvas *c1 = new TCanvas("c1","Contours",10,10,800,600);
gStyle->SetPalette(1);
ntuple->Draw("py:px","px*px+py*py < 20", "contz,list");
//we must call Update to force the canvas to be painted. When
//painting the contour plot, the list of contours is generated
//and a reference to it added to the Root list of special objects
c1->Update();
TCanvas *c2 = new TCanvas("c2","First contour",100,100,800,600);
TObjArray *contours =
(TObjArray*)gROOT->GetListOfSpecials()->FindObject("contours");
if (!contours) return;
TList *lcontour1 = (TList*)contours->At(0);
if (!lcontour1) return;
TGraph *gc1 = (TGraph*)lcontour1->First();
if (!gc1) return;
if (gc1->GetN() < 10) return;
gc1->SetMarkerStyle(21);
gc1->Draw("alp");
//We make a TCutG object with the array obtained from this graph
TCutG *cutg = new TCutG("cutg",gc1->GetN(),gc1->GetX(),gc1->GetY());
//We create a polymarker object with npmax points.
const Int_t npmax = 50000;
TPolyMarker *pm = new TPolyMarker(npmax);
Int_t np = 0;
while(1) {
Double_t x = -4 +8*gRandom->Rndm();
Double_t y = -4 +8*gRandom->Rndm();
if (cutg->IsInside(x,y)) {
pm->SetPoint(np,x,y);
np++;
if (np == npmax) break;
}
}
pm->Draw();
}
//--------------end of script contours.C
<|endoftext|> |
<commit_before>/*! @file tissue.hpp
@brief Interface of Tissue class
*/
#pragma once
#ifndef TUMOPP_TISSUE_HPP_
#define TUMOPP_TISSUE_HPP_
#include "coord.hpp"
#include "cell.hpp"
#include "random.hpp"
#include <cstdint>
#include <sstream>
#include <string>
#include <vector>
#include <array>
#include <unordered_set>
#include <map>
#include <memory>
#include <functional>
namespace tumopp {
class Benchmark;
/*! @brief Population of Cell
*/
class Tissue {
public:
//! Constructor
Tissue(
size_t initial_size=1u,
unsigned dimensions=3u,
const std::string& coordinate="moore",
const std::string& local_density_effect="const",
const std::string& displacement_path="random",
const EventRates& init_event_rates=EventRates{},
uint_fast32_t seed=std::random_device{}(),
bool enable_benchmark=false);
~Tissue();
//! main function
bool grow(
size_t max_size,
double max_time=100.0,
double snapshot_interval=0.0,
size_t recording_early_growth=0u,
size_t mutation_timing=0u,
bool verbose=false);
//! Simulate turnover with the increased death_rate
void plateau(double time);
//! Simulate medical treatment with the increased death_prob
void treatment(double death_prob, size_t num_resistant_cells = 3u);
//! Write #extant_cells_ and their ancestors
std::ostream& write_history(std::ostream&) const;
//! Write #snapshots_
std::ostream& write_snapshots(std::ostream&) const;
//! Write #drivers_
std::ostream& write_drivers(std::ostream&) const;
//! Write #benchmark_
std::ostream& write_benchmark(std::ostream&) const;
friend std::ostream& operator<< (std::ostream&, const Tissue&);
//! @cond
bool has_snapshots() const {return snapshots_.rdbuf()->in_avail();};
bool has_drivers() const {return drivers_.rdbuf()->in_avail();}
bool has_benchmark() const {return bool(benchmark_);}
//! @endcond
//! @name Getter functions
size_t size() const noexcept {return extant_cells_.size();}
unsigned dimensions() const noexcept {return coord_func_->dimensions();}
//@}
private:
//! Set #coord_func_
void init_coord(unsigned dimensions, const std::string& coordinate);
//! Set #insert function
void init_insert_function(const std::string& local_density_effect, const std::string& displacement_path);
//! initialized in init_insert_function()
std::function<bool(const std::shared_ptr<Cell>&)> insert;
//! Swap with a random neighbor
void migrate(const std::shared_ptr<Cell>&);
//! Emplace daughter cell and push other cells to the direction
void push(std::shared_ptr<Cell> moving, const coord_t& direction);
//! Push through the minimum drag path
void push_minimum_drag(std::shared_ptr<Cell> moving);
//! Try insert_adjacent() on every step in push()
void stroll(std::shared_ptr<Cell> moving, const coord_t& direction);
//! Insert x if any adjacent node is empty
bool insert_adjacent(const std::shared_ptr<Cell>& x);
//! Put new cell and return existing.
bool swap_existing(std::shared_ptr<Cell>* x);
//! Count steps to the nearest empty
size_t steps_to_empty(coord_t current, const coord_t& direction) const;
//! Direction to the nearest empty
const coord_t& to_nearest_empty(const coord_t& current, unsigned search_max=26) const;
//! Direction is selected with a probability proportional with 1/l
coord_t roulette_direction(const coord_t& current) const;
//! Count adjacent empty sites
uint_fast8_t num_empty_neighbors(const coord_t&) const;
//! TODO: Calculate positional value
constexpr double positional_value(const coord_t&) const {return 1.0;}
//! Push a cell to event #queue_
void queue_push(const std::shared_ptr<Cell>&, bool surrounded=false);
//! Write all cells to #snapshots_ with #time_
void snapshots_append();
/////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// Function object for extant_cells_
//! Hashing function object for shptr<Cell>
struct hash_shptr_cell {
//! hash function
size_t operator() (const std::shared_ptr<tumopp::Cell>& x) const noexcept {
return hash(x->coord());
}
};
//! Equal function object for shptr<Cell>
struct equal_shptr_cell {
//! Compare cell coord
bool operator() (const std::shared_ptr<tumopp::Cell>& lhs,
const std::shared_ptr<tumopp::Cell>& rhs) const noexcept {
return lhs->coord() == rhs->coord();
}
};
/////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// Data member
//! cells
std::unordered_set<
std::shared_ptr<Cell>,
hash_shptr_cell,
equal_shptr_cell> extant_cells_;
//! incremented when a new cell is born
unsigned id_tail_ = 0;
//! event queue
std::multimap<double, std::shared_ptr<Cell>> queue_;
//! continuous time
double time_ = 0.0;
//! initialized in init_coord() or init_coord_test()
std::unique_ptr<Coord> coord_func_;
//! record snapshots
std::stringstream snapshots_;
//! record driver mutations
std::stringstream drivers_;
//! record resource usage
std::unique_ptr<Benchmark> benchmark_;
//! random number generator
std::unique_ptr<urbg_t> engine_;
};
} // namespace tumopp
#endif // TUMOPP_TISSUE_HPP_
<commit_msg>:bug: Revert constexpr method for gcc-5<commit_after>/*! @file tissue.hpp
@brief Interface of Tissue class
*/
#pragma once
#ifndef TUMOPP_TISSUE_HPP_
#define TUMOPP_TISSUE_HPP_
#include "coord.hpp"
#include "cell.hpp"
#include "random.hpp"
#include <cstdint>
#include <sstream>
#include <string>
#include <vector>
#include <array>
#include <unordered_set>
#include <map>
#include <memory>
#include <functional>
namespace tumopp {
class Benchmark;
/*! @brief Population of Cell
*/
class Tissue {
public:
//! Constructor
Tissue(
size_t initial_size=1u,
unsigned dimensions=3u,
const std::string& coordinate="moore",
const std::string& local_density_effect="const",
const std::string& displacement_path="random",
const EventRates& init_event_rates=EventRates{},
uint_fast32_t seed=std::random_device{}(),
bool enable_benchmark=false);
~Tissue();
//! main function
bool grow(
size_t max_size,
double max_time=100.0,
double snapshot_interval=0.0,
size_t recording_early_growth=0u,
size_t mutation_timing=0u,
bool verbose=false);
//! Simulate turnover with the increased death_rate
void plateau(double time);
//! Simulate medical treatment with the increased death_prob
void treatment(double death_prob, size_t num_resistant_cells = 3u);
//! Write #extant_cells_ and their ancestors
std::ostream& write_history(std::ostream&) const;
//! Write #snapshots_
std::ostream& write_snapshots(std::ostream&) const;
//! Write #drivers_
std::ostream& write_drivers(std::ostream&) const;
//! Write #benchmark_
std::ostream& write_benchmark(std::ostream&) const;
friend std::ostream& operator<< (std::ostream&, const Tissue&);
//! @cond
bool has_snapshots() const {return snapshots_.rdbuf()->in_avail();};
bool has_drivers() const {return drivers_.rdbuf()->in_avail();}
bool has_benchmark() const {return bool(benchmark_);}
//! @endcond
//! @name Getter functions
size_t size() const noexcept {return extant_cells_.size();}
unsigned dimensions() const noexcept {return coord_func_->dimensions();}
//@}
private:
//! Set #coord_func_
void init_coord(unsigned dimensions, const std::string& coordinate);
//! Set #insert function
void init_insert_function(const std::string& local_density_effect, const std::string& displacement_path);
//! initialized in init_insert_function()
std::function<bool(const std::shared_ptr<Cell>&)> insert;
//! Swap with a random neighbor
void migrate(const std::shared_ptr<Cell>&);
//! Emplace daughter cell and push other cells to the direction
void push(std::shared_ptr<Cell> moving, const coord_t& direction);
//! Push through the minimum drag path
void push_minimum_drag(std::shared_ptr<Cell> moving);
//! Try insert_adjacent() on every step in push()
void stroll(std::shared_ptr<Cell> moving, const coord_t& direction);
//! Insert x if any adjacent node is empty
bool insert_adjacent(const std::shared_ptr<Cell>& x);
//! Put new cell and return existing.
bool swap_existing(std::shared_ptr<Cell>* x);
//! Count steps to the nearest empty
size_t steps_to_empty(coord_t current, const coord_t& direction) const;
//! Direction to the nearest empty
const coord_t& to_nearest_empty(const coord_t& current, unsigned search_max=26) const;
//! Direction is selected with a probability proportional with 1/l
coord_t roulette_direction(const coord_t& current) const;
//! Count adjacent empty sites
uint_fast8_t num_empty_neighbors(const coord_t&) const;
//! TODO: Calculate positional value
double positional_value(const coord_t&) const {return 1.0;}
//! Push a cell to event #queue_
void queue_push(const std::shared_ptr<Cell>&, bool surrounded=false);
//! Write all cells to #snapshots_ with #time_
void snapshots_append();
/////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// Function object for extant_cells_
//! Hashing function object for shptr<Cell>
struct hash_shptr_cell {
//! hash function
size_t operator() (const std::shared_ptr<tumopp::Cell>& x) const noexcept {
return hash(x->coord());
}
};
//! Equal function object for shptr<Cell>
struct equal_shptr_cell {
//! Compare cell coord
bool operator() (const std::shared_ptr<tumopp::Cell>& lhs,
const std::shared_ptr<tumopp::Cell>& rhs) const noexcept {
return lhs->coord() == rhs->coord();
}
};
/////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// Data member
//! cells
std::unordered_set<
std::shared_ptr<Cell>,
hash_shptr_cell,
equal_shptr_cell> extant_cells_;
//! incremented when a new cell is born
unsigned id_tail_ = 0;
//! event queue
std::multimap<double, std::shared_ptr<Cell>> queue_;
//! continuous time
double time_ = 0.0;
//! initialized in init_coord() or init_coord_test()
std::unique_ptr<Coord> coord_func_;
//! record snapshots
std::stringstream snapshots_;
//! record driver mutations
std::stringstream drivers_;
//! record resource usage
std::unique_ptr<Benchmark> benchmark_;
//! random number generator
std::unique_ptr<urbg_t> engine_;
};
} // namespace tumopp
#endif // TUMOPP_TISSUE_HPP_
<|endoftext|> |
<commit_before>#include <StdAfx.h>
#include <UI/Dialogs/Editors/restriction/CriteriaEditor.h>
#include <UI/Dialogs/Editors/restriction/RestrictEditor.h>
#include <core/mapi/extraPropTags.h>
#include <core/sortlistdata/binaryData.h>
#include <core/mapi/mapiMemory.h>
#include <core/utility/output.h>
#include <core/interpret/flags.h>
#include <core/addin/mfcmapi.h>
#include <core/property/parseProperty.h>
namespace dialog::editor
{
// Note that no alloc parent is passed in to CriteriaEditor. So we're completely responsible for freeing any memory we allocate.
// If we return (detach) memory to a caller, they must MAPIFreeBuffer
static std::wstring CRITERIACLASS = L"CriteriaEditor"; // STRING_OK
enum __CriteriaEditorFields
{
CRITERIA_SEARCHSTATEHEX,
CRITERIA_SEARCHSTATESTRING,
CRITERIA_SEARCHFLAGSHEX,
CRITERIA_SEARCHFLAGSSTRING,
CRITERIA_ENTRYLIST,
CRITERIA_RESTRICTIONSTRING
};
CriteriaEditor::CriteriaEditor(
_In_ CWnd* pParentWnd,
_In_ std::shared_ptr<cache::CMapiObjects> lpMapiObjects,
_In_ const _SRestriction* lpRes,
_In_ LPENTRYLIST lpEntryList,
ULONG ulSearchState)
: CEditor(
pParentWnd,
IDS_CRITERIAEDITOR,
IDS_CRITERIAEDITORPROMPT,
CEDITOR_BUTTON_OK | CEDITOR_BUTTON_ACTION1 | CEDITOR_BUTTON_CANCEL,
IDS_ACTIONEDITRES,
NULL,
NULL)
{
TRACE_CONSTRUCTOR(CRITERIACLASS);
m_lpMapiObjects = lpMapiObjects;
m_lpSourceRes = lpRes;
m_lpNewRes = nullptr;
m_lpSourceEntryList = lpEntryList;
m_lpNewEntryList = mapi::allocate<SBinaryArray*>(sizeof(SBinaryArray));
m_ulNewSearchFlags = NULL;
SetPromptPostFix(flags::AllFlagsToString(flagSearchFlag, true));
AddPane(viewpane::TextPane::CreateSingleLinePane(CRITERIA_SEARCHSTATEHEX, IDS_SEARCHSTATE, true));
SetHex(CRITERIA_SEARCHSTATEHEX, ulSearchState);
const auto szFlags = flags::InterpretFlags(flagSearchState, ulSearchState);
AddPane(viewpane::TextPane::CreateSingleLinePane(CRITERIA_SEARCHSTATESTRING, IDS_SEARCHSTATE, szFlags, true));
AddPane(viewpane::TextPane::CreateSingleLinePane(CRITERIA_SEARCHFLAGSHEX, IDS_SEARCHFLAGS, false));
SetHex(CRITERIA_SEARCHFLAGSHEX, 0);
AddPane(viewpane::TextPane::CreateSingleLinePane(CRITERIA_SEARCHFLAGSSTRING, IDS_SEARCHFLAGS, true));
AddPane(viewpane::ListPane::CreateCollapsibleListPane(
CRITERIA_ENTRYLIST, IDS_EIDLIST, false, false, ListEditCallBack(this)));
SetListID(CRITERIA_ENTRYLIST);
AddPane(viewpane::TextPane::CreateMultiLinePane(
CRITERIA_RESTRICTIONSTRING,
IDS_RESTRICTIONTEXT,
property::RestrictionToString(m_lpSourceRes, nullptr),
true));
}
CriteriaEditor::~CriteriaEditor()
{
// If these structures weren't detached, we need to free them
MAPIFreeBuffer(m_lpNewEntryList);
MAPIFreeBuffer(m_lpNewRes);
}
// Used to call functions which need to be called AFTER controls are created
BOOL CriteriaEditor::OnInitDialog()
{
const auto bRet = CEditor::OnInitDialog();
InitListFromEntryList(CRITERIA_ENTRYLIST, m_lpSourceEntryList);
UpdateButtons();
return bRet;
}
_Check_return_ const _SRestriction* CriteriaEditor::GetSourceRes() const noexcept
{
if (m_lpNewRes) return m_lpNewRes;
return m_lpSourceRes;
}
_Check_return_ ULONG CriteriaEditor::HandleChange(UINT nID)
{
const auto paneID = CEditor::HandleChange(nID);
if (paneID == CRITERIA_SEARCHFLAGSHEX)
{
SetStringW(CRITERIA_SEARCHFLAGSSTRING, flags::InterpretFlags(flagSearchFlag, GetHex(paneID)));
}
return paneID;
}
// Whoever gets this MUST MAPIFreeBuffer
_Check_return_ LPSRestriction CriteriaEditor::DetachModifiedSRestriction() noexcept
{
const auto lpRet = m_lpNewRes;
m_lpNewRes = nullptr;
return lpRet;
}
// Whoever gets this MUST MAPIFreeBuffer
_Check_return_ LPENTRYLIST CriteriaEditor::DetachModifiedEntryList() noexcept
{
const auto lpRet = m_lpNewEntryList;
m_lpNewEntryList = nullptr;
return lpRet;
}
_Check_return_ ULONG CriteriaEditor::GetSearchFlags() const noexcept { return m_ulNewSearchFlags; }
void CriteriaEditor::InitListFromEntryList(ULONG ulListNum, _In_ const SBinaryArray* lpEntryList) const
{
ClearList(ulListNum);
InsertColumn(ulListNum, 0, IDS_SHARP);
InsertColumn(ulListNum, 1, IDS_CB);
InsertColumn(ulListNum, 2, IDS_BINARY);
InsertColumn(ulListNum, 3, IDS_TEXTVIEW);
if (lpEntryList)
{
for (ULONG iRow = 0; iRow < lpEntryList->cValues; iRow++)
{
auto lpData = InsertListRow(ulListNum, iRow, std::to_wstring(iRow));
if (lpData)
{
sortlistdata::binaryData::init(lpData, &lpEntryList->lpbin[iRow]);
}
SetListString(ulListNum, iRow, 1, std::to_wstring(lpEntryList->lpbin[iRow].cb));
SetListString(ulListNum, iRow, 2, strings::BinToHexString(&lpEntryList->lpbin[iRow], false));
SetListString(ulListNum, iRow, 3, strings::BinToTextString(&lpEntryList->lpbin[iRow], true));
if (lpData) lpData->setFullyLoaded(true);
}
}
ResizeList(ulListNum, false);
}
void CriteriaEditor::OnEditAction1()
{
const auto lpSourceRes = GetSourceRes();
RestrictEditor MyResEditor(this, m_lpMapiObjects, nullptr,
lpSourceRes); // pass source res into editor
if (MyResEditor.DisplayDialog())
{
const auto lpModRes = MyResEditor.DetachModifiedSRestriction();
if (lpModRes)
{
// We didn't pass an alloc parent to RestrictEditor, so we must free what came back
MAPIFreeBuffer(m_lpNewRes);
m_lpNewRes = lpModRes;
SetStringW(CRITERIA_RESTRICTIONSTRING, property::RestrictionToString(m_lpNewRes, nullptr));
}
}
}
_Check_return_ bool CriteriaEditor::DoListEdit(ULONG ulListNum, int iItem, _In_ sortlistdata::sortListData* lpData)
{
if (!lpData) return false;
if (!lpData->cast<sortlistdata::binaryData>())
{
sortlistdata::binaryData::init(lpData, nullptr);
}
const auto binary = lpData->cast<sortlistdata::binaryData>();
if (!binary) return false;
CEditor BinEdit(this, IDS_EIDEDITOR, IDS_EIDEDITORPROMPT, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL);
auto lpSourcebin = binary->getCurrentBin();
BinEdit.AddPane(
viewpane::TextPane::CreateSingleLinePane(0, IDS_EID, strings::BinToHexString(lpSourcebin, false), false));
if (BinEdit.DisplayDialog())
{
auto bin = strings::HexStringToBin(BinEdit.GetStringW(0));
auto newBin = SBinary{};
newBin.lpb = mapi::ByteVectorToMAPI(bin, m_lpNewEntryList);
if (newBin.lpb)
{
newBin.cb = static_cast<ULONG>(bin.size());
binary->setCurrentBin(newBin);
const auto szTmp = std::to_wstring(newBin.cb);
SetListString(ulListNum, iItem, 1, szTmp);
SetListString(ulListNum, iItem, 2, strings::BinToHexString(&newBin, false));
SetListString(ulListNum, iItem, 3, strings::BinToTextString(&newBin, true));
return true;
}
}
return false;
}
void CriteriaEditor::OnOK()
{
CMyDialog::OnOK(); // don't need to call CEditor::OnOK
const auto ulValues = GetListCount(CRITERIA_ENTRYLIST);
if (m_lpNewEntryList && ulValues < ULONG_MAX / sizeof(SBinary))
{
m_lpNewEntryList->cValues = ulValues;
m_lpNewEntryList->lpbin =
mapi::allocate<LPSBinary>(m_lpNewEntryList->cValues * sizeof(SBinary), m_lpNewEntryList);
for (ULONG paneID = 0; paneID < m_lpNewEntryList->cValues; paneID++)
{
const auto lpData = GetListRowData(CRITERIA_ENTRYLIST, paneID);
if (lpData)
{
const auto binary = lpData->cast<sortlistdata::binaryData>();
if (binary)
{
m_lpNewEntryList->lpbin[paneID] = binary->detachBin(m_lpNewEntryList);
}
}
}
}
if (!m_lpNewRes && m_lpSourceRes)
{
EC_H_S(mapi::HrCopyRestriction(m_lpSourceRes, nullptr, &m_lpNewRes));
}
m_ulNewSearchFlags = GetHex(CRITERIA_SEARCHFLAGSHEX);
}
} // namespace dialog::editor<commit_msg>Group search flags as collapsables<commit_after>#include <StdAfx.h>
#include <UI/Dialogs/Editors/restriction/CriteriaEditor.h>
#include <UI/Dialogs/Editors/restriction/RestrictEditor.h>
#include <UI/ViewPane/SplitterPane.h>
#include <core/mapi/extraPropTags.h>
#include <core/sortlistdata/binaryData.h>
#include <core/mapi/mapiMemory.h>
#include <core/utility/output.h>
#include <core/interpret/flags.h>
#include <core/addin/mfcmapi.h>
#include <core/property/parseProperty.h>
namespace dialog::editor
{
// Note that no alloc parent is passed in to CriteriaEditor. So we're completely responsible for freeing any memory we allocate.
// If we return (detach) memory to a caller, they must MAPIFreeBuffer
static std::wstring CRITERIACLASS = L"CriteriaEditor"; // STRING_OK
enum __CriteriaEditorFields
{
CRITERIA_SEARCH,
CRITERIA_SEARCHSTATE,
CRITERIA_SEARCHSTATEHEX,
CRITERIA_SEARCHSTATESTRING,
CRITERIA_SEARCHFLAGS,
CRITERIA_SEARCHFLAGSHEX,
CRITERIA_SEARCHFLAGSSTRING,
CRITERIA_ENTRYLIST,
CRITERIA_RESTRICTIONSTRING
};
CriteriaEditor::CriteriaEditor(
_In_ CWnd* pParentWnd,
_In_ std::shared_ptr<cache::CMapiObjects> lpMapiObjects,
_In_ const _SRestriction* lpRes,
_In_ LPENTRYLIST lpEntryList,
ULONG ulSearchState)
: CEditor(
pParentWnd,
IDS_CRITERIAEDITOR,
IDS_CRITERIAEDITORPROMPT,
CEDITOR_BUTTON_OK | CEDITOR_BUTTON_ACTION1 | CEDITOR_BUTTON_CANCEL,
IDS_ACTIONEDITRES,
NULL,
NULL)
{
TRACE_CONSTRUCTOR(CRITERIACLASS);
m_lpMapiObjects = lpMapiObjects;
m_lpSourceRes = lpRes;
m_lpNewRes = nullptr;
m_lpSourceEntryList = lpEntryList;
m_lpNewEntryList = mapi::allocate<SBinaryArray*>(sizeof(SBinaryArray));
m_ulNewSearchFlags = NULL;
auto splitter = viewpane::SplitterPane::CreateHorizontalPane(CRITERIA_SEARCH, 0);
AddPane(splitter);
auto splitterState = viewpane::SplitterPane::CreateHorizontalPane(CRITERIA_SEARCHSTATE, IDS_SEARCHSTATE);
splitter->SetPaneOne(splitterState);
SetPromptPostFix(flags::AllFlagsToString(flagSearchFlag, true));
splitterState->SetPaneOne(viewpane::TextPane::CreateSingleLinePane(CRITERIA_SEARCHSTATEHEX, NULL, true));
SetHex(CRITERIA_SEARCHSTATEHEX, ulSearchState);
const auto szFlags = flags::InterpretFlags(flagSearchState, ulSearchState);
splitterState->SetPaneTwo(
viewpane::TextPane::CreateSingleLinePane(CRITERIA_SEARCHSTATESTRING, NULL, szFlags, true));
auto splitterFlags = viewpane::SplitterPane::CreateHorizontalPane(CRITERIA_SEARCHFLAGS, IDS_SEARCHFLAGS);
splitter->SetPaneTwo(splitterFlags);
splitterFlags->SetPaneOne(viewpane::TextPane::CreateSingleLinePane(CRITERIA_SEARCHFLAGSHEX, NULL, false));
SetHex(CRITERIA_SEARCHFLAGSHEX, 0);
splitterFlags->SetPaneTwo(viewpane::TextPane::CreateSingleLinePane(CRITERIA_SEARCHFLAGSSTRING, NULL, true));
AddPane(viewpane::ListPane::CreateCollapsibleListPane(
CRITERIA_ENTRYLIST, IDS_EIDLIST, false, false, ListEditCallBack(this)));
SetListID(CRITERIA_ENTRYLIST);
AddPane(viewpane::TextPane::CreateCollapsibleTextPane(CRITERIA_RESTRICTIONSTRING, IDS_RESTRICTIONTEXT, true));
SetStringW(CRITERIA_RESTRICTIONSTRING, property::RestrictionToString(m_lpSourceRes, nullptr));
}
CriteriaEditor::~CriteriaEditor()
{
// If these structures weren't detached, we need to free them
MAPIFreeBuffer(m_lpNewEntryList);
MAPIFreeBuffer(m_lpNewRes);
}
// Used to call functions which need to be called AFTER controls are created
BOOL CriteriaEditor::OnInitDialog()
{
const auto bRet = CEditor::OnInitDialog();
InitListFromEntryList(CRITERIA_ENTRYLIST, m_lpSourceEntryList);
UpdateButtons();
return bRet;
}
_Check_return_ const _SRestriction* CriteriaEditor::GetSourceRes() const noexcept
{
if (m_lpNewRes) return m_lpNewRes;
return m_lpSourceRes;
}
_Check_return_ ULONG CriteriaEditor::HandleChange(UINT nID)
{
const auto paneID = CEditor::HandleChange(nID);
if (paneID == CRITERIA_SEARCHFLAGSHEX)
{
SetStringW(CRITERIA_SEARCHFLAGSSTRING, flags::InterpretFlags(flagSearchFlag, GetHex(paneID)));
}
return paneID;
}
// Whoever gets this MUST MAPIFreeBuffer
_Check_return_ LPSRestriction CriteriaEditor::DetachModifiedSRestriction() noexcept
{
const auto lpRet = m_lpNewRes;
m_lpNewRes = nullptr;
return lpRet;
}
// Whoever gets this MUST MAPIFreeBuffer
_Check_return_ LPENTRYLIST CriteriaEditor::DetachModifiedEntryList() noexcept
{
const auto lpRet = m_lpNewEntryList;
m_lpNewEntryList = nullptr;
return lpRet;
}
_Check_return_ ULONG CriteriaEditor::GetSearchFlags() const noexcept { return m_ulNewSearchFlags; }
void CriteriaEditor::InitListFromEntryList(ULONG ulListNum, _In_ const SBinaryArray* lpEntryList) const
{
ClearList(ulListNum);
InsertColumn(ulListNum, 0, IDS_SHARP);
InsertColumn(ulListNum, 1, IDS_CB);
InsertColumn(ulListNum, 2, IDS_BINARY);
InsertColumn(ulListNum, 3, IDS_TEXTVIEW);
if (lpEntryList)
{
for (ULONG iRow = 0; iRow < lpEntryList->cValues; iRow++)
{
auto lpData = InsertListRow(ulListNum, iRow, std::to_wstring(iRow));
if (lpData)
{
sortlistdata::binaryData::init(lpData, &lpEntryList->lpbin[iRow]);
}
SetListString(ulListNum, iRow, 1, std::to_wstring(lpEntryList->lpbin[iRow].cb));
SetListString(ulListNum, iRow, 2, strings::BinToHexString(&lpEntryList->lpbin[iRow], false));
SetListString(ulListNum, iRow, 3, strings::BinToTextString(&lpEntryList->lpbin[iRow], true));
if (lpData) lpData->setFullyLoaded(true);
}
}
ResizeList(ulListNum, false);
}
void CriteriaEditor::OnEditAction1()
{
const auto lpSourceRes = GetSourceRes();
RestrictEditor MyResEditor(this, m_lpMapiObjects, nullptr,
lpSourceRes); // pass source res into editor
if (MyResEditor.DisplayDialog())
{
const auto lpModRes = MyResEditor.DetachModifiedSRestriction();
if (lpModRes)
{
// We didn't pass an alloc parent to RestrictEditor, so we must free what came back
MAPIFreeBuffer(m_lpNewRes);
m_lpNewRes = lpModRes;
SetStringW(CRITERIA_RESTRICTIONSTRING, property::RestrictionToString(m_lpNewRes, nullptr));
}
}
}
_Check_return_ bool CriteriaEditor::DoListEdit(ULONG ulListNum, int iItem, _In_ sortlistdata::sortListData* lpData)
{
if (!lpData) return false;
if (!lpData->cast<sortlistdata::binaryData>())
{
sortlistdata::binaryData::init(lpData, nullptr);
}
const auto binary = lpData->cast<sortlistdata::binaryData>();
if (!binary) return false;
CEditor BinEdit(this, IDS_EIDEDITOR, IDS_EIDEDITORPROMPT, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL);
auto lpSourcebin = binary->getCurrentBin();
BinEdit.AddPane(
viewpane::TextPane::CreateSingleLinePane(0, IDS_EID, strings::BinToHexString(lpSourcebin, false), false));
if (BinEdit.DisplayDialog())
{
auto bin = strings::HexStringToBin(BinEdit.GetStringW(0));
auto newBin = SBinary{};
newBin.lpb = mapi::ByteVectorToMAPI(bin, m_lpNewEntryList);
if (newBin.lpb)
{
newBin.cb = static_cast<ULONG>(bin.size());
binary->setCurrentBin(newBin);
const auto szTmp = std::to_wstring(newBin.cb);
SetListString(ulListNum, iItem, 1, szTmp);
SetListString(ulListNum, iItem, 2, strings::BinToHexString(&newBin, false));
SetListString(ulListNum, iItem, 3, strings::BinToTextString(&newBin, true));
return true;
}
}
return false;
}
void CriteriaEditor::OnOK()
{
CMyDialog::OnOK(); // don't need to call CEditor::OnOK
const auto ulValues = GetListCount(CRITERIA_ENTRYLIST);
if (m_lpNewEntryList && ulValues < ULONG_MAX / sizeof(SBinary))
{
m_lpNewEntryList->cValues = ulValues;
m_lpNewEntryList->lpbin =
mapi::allocate<LPSBinary>(m_lpNewEntryList->cValues * sizeof(SBinary), m_lpNewEntryList);
for (ULONG paneID = 0; paneID < m_lpNewEntryList->cValues; paneID++)
{
const auto lpData = GetListRowData(CRITERIA_ENTRYLIST, paneID);
if (lpData)
{
const auto binary = lpData->cast<sortlistdata::binaryData>();
if (binary)
{
m_lpNewEntryList->lpbin[paneID] = binary->detachBin(m_lpNewEntryList);
}
}
}
}
if (!m_lpNewRes && m_lpSourceRes)
{
EC_H_S(mapi::HrCopyRestriction(m_lpSourceRes, nullptr, &m_lpNewRes));
}
m_ulNewSearchFlags = GetHex(CRITERIA_SEARCHFLAGSHEX);
}
} // namespace dialog::editor<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "ReClass2015.h"
#include "DialogModules.h"
#include "MainFrm.h"
#include "ChildFrm.h"
#include "SDK.h"
#include "afxdialogex.h"
IMPLEMENT_DYNAMIC(CDialogModules, CDialogEx)
CDialogModules::CDialogModules(CWnd* pParent)
: CDialogEx(CDialogModules::IDD, pParent)
{
}
CDialogModules::~CDialogModules()
{
}
void CDialogModules::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_MODULELIST, m_ModuleViewList);
DDX_Control(pDX, IDC_MODULENAME, m_Edit);
}
void CDialogModules::OnSize(UINT nType, int cx, int cy)
{
CDialogEx::OnSize( nType, cx, cy );
}
void CDialogModules::OnGetMinMaxInfo( MINMAXINFO *lpinfo )
{
CDialogEx::OnGetMinMaxInfo( lpinfo );
if ( !m_OriginalSize.IsRectNull( ) )
{
lpinfo->ptMinTrackSize.x = m_OriginalSize.Width( );
lpinfo->ptMinTrackSize.y = m_OriginalSize.Height( );
}
}
BEGIN_MESSAGE_MAP(CDialogModules, CDialogEx)
ON_NOTIFY(NM_DBLCLK, IDC_MODULELIST, OnDblclkListControl)
ON_NOTIFY(LVN_COLUMNCLICK, IDC_MODULELIST, OnColumnClick)
ON_EN_CHANGE(IDC_MODULENAME, &CDialogModules::OnEnChangeModuleName)
ON_WM_GETMINMAXINFO()
ON_WM_SIZE()
END_MESSAGE_MAP()
void CDialogModules::BuildList()
{
for (UINT i = 0; i < MemMapModule.size(); i++)
{
MemMapInfo moduleInfo = MemMapModule[i];
SHFILEINFO sfi = { 0 };
SHGetFileInfo(MemMapModule[i].Path, FILE_ATTRIBUTE_NORMAL, &sfi, sizeof(SHFILEINFO), SHGFI_ICON | SHGFI_USEFILEATTRIBUTES);
m_ImageList.Add(sfi.hIcon);
CString name = moduleInfo.Name, upercase_name = CString(moduleInfo.Name).MakeUpper();
if ( m_Filter.GetLength( ) != 0 && upercase_name.Find( m_Filter.MakeUpper( ) ) == -1 )
continue;
TCHAR strStart[64];
_stprintf(strStart, _T("0x%IX"), moduleInfo.Start);
TCHAR strEnd[64];
_stprintf(strEnd, _T("0x%IX"), moduleInfo.End);
TCHAR strSize[64];
_stprintf(strSize, _T("0x%X"), moduleInfo.Size);
AddData(i, (LPTSTR)name.GetString(), strStart, strEnd, strSize, static_cast<LPARAM>(moduleInfo.Start));
}
}
BOOL CDialogModules::OnInitDialog()
{
CDialogEx::OnInitDialog();
GetWindowRect( &m_OriginalSize );
ScreenToClient( &m_OriginalSize );
m_ImageList.Create(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), ILC_COLOR32, 1, 1);
m_ImageList.SetBkColor(RGB(255, 255, 255));
m_ModuleViewList.SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES | LVS_EX_DOUBLEBUFFER);
m_ModuleViewList.InsertColumn(COLUMN_MODULE, _T("Module"), LVCFMT_LEFT, 300);
m_ModuleViewList.InsertColumn(COLUMN_START, _T("Start"), LVCFMT_LEFT, 80);
m_ModuleViewList.InsertColumn(COLUMN_END, _T("End"), LVCFMT_LEFT, 80);
m_ModuleViewList.InsertColumn(COLUMN_SIZE, _T("Size"), LVCFMT_LEFT, 80);
m_ModuleViewList.SetImageList(&m_ImageList, LVSIL_SMALL);
BuildList();
return TRUE;
}
__inline int CDialogModules::FindModuleByName(const TCHAR* szName)
{
for (int id = 0; id < MemMapModule.size(); id++)
{
MemMapInfo moduleInfo = MemMapModule[id];
if (_tcsicmp(moduleInfo.Name, szName) == 0)
return id;
}
return -1;
};
__inline CNodeClass* CDialogModules::GetClassByName(const TCHAR* szClassName)
{
CNodeClass* pClass = 0;
for (unsigned int i = 0; i < theApp.Classes.size(); i++) {
if (theApp.Classes[i]->Name == szClassName) {
pClass = theApp.Classes[i];
break;
}
}
return pClass;
}
void CDialogModules::SetSelected()
{
POSITION pos = m_ModuleViewList.GetFirstSelectedItemPosition();
while (pos)
{
int nItem = m_ModuleViewList.GetNextSelectedItem(pos);
nItem = FindModuleByName(m_ModuleViewList.GetItemText(nItem, 0));
CMainFrame* pFrame = static_cast<CMainFrame*>(AfxGetApp()->m_pMainWnd);
CChildFrame* pChild = static_cast<CChildFrame*>(pFrame->CreateNewChild(RUNTIME_CLASS(CChildFrame), IDR_ReClass2015TYPE, theApp.m_hMDIMenu, theApp.m_hMDIAccel));
int extension_size = MemMapModule[ nItem ].Name.ReverseFind( '.' );
if ( extension_size == -1 ) extension_size = 0;
else extension_size = MemMapModule[ nItem ].Name.GetLength( ) - extension_size;
CString ClassName = MemMapModule[ nItem ].Name.Left( MemMapModule[ nItem ].Name.GetLength( ) - extension_size ) + _T( "_base" );
CNodeClass* pNewClass = GetClassByName(ClassName);
if (!pNewClass)
{
pNewClass = new CNodeClass;
pNewClass->Name = ClassName;
TCHAR strStart[64];
_stprintf(strStart, _T("%IX"), MemMapModule[nItem].Start);
pNewClass->strOffset = strStart;
pNewClass->offset = MemMapModule[nItem].Start;
pNewClass->pChildWindow = pChild;
pNewClass->idx = (int)theApp.Classes.size();
theApp.Classes.push_back(pNewClass);
DWORD offset = 0;
for (int i = 0; i < 64 / sizeof(size_t); i++)
{
CNodeHex* pNode = new CNodeHex;
pNode->pParent = pNewClass;
pNode->offset = offset;
offset += pNode->GetMemorySize();
pNewClass->Nodes.push_back(pNode);
}
}
pChild->m_wndView.m_pClass = pNewClass;
// This will get overwritten for each module that is selected
pChild->SetTitle(ClassName);
pChild->SetWindowText(ClassName);
pFrame->UpdateFrameTitleForDocument(ClassName);
}
}
//int (CALLBACK *PFNLVCOMPARE)(LPARAM, LPARAM, LPARAM);
int CALLBACK CDialogModules::CompareFunction(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{
COMPARESTRUCT* compare = (COMPARESTRUCT*)lParamSort;
if (compare)
{
CListCtrl* pListCtrl = (CListCtrl*)compare->pListCtrl;
int column = compare->iColumn;
if (column == COLUMN_START || column == COLUMN_END || column == COLUMN_SIZE)
{
CString strNum1 = pListCtrl->GetItemText(static_cast<int>(lParam1), column);
CString strNum2 = pListCtrl->GetItemText(static_cast<int>(lParam2), column);
size_t num1 = (size_t)_tcstoui64(strNum1.GetBuffer(), NULL, 16);
size_t num2 = (size_t)_tcstoui64(strNum2.GetBuffer(), NULL, 16);
return num2 - num1;
}
else if (column == COLUMN_MODULE)
{
CString strModuleName1 = pListCtrl->GetItemText(static_cast<int>(lParam1), column);
CString strModuleName2 = pListCtrl->GetItemText(static_cast<int>(lParam2), column);
return _tcsicmp(strModuleName1.GetBuffer(), strModuleName2.GetBuffer());
}
}
return 0;
}
void CDialogModules::OnColumnClick(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
LPCOMPARESTRUCT compare = new COMPARESTRUCT;
compare->pListCtrl = &m_ModuleViewList;
compare->iColumn = pNMListView->iSubItem;
m_ModuleViewList.SortItemsEx(CompareFunction, (LPARAM)compare);
delete compare;
*pResult = 0;
}
void CDialogModules::OnDblclkListControl(NMHDR* pNMHDR, LRESULT* pResult)
{
SetSelected();
CDialogEx::OnOK();
}
void CDialogModules::OnOK()
{
SetSelected();
CDialogEx::OnOK();
}
int CDialogModules::AddData(int Index, LPTSTR ModuleName, LPTSTR StartAddress, LPTSTR EndAddress, LPTSTR ModuleSize, LPARAM lParam)
{
LVITEM lvi = { 0 };
lvi.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM;
lvi.pszText = ModuleName;
lvi.cchTextMax = static_cast<int>(_tcslen(ModuleName)) + 1;
lvi.iImage = Index;
lvi.lParam = lParam;
lvi.iItem = m_ModuleViewList.GetItemCount();
int pos = m_ModuleViewList.InsertItem(&lvi);
m_ModuleViewList.SetItemText(pos, COLUMN_START, (LPTSTR)StartAddress);
m_ModuleViewList.SetItemText(pos, COLUMN_END, (LPTSTR)EndAddress);
m_ModuleViewList.SetItemText(pos, COLUMN_SIZE, (LPTSTR)ModuleSize);
return pos;
}
void CDialogModules::OnEnChangeModuleName()
{
m_Edit.GetWindowText(m_Filter);
m_ModuleViewList.DeleteAllItems();
BuildList();
}
<commit_msg>Delete DialogModulesBACKUP.cpp<commit_after><|endoftext|> |
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/VIEW/PRIMITIVES/QuadMesh>
using namespace std;
namespace BALL
{
namespace VIEW
{
QuadMesh::QuadMesh()
: GeometricObject(),
MultiColorExtension()
{
}
QuadMesh::QuadMesh(const QuadMesh& mesh)
: GeometricObject(mesh),
MultiColorExtension(mesh),
vertex(mesh.vertex),
normal(mesh.normal),
quad(mesh.quad)
{
}
} // namespace VIEW
} // namespace BALL
<commit_msg>Fixed some QT::tr bug<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/VIEW/PRIMITIVES/quadMesh.h>
using namespace std;
namespace BALL
{
namespace VIEW
{
QuadMesh::QuadMesh()
: GeometricObject(),
MultiColorExtension()
{
}
QuadMesh::QuadMesh(const QuadMesh& mesh)
: GeometricObject(mesh),
MultiColorExtension(mesh),
vertex(mesh.vertex),
normal(mesh.normal),
quad(mesh.quad)
{
}
} // namespace VIEW
} // namespace BALL
<|endoftext|> |
<commit_before>/*
kwatchgnupgconfig.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB
Kleopatra is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Kleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "kwatchgnupgconfig.h"
#include <klocale.h>
#include <kurlrequester.h>
#include <kconfig.h>
#include <kapplication.h>
#include <qframe.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qspinbox.h>
#include <qcheckbox.h>
#include <qcombobox.h>
#include <qdir.h>
#include <qvgroupbox.h>
static const char* log_levels[] = { "none", "basic", "advanced", "expert", "guru" };
static int log_level_to_int( const QString& loglevel )
{
if( loglevel == "none" ) {
return 0;
} else if( loglevel == "basic" ) {
return 1;
} else if( loglevel == "advanced" ) {
return 2;
} else if( loglevel == "expert" ) {
return 3;
} else if( loglevel == "guru" ) {
return 4;
} else {
// default
return 1;
}
}
KWatchGnuPGConfig::KWatchGnuPGConfig( QWidget* parent, const char* name )
: KDialogBase( Plain, i18n("Configure KWatchGnuPG"),
Apply|Ok|Cancel, Ok, parent, name )
{
// tmp vars:
QWidget * w;
QGridLayout * glay;
QGroupBox * group;
QWidget * top = plainPage();
QVBoxLayout * vlay = new QVBoxLayout( top, 0, spacingHint() );
group = new QVGroupBox( i18n("WatchGnuPG"), top );
group->layout()->setSpacing( spacingHint() );
w = new QWidget( group );
glay = new QGridLayout( w, 3, 2, 0, spacingHint() );
glay->setColStretch( 1, 1 );
int row = -1;
++row;
mExeED = new KURLRequester( w );
glay->addWidget( new QLabel( mExeED, i18n("&Executable:"), w ), row, 0 );
glay->addWidget( mExeED, row, 1 );
connect( mExeED, SIGNAL(textChanged(const QString&)), SLOT(slotChanged()) );
++row;
mSocketED = new KURLRequester( w );
glay->addWidget( new QLabel( mSocketED, i18n("&Socket:"), w ), row, 0 );
glay->addWidget( mSocketED, row, 1 );
connect( mSocketED, SIGNAL(textChanged(const QString&)), SLOT(slotChanged()) );
++row;
mLogLevelCB = new QComboBox( false, w );
mLogLevelCB->insertItem( i18n("None") );
mLogLevelCB->insertItem( i18n("Basic") );
mLogLevelCB->insertItem( i18n("Advanced") );
mLogLevelCB->insertItem( i18n("Expert") );
mLogLevelCB->insertItem( i18n("Guru") );
glay->addWidget( new QLabel( mLogLevelCB, i18n("Default &log level:"), w ), row, 0 );
glay->addWidget( mLogLevelCB, row, 1 );
connect( mLogLevelCB, SIGNAL(activated(int)), SLOT(slotChanged()) );
vlay->addWidget( group );
/******************* Log Window group *******************/
group = new QVGroupBox( i18n("Log Window"), top );
group->layout()->setSpacing( spacingHint() );
w = new QWidget( group );
glay = new QGridLayout( w, 2, 3, 0, spacingHint() );
glay->setColStretch( 1, 1 );
row = -1;
++row;
mLoglenSB = new QSpinBox( 0, 1000000, 100, w );
mLoglenSB->setSuffix( i18n("history size spinbox suffix"," lines") );
mLoglenSB->setSpecialValueText( i18n("unlimited") );
glay->addWidget( new QLabel( mLoglenSB, i18n("&History size:"), w ), row, 0 );
glay->addWidget( mLoglenSB, row, 1 );
QPushButton * button = new QPushButton( i18n("Set &Unlimited"), w );
glay->addWidget( button, row, 2 );
connect( mLoglenSB, SIGNAL(valueChanged(int)), SLOT(slotChanged()) );
connect( button, SIGNAL(clicked()), SLOT(slotSetHistorySizeUnlimited()) );
++row;
mWordWrapCB = new QCheckBox( i18n("Enable &word wrapping"), w );
glay->addMultiCellWidget( mWordWrapCB, row, row, 0, 2 );
connect( mWordWrapCB, SIGNAL(clicked()), SLOT(slotChanged()) );
vlay->addWidget( group );
vlay->addStretch( 1 );
connect( this, SIGNAL(applyClicked()), SLOT(slotSave()) );
connect( this, SIGNAL(okClicked()), SLOT(slotSave()) );
}
void KWatchGnuPGConfig::slotSetHistorySizeUnlimited() {
mLoglenSB->setValue( 0 );
}
void KWatchGnuPGConfig::loadConfig()
{
KConfig* config = kapp->config();
config->setGroup("WatchGnuPG");
mExeED->setURL( config->readEntry( "Executable", "watchgnupg" ) );
mSocketED->setURL( config->readEntry( "Socket", QDir::home().canonicalPath()
+ "/.gnupg/log-socket") );
mLogLevelCB->setCurrentItem( log_level_to_int( config->readEntry( "LogLevel", "basic" ) ) );
config->setGroup("LogWindow");
mLoglenSB->setValue( config->readNumEntry( "MaxLogLen", 10000 ) );
mWordWrapCB->setChecked( config->readBoolEntry("WordWrap", false ) );
config->setGroup( QString::null );
enableButtonOK( false );
enableButtonApply( false );
}
void KWatchGnuPGConfig::saveConfig()
{
KConfig* config = kapp->config();
config->setGroup("WatchGnuPG");
config->writeEntry( "Executable", mExeED->url() );
config->writeEntry( "Socket", mSocketED->url() );
config->writeEntry( "LogLevel", log_levels[mLogLevelCB->currentItem()] );
config->setGroup("LogWindow");
config->writeEntry( "MaxLogLen", mLoglenSB->value() );
config->writeEntry( "WordWrap", mWordWrapCB->isChecked() );
config->setGroup( QString::null );
config->sync();
enableButtonOK( false );
enableButtonApply( false );
}
void KWatchGnuPGConfig::slotChanged()
{
enableButtonOK( true );
enableButtonApply( true );
}
void KWatchGnuPGConfig::slotSave()
{
saveConfig();
emit reconfigure();
}
#include "kwatchgnupgconfig.moc"
<commit_msg>QTextEdit doesn't support word wrap in LogText mode. So hide this option.<commit_after>/*
kwatchgnupgconfig.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB
Kleopatra is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Kleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "kwatchgnupgconfig.h"
#include <klocale.h>
#include <kurlrequester.h>
#include <kconfig.h>
#include <kapplication.h>
#include <qframe.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qspinbox.h>
#include <qcheckbox.h>
#include <qcombobox.h>
#include <qdir.h>
#include <qvgroupbox.h>
static const char* log_levels[] = { "none", "basic", "advanced", "expert", "guru" };
static int log_level_to_int( const QString& loglevel )
{
if( loglevel == "none" ) {
return 0;
} else if( loglevel == "basic" ) {
return 1;
} else if( loglevel == "advanced" ) {
return 2;
} else if( loglevel == "expert" ) {
return 3;
} else if( loglevel == "guru" ) {
return 4;
} else {
// default
return 1;
}
}
KWatchGnuPGConfig::KWatchGnuPGConfig( QWidget* parent, const char* name )
: KDialogBase( Plain, i18n("Configure KWatchGnuPG"),
Apply|Ok|Cancel, Ok, parent, name )
{
// tmp vars:
QWidget * w;
QGridLayout * glay;
QGroupBox * group;
QWidget * top = plainPage();
QVBoxLayout * vlay = new QVBoxLayout( top, 0, spacingHint() );
group = new QVGroupBox( i18n("WatchGnuPG"), top );
group->layout()->setSpacing( spacingHint() );
w = new QWidget( group );
glay = new QGridLayout( w, 3, 2, 0, spacingHint() );
glay->setColStretch( 1, 1 );
int row = -1;
++row;
mExeED = new KURLRequester( w );
glay->addWidget( new QLabel( mExeED, i18n("&Executable:"), w ), row, 0 );
glay->addWidget( mExeED, row, 1 );
connect( mExeED, SIGNAL(textChanged(const QString&)), SLOT(slotChanged()) );
++row;
mSocketED = new KURLRequester( w );
glay->addWidget( new QLabel( mSocketED, i18n("&Socket:"), w ), row, 0 );
glay->addWidget( mSocketED, row, 1 );
connect( mSocketED, SIGNAL(textChanged(const QString&)), SLOT(slotChanged()) );
++row;
mLogLevelCB = new QComboBox( false, w );
mLogLevelCB->insertItem( i18n("None") );
mLogLevelCB->insertItem( i18n("Basic") );
mLogLevelCB->insertItem( i18n("Advanced") );
mLogLevelCB->insertItem( i18n("Expert") );
mLogLevelCB->insertItem( i18n("Guru") );
glay->addWidget( new QLabel( mLogLevelCB, i18n("Default &log level:"), w ), row, 0 );
glay->addWidget( mLogLevelCB, row, 1 );
connect( mLogLevelCB, SIGNAL(activated(int)), SLOT(slotChanged()) );
vlay->addWidget( group );
/******************* Log Window group *******************/
group = new QVGroupBox( i18n("Log Window"), top );
group->layout()->setSpacing( spacingHint() );
w = new QWidget( group );
glay = new QGridLayout( w, 2, 3, 0, spacingHint() );
glay->setColStretch( 1, 1 );
row = -1;
++row;
mLoglenSB = new QSpinBox( 0, 1000000, 100, w );
mLoglenSB->setSuffix( i18n("history size spinbox suffix"," lines") );
mLoglenSB->setSpecialValueText( i18n("unlimited") );
glay->addWidget( new QLabel( mLoglenSB, i18n("&History size:"), w ), row, 0 );
glay->addWidget( mLoglenSB, row, 1 );
QPushButton * button = new QPushButton( i18n("Set &Unlimited"), w );
glay->addWidget( button, row, 2 );
connect( mLoglenSB, SIGNAL(valueChanged(int)), SLOT(slotChanged()) );
connect( button, SIGNAL(clicked()), SLOT(slotSetHistorySizeUnlimited()) );
++row;
mWordWrapCB = new QCheckBox( i18n("Enable &word wrapping"), w );
mWordWrapCB->hide(); // QTextEdit doesn't support word wrapping in LogText mode
glay->addMultiCellWidget( mWordWrapCB, row, row, 0, 2 );
connect( mWordWrapCB, SIGNAL(clicked()), SLOT(slotChanged()) );
vlay->addWidget( group );
vlay->addStretch( 1 );
connect( this, SIGNAL(applyClicked()), SLOT(slotSave()) );
connect( this, SIGNAL(okClicked()), SLOT(slotSave()) );
}
void KWatchGnuPGConfig::slotSetHistorySizeUnlimited() {
mLoglenSB->setValue( 0 );
}
void KWatchGnuPGConfig::loadConfig()
{
KConfig* config = kapp->config();
config->setGroup("WatchGnuPG");
mExeED->setURL( config->readEntry( "Executable", "watchgnupg" ) );
mSocketED->setURL( config->readEntry( "Socket", QDir::home().canonicalPath()
+ "/.gnupg/log-socket") );
mLogLevelCB->setCurrentItem( log_level_to_int( config->readEntry( "LogLevel", "basic" ) ) );
config->setGroup("LogWindow");
mLoglenSB->setValue( config->readNumEntry( "MaxLogLen", 10000 ) );
mWordWrapCB->setChecked( config->readBoolEntry("WordWrap", false ) );
config->setGroup( QString::null );
enableButtonOK( false );
enableButtonApply( false );
}
void KWatchGnuPGConfig::saveConfig()
{
KConfig* config = kapp->config();
config->setGroup("WatchGnuPG");
config->writeEntry( "Executable", mExeED->url() );
config->writeEntry( "Socket", mSocketED->url() );
config->writeEntry( "LogLevel", log_levels[mLogLevelCB->currentItem()] );
config->setGroup("LogWindow");
config->writeEntry( "MaxLogLen", mLoglenSB->value() );
config->writeEntry( "WordWrap", mWordWrapCB->isChecked() );
config->setGroup( QString::null );
config->sync();
enableButtonOK( false );
enableButtonApply( false );
}
void KWatchGnuPGConfig::slotChanged()
{
enableButtonOK( true );
enableButtonApply( true );
}
void KWatchGnuPGConfig::slotSave()
{
saveConfig();
emit reconfigure();
}
#include "kwatchgnupgconfig.moc"
<|endoftext|> |
<commit_before>// Copyright 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/logging.h"
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
#if defined(OS_POSIX)
#include <sys/time.h>
#include <unistd.h>
#include "base/posix/safe_strerror.h"
#endif // OS_POSIX
#if defined(OS_MACOSX)
#include <pthread.h>
#elif defined(OS_LINUX)
#include <sys/syscall.h>
#include <sys/types.h>
#elif defined(OS_WIN)
#include <windows.h>
#endif
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
namespace logging {
namespace {
const char* const log_severity_names[] = {
"INFO",
"WARNING",
"ERROR",
"ERROR_REPORT",
"FATAL"
};
LogMessageHandlerFunction g_log_message_handler = nullptr;
} // namespace
void SetLogMessageHandler(LogMessageHandlerFunction log_message_handler) {
g_log_message_handler = log_message_handler;
}
LogMessageHandlerFunction GetLogMessageHandler() {
return g_log_message_handler;
}
#if defined(OS_WIN)
std::string SystemErrorCodeToString(unsigned long error_code) {
wchar_t msgbuf[256];
DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_MAX_WIDTH_MASK;
DWORD len = FormatMessage(
flags, nullptr, error_code, 0, msgbuf, arraysize(msgbuf), nullptr);
if (len) {
// Most system messages end in a period and a space. Remove the space if
// it’s there, because the following StringPrintf() includes one.
if (len >= 1 && msgbuf[len - 1] == ' ') {
msgbuf[len - 1] = '\0';
}
return base::StringPrintf("%s (%u)",
base::UTF16ToUTF8(msgbuf).c_str(), error_code);
}
return base::StringPrintf("Error %u while retrieving error %u",
GetLastError(),
error_code);
}
#endif // OS_WIN
LogMessage::LogMessage(const char* function,
const char* file_path,
int line,
LogSeverity severity)
: stream_(),
file_path_(file_path),
message_start_(0),
line_(line),
severity_(severity) {
Init(function);
}
LogMessage::LogMessage(const char* function,
const char* file_path,
int line,
std::string* result)
: stream_(),
file_path_(file_path),
message_start_(0),
line_(line),
severity_(LOG_FATAL) {
Init(function);
stream_ << "Check failed: " << *result << ". ";
delete result;
}
LogMessage::~LogMessage() {
stream_ << std::endl;
std::string str_newline(stream_.str());
if (g_log_message_handler &&
g_log_message_handler(
severity_, file_path_, line_, message_start_, str_newline)) {
return;
}
fprintf(stderr, "%s", str_newline.c_str());
fflush(stderr);
#if defined(OS_WIN)
OutputDebugString(base::UTF8ToUTF16(str_newline).c_str());
#endif
if (severity_ == LOG_FATAL) {
#ifndef NDEBUG
abort();
#else
#if defined(OS_WIN)
__debugbreak();
#else
__asm__("int3");
#endif
#endif
}
}
void LogMessage::Init(const char* function) {
std::string file_name(file_path_);
#if defined(OS_WIN)
size_t last_slash = file_name.find_last_of("\\/");
#else
size_t last_slash = file_name.find_last_of('/');
#endif
if (last_slash != std::string::npos) {
file_name.assign(file_name.substr(last_slash + 1));
}
#if defined(OS_POSIX)
pid_t pid = getpid();
#elif defined(OS_WIN)
DWORD pid = GetCurrentProcessId();
#endif
#if defined(OS_MACOSX)
uint64_t thread;
pthread_threadid_np(pthread_self(), &thread);
#elif defined(OS_LINUX)
pid_t thread = syscall(__NR_gettid);
#elif defined(OS_WIN)
DWORD thread = GetCurrentThreadId();
#endif
stream_ << '['
<< pid
<< ':'
<< thread
<< ':'
<< std::setfill('0');
#if defined(OS_POSIX)
timeval tv;
gettimeofday(&tv, nullptr);
tm local_time;
localtime_r(&tv.tv_sec, &local_time);
stream_ << std::setw(4) << local_time.tm_year + 1900
<< std::setw(2) << local_time.tm_mon + 1
<< std::setw(2) << local_time.tm_mday
<< ','
<< std::setw(2) << local_time.tm_hour
<< std::setw(2) << local_time.tm_min
<< std::setw(2) << local_time.tm_sec
<< '.'
<< std::setw(6) << tv.tv_usec;
#elif defined(OS_WIN)
SYSTEMTIME local_time;
GetLocalTime(&local_time);
stream_ << std::setw(4) << local_time.wYear
<< std::setw(2) << local_time.wMonth
<< std::setw(2) << local_time.wDay
<< ','
<< std::setw(2) << local_time.wHour
<< std::setw(2) << local_time.wMinute
<< std::setw(2) << local_time.wSecond
<< '.'
<< std::setw(3) << local_time.wMilliseconds;
#endif
stream_ << ':';
if (severity_ >= 0) {
stream_ << log_severity_names[severity_];
} else {
stream_ << "VERBOSE" << -severity_;
}
stream_ << ' '
<< file_name
<< ':'
<< line_
<< "] ";
message_start_ = stream_.str().size();
}
#if defined(OS_WIN)
unsigned long GetLastSystemErrorCode() {
return GetLastError();
}
Win32ErrorLogMessage::Win32ErrorLogMessage(const char* function,
const char* file_path,
int line,
LogSeverity severity,
unsigned long err)
: LogMessage(function, file_path, line, severity), err_(err) {
}
Win32ErrorLogMessage::~Win32ErrorLogMessage() {
stream() << ": " << SystemErrorCodeToString(err_);
}
#elif defined(OS_POSIX)
ErrnoLogMessage::ErrnoLogMessage(const char* function,
const char* file_path,
int line,
LogSeverity severity,
int err)
: LogMessage(function, file_path, line, severity),
err_(err) {
}
ErrnoLogMessage::~ErrnoLogMessage() {
stream() << ": "
<< base::safe_strerror(err_)
<< " ("
<< err_
<< ")";
}
#endif // OS_POSIX
} // namespace logging
<commit_msg>mac: Log messages to the system log via ASL<commit_after>// Copyright 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/logging.h"
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
#if defined(OS_POSIX)
#include <paths.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include "base/posix/safe_strerror.h"
#endif // OS_POSIX
#if defined(OS_MACOSX)
#include <asl.h>
#include <CoreFoundation/CoreFoundation.h>
#include <pthread.h>
#elif defined(OS_LINUX)
#include <sys/syscall.h>
#include <sys/types.h>
#elif defined(OS_WIN)
#include <windows.h>
#endif
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
namespace logging {
namespace {
const char* const log_severity_names[] = {
"INFO",
"WARNING",
"ERROR",
"ERROR_REPORT",
"FATAL"
};
LogMessageHandlerFunction g_log_message_handler = nullptr;
} // namespace
void SetLogMessageHandler(LogMessageHandlerFunction log_message_handler) {
g_log_message_handler = log_message_handler;
}
LogMessageHandlerFunction GetLogMessageHandler() {
return g_log_message_handler;
}
#if defined(OS_WIN)
std::string SystemErrorCodeToString(unsigned long error_code) {
wchar_t msgbuf[256];
DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_MAX_WIDTH_MASK;
DWORD len = FormatMessage(
flags, nullptr, error_code, 0, msgbuf, arraysize(msgbuf), nullptr);
if (len) {
// Most system messages end in a period and a space. Remove the space if
// it’s there, because the following StringPrintf() includes one.
if (len >= 1 && msgbuf[len - 1] == ' ') {
msgbuf[len - 1] = '\0';
}
return base::StringPrintf("%s (%u)",
base::UTF16ToUTF8(msgbuf).c_str(), error_code);
}
return base::StringPrintf("Error %u while retrieving error %u",
GetLastError(),
error_code);
}
#endif // OS_WIN
LogMessage::LogMessage(const char* function,
const char* file_path,
int line,
LogSeverity severity)
: stream_(),
file_path_(file_path),
message_start_(0),
line_(line),
severity_(severity) {
Init(function);
}
LogMessage::LogMessage(const char* function,
const char* file_path,
int line,
std::string* result)
: stream_(),
file_path_(file_path),
message_start_(0),
line_(line),
severity_(LOG_FATAL) {
Init(function);
stream_ << "Check failed: " << *result << ". ";
delete result;
}
LogMessage::~LogMessage() {
stream_ << std::endl;
std::string str_newline(stream_.str());
if (g_log_message_handler &&
g_log_message_handler(
severity_, file_path_, line_, message_start_, str_newline)) {
return;
}
fprintf(stderr, "%s", str_newline.c_str());
fflush(stderr);
#if defined(OS_MACOSX)
const bool log_via_asl = []() {
struct stat stderr_stat;
if (fstat(fileno(stderr), &stderr_stat) == -1) {
return true;
}
if (!S_ISCHR(stderr_stat.st_mode)) {
return false;
}
struct stat dev_null_stat;
if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
return true;
}
return !S_ISCHR(dev_null_stat.st_mode) ||
stderr_stat.st_rdev == dev_null_stat.st_rdev;
}();
if (log_via_asl) {
CFBundleRef main_bundle = CFBundleGetMainBundle();
CFStringRef main_bundle_id_cf =
main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
std::string main_bundle_id_buf;
const char* asl_facility = nullptr;
if (main_bundle_id_cf) {
asl_facility =
CFStringGetCStringPtr(main_bundle_id_cf, kCFStringEncodingUTF8);
if (!asl_facility) {
// 1024 is from 10.10.5 CF-1153.18/CFBundle.c __CFBundleMainID__ (at
// the point of use, not declaration).
main_bundle_id_buf.resize(1024);
if (!CFStringGetCString(main_bundle_id_cf,
&main_bundle_id_buf[0],
main_bundle_id_buf.size(),
kCFStringEncodingUTF8)) {
main_bundle_id_buf.clear();
} else {
asl_facility = &main_bundle_id_buf[0];
}
}
}
if (!asl_facility) {
asl_facility = "com.apple.console";
}
class ASLClient {
public:
explicit ASLClient(const char* asl_facility)
: client_(asl_open(nullptr, asl_facility, ASL_OPT_NO_DELAY)) {}
~ASLClient() { asl_close(client_); }
aslclient get() const { return client_; }
private:
aslclient client_;
DISALLOW_COPY_AND_ASSIGN(ASLClient);
} asl_client(asl_facility);
class ASLMessage {
public:
ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
~ASLMessage() { asl_free(message_); }
aslmsg get() const { return message_; }
private:
aslmsg message_;
DISALLOW_COPY_AND_ASSIGN(ASLMessage);
} asl_message;
// By default, messages are only readable by the admin group. Explicitly
// make them readable by the user generating the messages.
char euid_string[12];
snprintf(euid_string, arraysize(euid_string), "%d", geteuid());
asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
// Map Chrome log severities to ASL log levels.
const char* const asl_level_string = [](LogSeverity severity) {
#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
#define ASL_LEVEL_STR_X(level) #level
switch (severity) {
case LOG_INFO:
return ASL_LEVEL_STR(ASL_LEVEL_INFO);
case LOG_WARNING:
return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
case LOG_ERROR:
return ASL_LEVEL_STR(ASL_LEVEL_ERR);
case LOG_FATAL:
return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
default:
return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
: ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
}
#undef ASL_LEVEL_STR
#undef ASL_LEVEL_STR_X
}(severity_);
asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
asl_send(asl_client.get(), asl_message.get());
}
#elif defined(OS_WIN)
OutputDebugString(base::UTF8ToUTF16(str_newline).c_str());
#endif // OS_MACOSX
if (severity_ == LOG_FATAL) {
#ifndef NDEBUG
abort();
#else
#if defined(OS_WIN)
__debugbreak();
#else
__asm__("int3");
#endif
#endif
}
}
void LogMessage::Init(const char* function) {
std::string file_name(file_path_);
#if defined(OS_WIN)
size_t last_slash = file_name.find_last_of("\\/");
#else
size_t last_slash = file_name.find_last_of('/');
#endif
if (last_slash != std::string::npos) {
file_name.assign(file_name.substr(last_slash + 1));
}
#if defined(OS_POSIX)
pid_t pid = getpid();
#elif defined(OS_WIN)
DWORD pid = GetCurrentProcessId();
#endif
#if defined(OS_MACOSX)
uint64_t thread;
pthread_threadid_np(pthread_self(), &thread);
#elif defined(OS_LINUX)
pid_t thread = syscall(__NR_gettid);
#elif defined(OS_WIN)
DWORD thread = GetCurrentThreadId();
#endif
stream_ << '['
<< pid
<< ':'
<< thread
<< ':'
<< std::setfill('0');
#if defined(OS_POSIX)
timeval tv;
gettimeofday(&tv, nullptr);
tm local_time;
localtime_r(&tv.tv_sec, &local_time);
stream_ << std::setw(4) << local_time.tm_year + 1900
<< std::setw(2) << local_time.tm_mon + 1
<< std::setw(2) << local_time.tm_mday
<< ','
<< std::setw(2) << local_time.tm_hour
<< std::setw(2) << local_time.tm_min
<< std::setw(2) << local_time.tm_sec
<< '.'
<< std::setw(6) << tv.tv_usec;
#elif defined(OS_WIN)
SYSTEMTIME local_time;
GetLocalTime(&local_time);
stream_ << std::setw(4) << local_time.wYear
<< std::setw(2) << local_time.wMonth
<< std::setw(2) << local_time.wDay
<< ','
<< std::setw(2) << local_time.wHour
<< std::setw(2) << local_time.wMinute
<< std::setw(2) << local_time.wSecond
<< '.'
<< std::setw(3) << local_time.wMilliseconds;
#endif
stream_ << ':';
if (severity_ >= 0) {
stream_ << log_severity_names[severity_];
} else {
stream_ << "VERBOSE" << -severity_;
}
stream_ << ' '
<< file_name
<< ':'
<< line_
<< "] ";
message_start_ = stream_.str().size();
}
#if defined(OS_WIN)
unsigned long GetLastSystemErrorCode() {
return GetLastError();
}
Win32ErrorLogMessage::Win32ErrorLogMessage(const char* function,
const char* file_path,
int line,
LogSeverity severity,
unsigned long err)
: LogMessage(function, file_path, line, severity), err_(err) {
}
Win32ErrorLogMessage::~Win32ErrorLogMessage() {
stream() << ": " << SystemErrorCodeToString(err_);
}
#elif defined(OS_POSIX)
ErrnoLogMessage::ErrnoLogMessage(const char* function,
const char* file_path,
int line,
LogSeverity severity,
int err)
: LogMessage(function, file_path, line, severity),
err_(err) {
}
ErrnoLogMessage::~ErrnoLogMessage() {
stream() << ": "
<< base::safe_strerror(err_)
<< " ("
<< err_
<< ")";
}
#endif // OS_POSIX
} // namespace logging
<|endoftext|> |
<commit_before>/***********************************************************************
filename: CEGuiOgreBaseApplication.cpp
created: 9/3/2004
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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.
***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
// this controls conditional compile of file for Apple
#include "CEGUISamplesConfig.h"
#ifdef CEGUI_SAMPLES_USE_OGRE
#include "CEGuiOgreBaseApplication.h"
#include "CEGuiSample.h"
#include <OgreKeyEvent.h>
CEGuiOgreBaseApplication::CEGuiOgreBaseApplication() :
d_ogreRoot(0),
d_renderer(0),
d_initialised(false),
d_frameListener(0)
{
using namespace Ogre;
d_ogreRoot = new Root();
initialiseResources();
if (d_ogreRoot->showConfigDialog())
{
// initialise system according to user options.
d_window = d_ogreRoot->initialise(true);
// Create and initialise the camera
d_camera = d_ogreRoot->getSceneManagerIterator().getNext()->createCamera("PlayerCam");
d_camera->setPosition(Vector3(0,0,500));
d_camera->lookAt(Vector3(0,0,-300));
d_camera->setNearClipDistance(5);
// Create a viewport covering whole window
Viewport* vp = d_window->addViewport(d_camera);
vp->setBackgroundColour(ColourValue(0,0,0));
// Update the camera aspect ratio to that of the viewport
d_camera->setAspectRatio(Real(vp->getActualWidth()) / Real(vp->getActualHeight()));
// initialise resources
ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
// initialise GUI system
d_renderer = new CEGUI::OgreCEGUIRenderer(d_window);
new CEGUI::System(d_renderer);
// create frame listener
d_frameListener= new CEGuiDemoFrameListener(this, d_window, d_camera);
d_ogreRoot->addFrameListener(d_frameListener);
d_initialised = true;
}
else
{
// aborted. Clean up and set root to 0 so when app attempts to run it knows what happened here.
delete d_ogreRoot;
d_ogreRoot = 0;
}
}
CEGuiOgreBaseApplication::~CEGuiOgreBaseApplication()
{
delete d_frameListener;
delete CEGUI::System::getSingletonPtr();
delete d_renderer;
delete d_ogreRoot;
}
bool CEGuiOgreBaseApplication::execute(CEGuiSample* sampleApp)
{
// if initialisation failed or was cancelled by user, bail out now.
if (d_ogreRoot && d_initialised)
{
// perform sample initialisation
sampleApp->initialiseSample();
// start rendering via Ogre3D engine.
try
{
d_ogreRoot->startRendering();
}
catch(Ogre::Exception&)
{
return false;
}
catch(CEGUI::Exception&)
{
return false;
}
return true;
}
else
{
return false;
}
}
void CEGuiOgreBaseApplication::cleanup()
{
// nothing to do here.
}
void CEGuiOgreBaseApplication::initialiseResources(void)
{
using namespace Ogre;
ResourceGroupManager& rgm = ResourceGroupManager::getSingleton();
// add resource groups that we use
rgm.createResourceGroup("imagesets");
rgm.createResourceGroup("fonts");
rgm.createResourceGroup("layouts");
rgm.createResourceGroup("schemes");
rgm.createResourceGroup("looknfeels");
// add CEGUI sample framework datafile dirs as resource locations
ResourceGroupManager::getSingleton().addResourceLocation("./", "FileSystem");
#ifndef __APPLE__
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/fonts", "FileSystem", "fonts");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/imagesets", "FileSystem", "imagesets");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/layouts", "FileSystem", "layouts");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/looknfeel", "FileSystem", "looknfeels");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/schemes", "FileSystem", "schemes");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/configs", "FileSystem");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/lua_scripts", "FileSystem");
#else
// Because Ogre/Mac looks in the bundle's Resources folder by default...
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/fonts", "FileSystem", "fonts");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/imagesets", "FileSystem", "imagesets");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/layouts", "FileSystem", "layouts");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/looknfeel", "FileSystem", "looknfeels");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/schemes", "FileSystem", "schemes");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/configs", "FileSystem");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/lua_scripts", "FileSystem");
#endif
}
////////////////////////////////////////////////////////////////////////////////
/*******************************************************************************
Start of CEGuiDemoFrameListener mehods
*******************************************************************************/
////////////////////////////////////////////////////////////////////////////////
CEGuiDemoFrameListener::CEGuiDemoFrameListener(CEGuiBaseApplication* baseApp, Ogre::RenderWindow* window, Ogre::Camera* camera, bool useBufferedInputKeys, bool useBufferedInputMouse)
{
// create and initialise events processor
d_eventProcessor = new Ogre::EventProcessor();
d_eventProcessor->initialise(window);
d_eventProcessor->addKeyListener(this);
d_eventProcessor->addMouseMotionListener(this);
d_eventProcessor->addMouseListener(this);
d_eventProcessor->startProcessingEvents();
// store inputs we want to make use of
d_camera = camera;
d_window = window;
// we've not quit yet.
d_quit = false;
// setup base app ptr
d_baseApp = baseApp;
}
CEGuiDemoFrameListener::~CEGuiDemoFrameListener()
{
delete d_eventProcessor;
}
bool CEGuiDemoFrameListener::frameStarted(const Ogre::FrameEvent& evt)
{
if(d_window->isClosed() || d_quit || d_baseApp->isQuitting())
{
return false;
}
else
{
// always inject a time pulse to enable widget automation
CEGUI::System::getSingleton().injectTimePulse(static_cast<float>(evt.timeSinceLastFrame));
return true;
}
}
bool CEGuiDemoFrameListener::frameEnded(const Ogre::FrameEvent& evt)
{
return true;
}
void CEGuiDemoFrameListener::mouseMoved(Ogre::MouseEvent *e)
{
CEGUI::Renderer* rend = CEGUI::System::getSingleton().getRenderer();
CEGUI::System::getSingleton().injectMouseMove(e->getRelX() * rend->getWidth(), e->getRelY() * rend->getHeight());
float wheel = e->getRelZ();
if (wheel != 0)
{
CEGUI::System::getSingleton().injectMouseWheelChange(wheel * 10);
}
e->consume();
}
void CEGuiDemoFrameListener::mouseDragged(Ogre::MouseEvent *e)
{
mouseMoved(e);
}
void CEGuiDemoFrameListener::keyPressed(Ogre::KeyEvent *e)
{
// give 'quitting' priority
if (e->getKey() == Ogre::KC_ESCAPE)
{
d_quit = true;
e->consume();
return;
}
// do event injection
CEGUI::System& cegui = CEGUI::System::getSingleton();
// key down
cegui.injectKeyDown(e->getKey());
// now character
cegui.injectChar(e->getKeyChar());
e->consume();
}
void CEGuiDemoFrameListener::keyReleased(Ogre::KeyEvent *e)
{
CEGUI::System::getSingleton().injectKeyUp(e->getKey());
}
void CEGuiDemoFrameListener::mousePressed(Ogre::MouseEvent *e)
{
CEGUI::System::getSingleton().injectMouseButtonDown(convertOgreButtonToCegui(e->getButtonID()));
e->consume();
}
void CEGuiDemoFrameListener::mouseReleased(Ogre::MouseEvent *e)
{
CEGUI::System::getSingleton().injectMouseButtonUp(convertOgreButtonToCegui(e->getButtonID()));
e->consume();
}
void CEGuiDemoFrameListener::keyClicked(Ogre::KeyEvent *e)
{}
void CEGuiDemoFrameListener::mouseClicked(Ogre::MouseEvent *e)
{}
void CEGuiDemoFrameListener::mouseEntered(Ogre::MouseEvent *e)
{}
void CEGuiDemoFrameListener::mouseExited(Ogre::MouseEvent *e)
{}
CEGUI::MouseButton CEGuiDemoFrameListener::convertOgreButtonToCegui(int ogre_button_id)
{
switch (ogre_button_id)
{
case Ogre::MouseEvent::BUTTON0_MASK:
return CEGUI::LeftButton;
break;
case Ogre::MouseEvent::BUTTON1_MASK:
return CEGUI::RightButton;
break;
case Ogre::MouseEvent::BUTTON2_MASK:
return CEGUI::MiddleButton;
break;
case Ogre::MouseEvent::BUTTON3_MASK:
return CEGUI::X1Button;
break;
default:
return CEGUI::LeftButton;
break;
}
}
#endif
<commit_msg>Bug Fix: Support was broken in the Samples framework for newer versions of Ogre.<commit_after>/***********************************************************************
filename: CEGuiOgreBaseApplication.cpp
created: 9/3/2004
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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.
***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
// this controls conditional compile of file for Apple
#include "CEGUISamplesConfig.h"
#ifdef CEGUI_SAMPLES_USE_OGRE
#include "CEGuiOgreBaseApplication.h"
#include "CEGuiSample.h"
#include <OgreKeyEvent.h>
CEGuiOgreBaseApplication::CEGuiOgreBaseApplication() :
d_ogreRoot(0),
d_renderer(0),
d_initialised(false),
d_frameListener(0)
{
using namespace Ogre;
d_ogreRoot = new Root();
initialiseResources();
if (d_ogreRoot->showConfigDialog())
{
// initialise system according to user options.
d_window = d_ogreRoot->initialise(true);
// Create the scene manager
SceneManager* sm = d_ogreRoot->
createSceneManager(ST_GENERIC, "SampleSceneMgr");
// Create and initialise the camera
d_camera = sm->createCamera("SampleCam");
d_camera->setPosition(Vector3(0,0,500));
d_camera->lookAt(Vector3(0,0,-300));
d_camera->setNearClipDistance(5);
// Create a viewport covering whole window
Viewport* vp = d_window->addViewport(d_camera);
vp->setBackgroundColour(ColourValue(0,0,0));
// Update the camera aspect ratio to that of the viewport
d_camera->setAspectRatio(Real(vp->getActualWidth()) / Real(vp->getActualHeight()));
// initialise resources
ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
// initialise GUI system
d_renderer = new CEGUI::OgreCEGUIRenderer(d_window, RENDER_QUEUE_OVERLAY, false, 0, sm);
new CEGUI::System(d_renderer);
// create frame listener
d_frameListener= new CEGuiDemoFrameListener(this, d_window, d_camera);
d_ogreRoot->addFrameListener(d_frameListener);
d_initialised = true;
}
else
{
// aborted. Clean up and set root to 0 so when app attempts to run it knows what happened here.
delete d_ogreRoot;
d_ogreRoot = 0;
}
}
CEGuiOgreBaseApplication::~CEGuiOgreBaseApplication()
{
delete d_frameListener;
delete CEGUI::System::getSingletonPtr();
delete d_renderer;
delete d_ogreRoot;
}
bool CEGuiOgreBaseApplication::execute(CEGuiSample* sampleApp)
{
// if initialisation failed or was cancelled by user, bail out now.
if (d_ogreRoot && d_initialised)
{
// perform sample initialisation
sampleApp->initialiseSample();
// start rendering via Ogre3D engine.
try
{
d_ogreRoot->startRendering();
}
catch(Ogre::Exception&)
{
return false;
}
catch(CEGUI::Exception&)
{
return false;
}
return true;
}
else
{
return false;
}
}
void CEGuiOgreBaseApplication::cleanup()
{
// nothing to do here.
}
void CEGuiOgreBaseApplication::initialiseResources(void)
{
using namespace Ogre;
ResourceGroupManager& rgm = ResourceGroupManager::getSingleton();
// add resource groups that we use
rgm.createResourceGroup("imagesets");
rgm.createResourceGroup("fonts");
rgm.createResourceGroup("layouts");
rgm.createResourceGroup("schemes");
rgm.createResourceGroup("looknfeels");
// add CEGUI sample framework datafile dirs as resource locations
ResourceGroupManager::getSingleton().addResourceLocation("./", "FileSystem");
#ifndef __APPLE__
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/fonts", "FileSystem", "fonts");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/imagesets", "FileSystem", "imagesets");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/layouts", "FileSystem", "layouts");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/looknfeel", "FileSystem", "looknfeels");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/schemes", "FileSystem", "schemes");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/configs", "FileSystem");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/lua_scripts", "FileSystem");
#else
// Because Ogre/Mac looks in the bundle's Resources folder by default...
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/fonts", "FileSystem", "fonts");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/imagesets", "FileSystem", "imagesets");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/layouts", "FileSystem", "layouts");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/looknfeel", "FileSystem", "looknfeels");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/schemes", "FileSystem", "schemes");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/configs", "FileSystem");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/lua_scripts", "FileSystem");
#endif
}
////////////////////////////////////////////////////////////////////////////////
/*******************************************************************************
Start of CEGuiDemoFrameListener mehods
*******************************************************************************/
////////////////////////////////////////////////////////////////////////////////
CEGuiDemoFrameListener::CEGuiDemoFrameListener(CEGuiBaseApplication* baseApp, Ogre::RenderWindow* window, Ogre::Camera* camera, bool useBufferedInputKeys, bool useBufferedInputMouse)
{
// create and initialise events processor
d_eventProcessor = new Ogre::EventProcessor();
d_eventProcessor->initialise(window);
d_eventProcessor->addKeyListener(this);
d_eventProcessor->addMouseMotionListener(this);
d_eventProcessor->addMouseListener(this);
d_eventProcessor->startProcessingEvents();
// store inputs we want to make use of
d_camera = camera;
d_window = window;
// we've not quit yet.
d_quit = false;
// setup base app ptr
d_baseApp = baseApp;
}
CEGuiDemoFrameListener::~CEGuiDemoFrameListener()
{
delete d_eventProcessor;
}
bool CEGuiDemoFrameListener::frameStarted(const Ogre::FrameEvent& evt)
{
if(d_window->isClosed() || d_quit || d_baseApp->isQuitting())
{
return false;
}
else
{
// always inject a time pulse to enable widget automation
CEGUI::System::getSingleton().injectTimePulse(static_cast<float>(evt.timeSinceLastFrame));
return true;
}
}
bool CEGuiDemoFrameListener::frameEnded(const Ogre::FrameEvent& evt)
{
return true;
}
void CEGuiDemoFrameListener::mouseMoved(Ogre::MouseEvent *e)
{
CEGUI::Renderer* rend = CEGUI::System::getSingleton().getRenderer();
CEGUI::System::getSingleton().injectMouseMove(e->getRelX() * rend->getWidth(), e->getRelY() * rend->getHeight());
float wheel = e->getRelZ();
if (wheel != 0)
{
CEGUI::System::getSingleton().injectMouseWheelChange(wheel * 10);
}
e->consume();
}
void CEGuiDemoFrameListener::mouseDragged(Ogre::MouseEvent *e)
{
mouseMoved(e);
}
void CEGuiDemoFrameListener::keyPressed(Ogre::KeyEvent *e)
{
// give 'quitting' priority
if (e->getKey() == Ogre::KC_ESCAPE)
{
d_quit = true;
e->consume();
return;
}
// do event injection
CEGUI::System& cegui = CEGUI::System::getSingleton();
// key down
cegui.injectKeyDown(e->getKey());
// now character
cegui.injectChar(e->getKeyChar());
e->consume();
}
void CEGuiDemoFrameListener::keyReleased(Ogre::KeyEvent *e)
{
CEGUI::System::getSingleton().injectKeyUp(e->getKey());
}
void CEGuiDemoFrameListener::mousePressed(Ogre::MouseEvent *e)
{
CEGUI::System::getSingleton().injectMouseButtonDown(convertOgreButtonToCegui(e->getButtonID()));
e->consume();
}
void CEGuiDemoFrameListener::mouseReleased(Ogre::MouseEvent *e)
{
CEGUI::System::getSingleton().injectMouseButtonUp(convertOgreButtonToCegui(e->getButtonID()));
e->consume();
}
void CEGuiDemoFrameListener::keyClicked(Ogre::KeyEvent *e)
{}
void CEGuiDemoFrameListener::mouseClicked(Ogre::MouseEvent *e)
{}
void CEGuiDemoFrameListener::mouseEntered(Ogre::MouseEvent *e)
{}
void CEGuiDemoFrameListener::mouseExited(Ogre::MouseEvent *e)
{}
CEGUI::MouseButton CEGuiDemoFrameListener::convertOgreButtonToCegui(int ogre_button_id)
{
switch (ogre_button_id)
{
case Ogre::MouseEvent::BUTTON0_MASK:
return CEGUI::LeftButton;
break;
case Ogre::MouseEvent::BUTTON1_MASK:
return CEGUI::RightButton;
break;
case Ogre::MouseEvent::BUTTON2_MASK:
return CEGUI::MiddleButton;
break;
case Ogre::MouseEvent::BUTTON3_MASK:
return CEGUI::X1Button;
break;
default:
return CEGUI::LeftButton;
break;
}
}
#endif
<|endoftext|> |
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXDE-Qt - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Razor team
* Authors:
* Alexander Sokoloff <sokoloff.a@gmail.com>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "plugin.h"
#include "ilxqtpanelplugin.h"
#include "lxqtpanel.h"
#include <QDebug>
#include <QProcessEnvironment>
#include <QStringList>
#include <QDir>
#include <QFileInfo>
#include <QPluginLoader>
#include <QGridLayout>
#include <QDialog>
#include <QEvent>
#include <QMenu>
#include <QMouseEvent>
#include <QApplication>
#include <QCryptographicHash>
#include <LXQt/Settings>
#include <LXQt/Translator>
#include <XdgIcon>
// statically linked built-in plugins
#include "../plugin-clock/lxqtclock.h" // clock
#include "../plugin-desktopswitch/desktopswitch.h" // desktopswitch
#include "../plugin-mainmenu/lxqtmainmenu.h" // mainmenu
#include "../plugin-quicklaunch/lxqtquicklaunchplugin.h" // quicklaunch
#include "../plugin-showdesktop/showdesktop.h" // showdesktop
#include "../plugin-taskbar/lxqttaskbarplugin.h" // taskbar
#include "../plugin-statusnotifier/statusnotifier.h" // statusnotifier
#include "../plugin-tray/lxqttrayplugin.h" // tray
#include "../plugin-worldclock/lxqtworldclock.h" // worldclock
QColor Plugin::mMoveMarkerColor= QColor(255, 0, 0, 255);
/************************************************
************************************************/
Plugin::Plugin(const LxQt::PluginInfo &desktopFile, const QString &settingsFile, const QString &settingsGroup, LxQtPanel *panel) :
QFrame(panel),
mDesktopFile(desktopFile),
mPluginLoader(0),
mPlugin(0),
mPluginWidget(0),
mAlignment(AlignLeft),
mSettingsGroup(settingsGroup),
mPanel(panel)
{
mSettings = new LxQt::Settings(settingsFile, QSettings::IniFormat, this);
connect(mSettings, SIGNAL(settingsChanged()), this, SLOT(settingsChanged()));
mSettings->beginGroup(settingsGroup);
mSettingsHash = calcSettingsHash();
setWindowTitle(desktopFile.name());
mName = desktopFile.name();
QStringList dirs;
dirs << QProcessEnvironment::systemEnvironment().value("LXQTPANEL_PLUGIN_PATH").split(":");
dirs << PLUGIN_DIR;
bool found = false;
if(ILxQtPanelPluginLibrary const * pluginLib = findStaticPlugin(desktopFile.id()))
{
// this is a static plugin
found = true;
loadLib(pluginLib);
}
else {
// this plugin is a dynamically loadable module
QString baseName = QString("lib%1.so").arg(desktopFile.id());
foreach(QString dirName, dirs)
{
QFileInfo fi(QDir(dirName), baseName);
if (fi.exists())
{
found = true;
if (loadModule(fi.absoluteFilePath()))
break;
}
}
}
if (!isLoaded())
{
if (!found)
qWarning() << QString("Plugin %1 not found in the").arg(desktopFile.id()) << dirs;
return;
}
// Load plugin translations
LxQt::Translator::translatePlugin(desktopFile.id(), QLatin1String("lxqt-panel"));
setObjectName(mPlugin->themeId() + "Plugin");
QString s = mSettings->value("alignment").toString();
// Retrun default value
if (s.isEmpty())
{
mAlignment = (mPlugin->flags().testFlag(ILxQtPanelPlugin::PreferRightAlignment)) ?
Plugin::AlignRight :
Plugin::AlignLeft;
}
else
{
mAlignment = (s.toUpper() == "RIGHT") ?
Plugin::AlignRight :
Plugin::AlignLeft;
}
if (mPluginWidget)
{
QGridLayout* layout = new QGridLayout(this);
layout->setSpacing(0);
layout->setMargin(0);
layout->setContentsMargins(0, 0, 0, 0);
setLayout(layout);
layout->addWidget(mPluginWidget, 0, 0);
}
saveSettings();
}
/************************************************
************************************************/
Plugin::~Plugin()
{
delete mPlugin;
if (mPluginLoader)
{
mPluginLoader->unload();
delete mPluginLoader;
}
}
void Plugin::setAlignment(Plugin::Alignment alignment)
{
mAlignment = alignment;
saveSettings();
}
/************************************************
************************************************/
ILxQtPanelPluginLibrary const * Plugin::findStaticPlugin(const QString &libraryName)
{
// find a static plugin library by name
// internally this is implemented using binary search
// statically linked built-in plugins
#if defined(WITH_CLOCK_PLUGIN)
static LxQtClockPluginLibrary clock_lib; // clock
#endif
#if defined(WITH_DESKTOPSWITCH_PLUGIN)
static DesktopSwitchPluginLibrary desktopswitch_lib; // desktopswitch
#endif
#if defined(WITH_MAINMENU_PLUGIN)
static LxQtMainMenuPluginLibrary mainmenu_lib; // mainmenu
#endif
#if defined(WITH_QUICKLAUNCH_PLUGIN)
static LxQtQuickLaunchPluginLibrary quicklaunch_lib; // quicklaunch
#endif
#if defined(WITH_SHOWDESKTOP_PLUGIN)
static ShowDesktopLibrary showdesktop_lib; //showdesktop
#endif
#if defined(WITH_TASKBAR_PLUGIN)
static LxQtTaskBarPluginLibrary taskbar_lib; //taskbar
#endif
#if defined(WITH_STATUSNOTIFIER_PLUGIN)
static StatusNotifierLibrary statusnotifier_lib; // statusnotifier
#endif
#if defined(WITH_TRAY_PLUGIN)
static LxQtTrayPluginLibrary tray_lib; //tray
#endif
#if defined(WITH_WORLDCLOCK_PLUGIN)
static LxQtWorldClockLibrary worldclock_lib; // worldclock
#endif
static const QString names[] = // the names should be kept sorted (for binary search)
{
QStringLiteral() //dummy first because of the next ifdefs
#if defined(WITH_CLOCK_PLUGIN)
, QStringLiteral("clock")
#endif
#if defined(WITH_DESKTOPSWITCH_PLUGIN)
, QStringLiteral("desktopswitch")
#endif
#if defined(WITH_MAINMENU_PLUGIN)
, QStringLiteral("mainmenu")
#endif
#if defined(WITH_QUICKLAUNCH_PLUGIN)
, QStringLiteral("quicklaunch")
#endif
#if defined(WITH_SHOWDESKTOP_PLUGIN)
, QStringLiteral("showdesktop")
#endif
#if defined(WITH_TASKBAR_PLUGIN)
, QStringLiteral("taskbar")
#endif
#if defined(WITH_STATUSNOTIFIER_PLUGIN)
, QStringLiteral("statusnotifier")
#endif
#if defined(WITH_TRAY_PLUGIN)
, QStringLiteral("tray")
#endif
#if defined(WITH_WORLDCLOCK_PLUGIN)
, QStringLiteral("worldclock")
#endif
};
static ILxQtPanelPluginLibrary* staticPlugins[] = // should be kept in the same order as names
{
nullptr //dummy first because of the next ifdefs
#if defined(WITH_CLOCK_PLUGIN)
, &clock_lib
#endif
#if defined(WITH_DESKTOPSWITCH_PLUGIN)
, &desktopswitch_lib
#endif
#if defined(WITH_MAINMENU_PLUGIN)
, &mainmenu_lib
#endif
#if defined(WITH_QUICKLAUNCH_PLUGIN)
, &quicklaunch_lib
#endif
#if defined(WITH_SHOWDESKTOP_PLUGIN)
, &showdesktop_lib
#endif
#if defined(WITH_TASKBAR_PLUGIN)
, &taskbar_lib
#endif
#if defined(WITH_STATUSNOTIFIER_PLUGIN)
, &statusnotifier_lib
#endif
#if defined(WITH_TRAY_PLUGIN)
, &tray_lib
#endif
#if defined(WITH_WORLDCLOCK_PLUGIN)
, &worldclock_lib
#endif
};
for (unsigned i = 1/*dummy first*/; i < sizeof(names) / sizeof(QString); i++)
if (names[i] == libraryName)
return staticPlugins[i];
return NULL;
}
// load a plugin from a library
bool Plugin::loadLib(ILxQtPanelPluginLibrary const * pluginLib)
{
ILxQtPanelPluginStartupInfo startupInfo;
startupInfo.settings = mSettings;
startupInfo.desktopFile = &mDesktopFile;
startupInfo.lxqtPanel = mPanel;
mPlugin = pluginLib->instance(startupInfo);
if (!mPlugin)
{
qWarning() << QString("Can't load plugin \"%1\". Plugin can't build ILxQtPanelPlugin.").arg(mPluginLoader->fileName());
return false;
}
mPluginWidget = mPlugin->widget();
if (mPluginWidget)
{
mPluginWidget->setObjectName(mPlugin->themeId());
}
this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
return true;
}
// load dynamic plugin from a *.so module
bool Plugin::loadModule(const QString &libraryName)
{
mPluginLoader = new QPluginLoader(libraryName);
if (!mPluginLoader->load())
{
qWarning() << mPluginLoader->errorString();
return false;
}
QObject *obj = mPluginLoader->instance();
if (!obj)
{
qWarning() << mPluginLoader->errorString();
return false;
}
ILxQtPanelPluginLibrary* pluginLib= qobject_cast<ILxQtPanelPluginLibrary*>(obj);
if (!pluginLib)
{
qWarning() << QString("Can't load plugin \"%1\". Plugin is not a ILxQtPanelPluginLibrary.").arg(mPluginLoader->fileName());
delete obj;
return false;
}
return loadLib(pluginLib);
}
/************************************************
************************************************/
QByteArray Plugin::calcSettingsHash()
{
QCryptographicHash hash(QCryptographicHash::Md5);
QStringList keys = mSettings->allKeys();
foreach (const QString &key, keys)
{
hash.addData(key.toUtf8());
hash.addData(mSettings->value(key).toByteArray());
}
return hash.result();
}
/************************************************
************************************************/
void Plugin::settingsChanged()
{
QByteArray hash = calcSettingsHash();
if (mSettingsHash != hash)
{
mSettingsHash = hash;
mPlugin->settingsChanged();
}
}
/************************************************
************************************************/
void Plugin::saveSettings()
{
mSettings->setValue("alignment", (mAlignment == AlignLeft) ? "Left" : "Right");
mSettings->setValue("type", mDesktopFile.id());
mSettings->sync();
}
/************************************************
************************************************/
void Plugin::contextMenuEvent(QContextMenuEvent *event)
{
mPanel->showPopupMenu(this);
}
/************************************************
************************************************/
void Plugin::mousePressEvent(QMouseEvent *event)
{
switch (event->button())
{
case Qt::LeftButton:
mPlugin->activated(ILxQtPanelPlugin::Trigger);
break;
case Qt::MidButton:
mPlugin->activated(ILxQtPanelPlugin::MiddleClick);
break;
default:
break;
}
}
/************************************************
************************************************/
void Plugin::mouseDoubleClickEvent(QMouseEvent*)
{
mPlugin->activated(ILxQtPanelPlugin::DoubleClick);
}
/************************************************
************************************************/
void Plugin::showEvent(QShowEvent *)
{
if (mPluginWidget)
mPluginWidget->adjustSize();
}
/************************************************
************************************************/
QMenu *Plugin::popupMenu() const
{
QString name = this->name().replace("&", "&&");
QMenu* menu = new QMenu(windowTitle());
if (mPlugin->flags().testFlag(ILxQtPanelPlugin::HaveConfigDialog))
{
QAction* configAction = new QAction(
XdgIcon::fromTheme(QStringLiteral("preferences-other")),
tr("Configure \"%1\"").arg(name), menu);
menu->addAction(configAction);
connect(configAction, SIGNAL(triggered()), this, SLOT(showConfigureDialog()));
}
QAction* moveAction = new QAction(XdgIcon::fromTheme("transform-move"), tr("Move \"%1\"").arg(name), menu);
menu->addAction(moveAction);
connect(moveAction, SIGNAL(triggered()), this, SIGNAL(startMove()));
menu->addSeparator();
QAction* removeAction = new QAction(
XdgIcon::fromTheme(QStringLiteral("list-remove")),
tr("Remove \"%1\"").arg(name), menu);
menu->addAction(removeAction);
connect(removeAction, SIGNAL(triggered()), this, SLOT(requestRemove()));
return menu;
}
/************************************************
************************************************/
bool Plugin::isSeparate() const
{
return mPlugin->isSeparate();
}
/************************************************
************************************************/
bool Plugin::isExpandable() const
{
return mPlugin->isExpandable();
}
/************************************************
************************************************/
void Plugin::realign()
{
if (mPlugin)
mPlugin->realign();
}
/************************************************
************************************************/
void Plugin::showConfigureDialog()
{
// store a pointer to each plugin using the plugins' names
static QHash<QString, QPointer<QDialog> > refs;
QDialog *dialog = refs[name()].data();
if (!dialog)
{
dialog = mPlugin->configureDialog();
refs[name()] = dialog;
connect(this, SIGNAL(destroyed()), dialog, SLOT(close()));
}
if (!dialog)
return;
dialog->show();
dialog->raise();
dialog->activateWindow();
}
/************************************************
************************************************/
void Plugin::requestRemove()
{
emit remove();
deleteLater();
}
<commit_msg>plugins: static plugins initialization on one place<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXDE-Qt - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Razor team
* Authors:
* Alexander Sokoloff <sokoloff.a@gmail.com>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "plugin.h"
#include "ilxqtpanelplugin.h"
#include "lxqtpanel.h"
#include <QDebug>
#include <QProcessEnvironment>
#include <QStringList>
#include <QDir>
#include <QFileInfo>
#include <QPluginLoader>
#include <QGridLayout>
#include <QDialog>
#include <QEvent>
#include <QMenu>
#include <QMouseEvent>
#include <QApplication>
#include <QCryptographicHash>
#include <memory>
#include <LXQt/Settings>
#include <LXQt/Translator>
#include <XdgIcon>
// statically linked built-in plugins
#include "../plugin-clock/lxqtclock.h" // clock
#include "../plugin-desktopswitch/desktopswitch.h" // desktopswitch
#include "../plugin-mainmenu/lxqtmainmenu.h" // mainmenu
#include "../plugin-quicklaunch/lxqtquicklaunchplugin.h" // quicklaunch
#include "../plugin-showdesktop/showdesktop.h" // showdesktop
#include "../plugin-taskbar/lxqttaskbarplugin.h" // taskbar
#include "../plugin-statusnotifier/statusnotifier.h" // statusnotifier
#include "../plugin-tray/lxqttrayplugin.h" // tray
#include "../plugin-worldclock/lxqtworldclock.h" // worldclock
QColor Plugin::mMoveMarkerColor= QColor(255, 0, 0, 255);
/************************************************
************************************************/
Plugin::Plugin(const LxQt::PluginInfo &desktopFile, const QString &settingsFile, const QString &settingsGroup, LxQtPanel *panel) :
QFrame(panel),
mDesktopFile(desktopFile),
mPluginLoader(0),
mPlugin(0),
mPluginWidget(0),
mAlignment(AlignLeft),
mSettingsGroup(settingsGroup),
mPanel(panel)
{
mSettings = new LxQt::Settings(settingsFile, QSettings::IniFormat, this);
connect(mSettings, SIGNAL(settingsChanged()), this, SLOT(settingsChanged()));
mSettings->beginGroup(settingsGroup);
mSettingsHash = calcSettingsHash();
setWindowTitle(desktopFile.name());
mName = desktopFile.name();
QStringList dirs;
dirs << QProcessEnvironment::systemEnvironment().value("LXQTPANEL_PLUGIN_PATH").split(":");
dirs << PLUGIN_DIR;
bool found = false;
if(ILxQtPanelPluginLibrary const * pluginLib = findStaticPlugin(desktopFile.id()))
{
// this is a static plugin
found = true;
loadLib(pluginLib);
}
else {
// this plugin is a dynamically loadable module
QString baseName = QString("lib%1.so").arg(desktopFile.id());
foreach(QString dirName, dirs)
{
QFileInfo fi(QDir(dirName), baseName);
if (fi.exists())
{
found = true;
if (loadModule(fi.absoluteFilePath()))
break;
}
}
}
if (!isLoaded())
{
if (!found)
qWarning() << QString("Plugin %1 not found in the").arg(desktopFile.id()) << dirs;
return;
}
// Load plugin translations
LxQt::Translator::translatePlugin(desktopFile.id(), QLatin1String("lxqt-panel"));
setObjectName(mPlugin->themeId() + "Plugin");
QString s = mSettings->value("alignment").toString();
// Retrun default value
if (s.isEmpty())
{
mAlignment = (mPlugin->flags().testFlag(ILxQtPanelPlugin::PreferRightAlignment)) ?
Plugin::AlignRight :
Plugin::AlignLeft;
}
else
{
mAlignment = (s.toUpper() == "RIGHT") ?
Plugin::AlignRight :
Plugin::AlignLeft;
}
if (mPluginWidget)
{
QGridLayout* layout = new QGridLayout(this);
layout->setSpacing(0);
layout->setMargin(0);
layout->setContentsMargins(0, 0, 0, 0);
setLayout(layout);
layout->addWidget(mPluginWidget, 0, 0);
}
saveSettings();
}
/************************************************
************************************************/
Plugin::~Plugin()
{
delete mPlugin;
if (mPluginLoader)
{
mPluginLoader->unload();
delete mPluginLoader;
}
}
void Plugin::setAlignment(Plugin::Alignment alignment)
{
mAlignment = alignment;
saveSettings();
}
/************************************************
************************************************/
namespace
{
//helper types for static plugins storage & binary search
typedef std::unique_ptr<ILxQtPanelPluginLibrary> plugin_ptr_t;
typedef std::pair<QString, plugin_ptr_t > plugin_pair_t;
//NOTE: Please keep the plugins sorted by name while adding new plugins.
static plugin_pair_t const static_plugins[] = {
#if defined(WITH_CLOCK_PLUGIN)
{ QStringLiteral("clock"), plugin_ptr_t{new LxQtClockPluginLibrary} },// clock
#endif
#if defined(WITH_DESKTOPSWITCH_PLUGIN)
{ QStringLiteral("desktopswitch"), plugin_ptr_t{new DesktopSwitchPluginLibrary} },// desktopswitch
#endif
#if defined(WITH_MAINMENU_PLUGIN)
{ QStringLiteral("mainmenu"), plugin_ptr_t{new LxQtMainMenuPluginLibrary} },// mainmenu
#endif
#if defined(WITH_QUICKLAUNCH_PLUGIN)
{ QStringLiteral("quicklaunch"), plugin_ptr_t{new LxQtQuickLaunchPluginLibrary} },// quicklaunch
#endif
#if defined(WITH_SHOWDESKTOP_PLUGIN)
{ QStringLiteral("showdesktop"), plugin_ptr_t{new ShowDesktopLibrary} },//showdesktop
#endif
#if defined(WITH_STATUSNOTIFIER_PLUGIN)
{ QStringLiteral("statusnotifier"), plugin_ptr_t{new StatusNotifierLibrary} },// statusnotifier
#endif
#if defined(WITH_TASKBAR_PLUGIN)
{ QStringLiteral("taskbar"), plugin_ptr_t{new LxQtTaskBarPluginLibrary} },//taskbar
#endif
#if defined(WITH_TRAY_PLUGIN)
{ QStringLiteral("tray"), plugin_ptr_t{new LxQtTrayPluginLibrary} },//tray
#endif
#if defined(WITH_WORLDCLOCK_PLUGIN)
{ QStringLiteral("worldclock"), plugin_ptr_t{new LxQtWorldClockLibrary} },// worldclock
#endif
};
static constexpr plugin_pair_t const * const plugins_begin = static_plugins;
static constexpr plugin_pair_t const * const plugins_end = static_plugins + sizeof (static_plugins) / sizeof (static_plugins[0]);
struct assert_helper
{
assert_helper()
{
Q_ASSERT(std::is_sorted(plugins_begin, plugins_end
, [] (plugin_pair_t const & p1, plugin_pair_t const & p2) -> bool { return p1.first < p2.first; }));
}
};
static assert_helper h;
}
ILxQtPanelPluginLibrary const * Plugin::findStaticPlugin(const QString &libraryName)
{
// find a static plugin library by name -> binary search
plugin_pair_t const * plugin = std::lower_bound(plugins_begin, plugins_end, libraryName
, [] (plugin_pair_t const & plugin, QString const & name) -> bool { return plugin.first < name; });
if (plugins_end != plugin && libraryName == plugin->first)
return plugin->second.get();
return nullptr;
}
// load a plugin from a library
bool Plugin::loadLib(ILxQtPanelPluginLibrary const * pluginLib)
{
ILxQtPanelPluginStartupInfo startupInfo;
startupInfo.settings = mSettings;
startupInfo.desktopFile = &mDesktopFile;
startupInfo.lxqtPanel = mPanel;
mPlugin = pluginLib->instance(startupInfo);
if (!mPlugin)
{
qWarning() << QString("Can't load plugin \"%1\". Plugin can't build ILxQtPanelPlugin.").arg(mPluginLoader->fileName());
return false;
}
mPluginWidget = mPlugin->widget();
if (mPluginWidget)
{
mPluginWidget->setObjectName(mPlugin->themeId());
}
this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
return true;
}
// load dynamic plugin from a *.so module
bool Plugin::loadModule(const QString &libraryName)
{
mPluginLoader = new QPluginLoader(libraryName);
if (!mPluginLoader->load())
{
qWarning() << mPluginLoader->errorString();
return false;
}
QObject *obj = mPluginLoader->instance();
if (!obj)
{
qWarning() << mPluginLoader->errorString();
return false;
}
ILxQtPanelPluginLibrary* pluginLib= qobject_cast<ILxQtPanelPluginLibrary*>(obj);
if (!pluginLib)
{
qWarning() << QString("Can't load plugin \"%1\". Plugin is not a ILxQtPanelPluginLibrary.").arg(mPluginLoader->fileName());
delete obj;
return false;
}
return loadLib(pluginLib);
}
/************************************************
************************************************/
QByteArray Plugin::calcSettingsHash()
{
QCryptographicHash hash(QCryptographicHash::Md5);
QStringList keys = mSettings->allKeys();
foreach (const QString &key, keys)
{
hash.addData(key.toUtf8());
hash.addData(mSettings->value(key).toByteArray());
}
return hash.result();
}
/************************************************
************************************************/
void Plugin::settingsChanged()
{
QByteArray hash = calcSettingsHash();
if (mSettingsHash != hash)
{
mSettingsHash = hash;
mPlugin->settingsChanged();
}
}
/************************************************
************************************************/
void Plugin::saveSettings()
{
mSettings->setValue("alignment", (mAlignment == AlignLeft) ? "Left" : "Right");
mSettings->setValue("type", mDesktopFile.id());
mSettings->sync();
}
/************************************************
************************************************/
void Plugin::contextMenuEvent(QContextMenuEvent *event)
{
mPanel->showPopupMenu(this);
}
/************************************************
************************************************/
void Plugin::mousePressEvent(QMouseEvent *event)
{
switch (event->button())
{
case Qt::LeftButton:
mPlugin->activated(ILxQtPanelPlugin::Trigger);
break;
case Qt::MidButton:
mPlugin->activated(ILxQtPanelPlugin::MiddleClick);
break;
default:
break;
}
}
/************************************************
************************************************/
void Plugin::mouseDoubleClickEvent(QMouseEvent*)
{
mPlugin->activated(ILxQtPanelPlugin::DoubleClick);
}
/************************************************
************************************************/
void Plugin::showEvent(QShowEvent *)
{
if (mPluginWidget)
mPluginWidget->adjustSize();
}
/************************************************
************************************************/
QMenu *Plugin::popupMenu() const
{
QString name = this->name().replace("&", "&&");
QMenu* menu = new QMenu(windowTitle());
if (mPlugin->flags().testFlag(ILxQtPanelPlugin::HaveConfigDialog))
{
QAction* configAction = new QAction(
XdgIcon::fromTheme(QStringLiteral("preferences-other")),
tr("Configure \"%1\"").arg(name), menu);
menu->addAction(configAction);
connect(configAction, SIGNAL(triggered()), this, SLOT(showConfigureDialog()));
}
QAction* moveAction = new QAction(XdgIcon::fromTheme("transform-move"), tr("Move \"%1\"").arg(name), menu);
menu->addAction(moveAction);
connect(moveAction, SIGNAL(triggered()), this, SIGNAL(startMove()));
menu->addSeparator();
QAction* removeAction = new QAction(
XdgIcon::fromTheme(QStringLiteral("list-remove")),
tr("Remove \"%1\"").arg(name), menu);
menu->addAction(removeAction);
connect(removeAction, SIGNAL(triggered()), this, SLOT(requestRemove()));
return menu;
}
/************************************************
************************************************/
bool Plugin::isSeparate() const
{
return mPlugin->isSeparate();
}
/************************************************
************************************************/
bool Plugin::isExpandable() const
{
return mPlugin->isExpandable();
}
/************************************************
************************************************/
void Plugin::realign()
{
if (mPlugin)
mPlugin->realign();
}
/************************************************
************************************************/
void Plugin::showConfigureDialog()
{
// store a pointer to each plugin using the plugins' names
static QHash<QString, QPointer<QDialog> > refs;
QDialog *dialog = refs[name()].data();
if (!dialog)
{
dialog = mPlugin->configureDialog();
refs[name()] = dialog;
connect(this, SIGNAL(destroyed()), dialog, SLOT(close()));
}
if (!dialog)
return;
dialog->show();
dialog->raise();
dialog->activateWindow();
}
/************************************************
************************************************/
void Plugin::requestRemove()
{
emit remove();
deleteLater();
}
<|endoftext|> |
<commit_before>/*
Dune II - The Maker
Author : Stefan Hendriks
Contact: stefanhen83@gmail.com
Website: http://d2tm.duneii.com
2001 - 2009 (c) code by Stefan Hendriks
-----------------------------------------------
Game menu items
-----------------------------------------------
*/
#include "d2tmh.h"
// Fading between menu items
void cGame::FADE_OUT()
{
iFadeAction = 1; // fade out
draw_sprite(bmp_fadeout, bmp_screen, 0, 0);
}
// Drawing of any movie/scene loaded
void cGame::draw_movie(int iType)
{
if (gfxmovie != NULL && iMovieFrame > -1)
{
// drawing only, circulating is done in think function
draw_sprite(bmp_screen, (BITMAP *)gfxmovie[iMovieFrame].dat, 256, 120);
}
}
// draw the message
void cGame::draw_message()
{
if (iMessageAlpha > -1)
{
set_trans_blender(0,0,0,iMessageAlpha);
BITMAP *temp = create_bitmap(480,30);
clear_bitmap(temp);
rectfill(temp, 0,0,480,40, makecol(255,0,255));
draw_sprite(temp, (BITMAP *)gfxinter[BMP_MESSAGEBAR].dat, 0,0);
// draw message
// alfont_textprintf(temp, game_font, 13,7, makecol(0,0,0), cMessage);
alfont_textprintf(temp, game_font, 13,21, makecol(0,0,0), cMessage);
//alfont_textprintf_aa(temp, game_font, 13,21, makecol(1,1,1), cMessage);
// draw temp
draw_trans_sprite(bmp_screen, temp, 1, 42);
destroy_bitmap(temp);
}
}
void cGame::draw_order()
{
// draw order button
if (iActiveList != LIST_STARPORT)
return;
bool bMouseHover=false;
// determine if mouse is over the button..
if ( (mouse_x > 29 && mouse_x < 187) && (mouse_y > 2 && mouse_y < 31))
bMouseHover=true;
bool bDrawOrder=false;
// we ordered stuff
for (int i = 0; i < MAX_ICONS; i++)
{
if (iconFrigate[i] > 0)
bDrawOrder=true;
}
if (TIMER_ordered > -1)
bDrawOrder=false; // grey
if (TIMER_mayorder > -1)
bDrawOrder=false;
if (bDrawOrder)
{
draw_sprite(bmp_screen, (BITMAP *)gfxinter[BTN_ORDER].dat, 29, 0);
}
else
{
// clear
BITMAP *bmp_trans=create_bitmap(((BITMAP *)gfxinter[BTN_ORDER].dat)->w,((BITMAP *)gfxinter[BTN_ORDER].dat)->h);
clear_to_color(bmp_trans, makecol(255,0,255));
// copy
draw_sprite(bmp_trans, (BITMAP *)gfxinter[BTN_ORDER].dat, 0, 0);
// make black
rectfill(bmp_screen, 29, 0, 187, 29, makecol(0,0,0));
// set blender
//set_trans_blender(0,0,0,128);
// trans
fblend_trans(bmp_trans, bmp_screen, 29, 0, 128);
//draw_trans_sprite(bmp_screen, bmp_trans, 29, 0);
// destroy - phew
destroy_bitmap(bmp_trans);
// rectfill(bmp_screen, 29, 0, 187, 29, makecol(0,0,0));
// set_trans_blender(0,0,0,128);
// draw_trans_sprite(bmp_screen, (BITMAP *)gfxinter[BTN_ORDER].dat, 29, 0);
//draw_sprite(bmp_screen, (BITMAP *)gfxinter[BTN_ORDER_GREY].dat, 29, 0);
}
// react on mouse
if (bMouseHover && bDrawOrder)
{
if (bMousePressedLeft)
{
TIMER_ordered=30; // 30 seconds
}
}
}
void cGame::draw_upgrade()
{
bool bDrawUpgradeButton=false;
bool bMouseHover=false;
int iLimit=0;
int iType=-1;
int iPrice=-1;
int iDrawXLimit=-1;
if (iActiveList == LIST_NONE)
return; // nothing selected, so nothing to upgrade
// determine if mouse is over the button..
if ( (mouse_x > 29 && mouse_x < 187) && (mouse_y > 2 && mouse_y < 31))
if (iconbuilding[iActiveList] < 0) // not building, then we may do this
bMouseHover=true;
// determine what list is selected
////////////////////////
/// CONSTRUCTION YARD UPGRADING
////////////////////////
if (iActiveList == LIST_CONSTYARD)
{
iType=CONSTYARD;
// first upgrade
if (iStructureUpgrade[CONSTYARD] == 0 && iMission >= 4)
{
bDrawUpgradeButton=true;
if (iUpgradeProgress[CONSTYARD] < 0)
{
// when mission 4 or higher, show upgrade button
// * upgrade is for 4 slabs
iLimit=10;
iPrice=200;
}
}
// second upgrade
// * Upgrade for Rocket Turret, but only when we have radar
if (iStructureUpgrade[CONSTYARD] == 1 && iMission >= 6 &&
player[0].iStructures[RADAR] > 0)
{
bDrawUpgradeButton=true;
if (iUpgradeProgress[CONSTYARD] < 0)
{
// when mission 4 or higher, show upgrade button
// * upgrade is for 4 slabs
iLimit=50;
iPrice=400;
}
}
}
////////////////////////
/// LIGHTFACTORY UPGRADING
////////////////////////
if (iActiveList == LIST_LIGHTFC)
{
// Lightfactory upgrading is done only for house Atreides and Ordos
iType=LIGHTFACTORY;
// first upgrade
if (iStructureUpgrade[LIGHTFACTORY] == 0 && iMission >= 2)
{
bDrawUpgradeButton=true;
if (iUpgradeProgress[LIGHTFACTORY] < 0)
{
// * upgrade for Quad
iLimit=50;
iPrice=500;
}
}
}
////////////////////////
/// BARRACKS/WOR UPGRADING
////////////////////////
if (iActiveList == LIST_INFANTRY)
{
// Lightfactory upgrading is done only for house Atreides and Ordos
if (player[0].house == ATREIDES ||
player[0].house == ORDOS)
iType=BARRACKS; // Note: ordos uses also wor, so this is also for wor!!
else
iType=WOR;
// first upgrade
if (iStructureUpgrade[iType] == 0 && iMission >= 2)
{
bDrawUpgradeButton=true;
if (iUpgradeProgress[iType] < 0)
{
// * upgrade for TROOPERS
iLimit=30;
iPrice=150;
if (iHouse == ORDOS)
{
iLimit=60;
iPrice=300; // double the price
}
}
}
}
////////////////////////
/// ORNI UPGRADING
////////////////////////
if (iActiveList == LIST_ORNI && player[0].house != HARKONNEN)
{
// Lightfactory upgrading is done only for house Atreides and Ordos
iType=HIGHTECH;
// first upgrade
if (iStructureUpgrade[HIGHTECH] == 0 && iMission >= 6)
{
bDrawUpgradeButton=true;
if (iUpgradeProgress[HIGHTECH] < 0)
{
// * upgrade for ORNI
iLimit=100;
iPrice=700;
}
}
}
////////////////////////
/// HEAVYFACTORY UPGRADING
////////////////////////
if (iActiveList == LIST_HEAVYFC)
{
// Lightfactory upgrading is done only for house Atreides and Ordos
iType=HEAVYFACTORY;
// first upgrade
if (iStructureUpgrade[HEAVYFACTORY] == 0 && iMission >= 4)
{
bDrawUpgradeButton=true;
if (iUpgradeProgress[HEAVYFACTORY] < 0)
{
// * upgrade for MCV
iLimit=60;
iPrice=500;
}
}
if (iStructureUpgrade[HEAVYFACTORY] == 1 && iMission >= 5)
{
bDrawUpgradeButton=true;
if (iUpgradeProgress[HEAVYFACTORY] < 0)
{
// * upgrade for LAUNCHER
iLimit=80;
iPrice=500;
}
}
if (iStructureUpgrade[HEAVYFACTORY] == 2 && iMission >= 6)
{
bDrawUpgradeButton=true;
if (iUpgradeProgress[HEAVYFACTORY] < 0)
{
// * upgrade for SIEGE
iLimit=100;
iPrice=700;
}
}
if (iStructureUpgrade[HEAVYFACTORY] == 3 && iMission >= 7 &&
player[0].iStructures[IX] > 0) // AND we do own a house of IX
{
bDrawUpgradeButton=true;
if (iUpgradeProgress[HEAVYFACTORY] < 0)
{
// * upgrade for SPECIAL WEAPON
iLimit=120;
iPrice=1000;
}
}
}
if (bMouseHover && bDrawUpgradeButton && iPrice > -1)
{
char msg[255];
sprintf(msg, "$%d | Upgrade (Shortkey 'U')", iPrice);
set_message(msg);
}
// Start upgrading sequence when pressing button and such
if (bDrawUpgradeButton)
if (iconbuilding[iActiveList] < 0 || player[0].credits < iPrice)
{
draw_sprite(bmp_screen, (BITMAP *)gfxinter[BTN_UPGRADE].dat, 29, 0);
bool bUpgrade=false;
if (bMousePressedLeft && bMouseHover)
bUpgrade=true;
if (key[KEY_U] && iUpgradeProgressLimit[iType] <= 0)
bUpgrade=true;
if (bUpgrade) // able to press button, valid and enough money
if (iType > -1 && player[0].credits >= iPrice)
{
iUpgradeTIMER[iType]=0;
iUpgradeProgress[iType]=0;
iUpgradeProgressLimit[iType]=iLimit;
player[0].credits -= iPrice;
}
}
else
{
// clear
BITMAP *bmp_trans=create_bitmap(((BITMAP *)gfxinter[BTN_UPGRADE].dat)->w,((BITMAP *)gfxinter[BTN_UPGRADE].dat)->h);
clear_to_color(bmp_trans, makecol(255,0,255));
// copy
draw_sprite(bmp_trans, (BITMAP *)gfxinter[BTN_UPGRADE].dat, 0, 0);
// make black
rectfill(bmp_screen, 29, 0, 187, 29, makecol(0,0,0));
// set blender
set_trans_blender(0,0,0,128);
// trans
draw_trans_sprite(bmp_screen, bmp_trans, 29, 0);
// destroy - phew
destroy_bitmap(bmp_trans);
}
// Draw progress bar
if (iType > -1 && iUpgradeProgress[iType] > -1)
{
iDrawXLimit = health_bar(157, iUpgradeProgress[iType], iUpgradeProgressLimit[iType]);
if (iDrawXLimit > -1)
{
int iColor=makecol(255,255,255);
BITMAP *temp = create_bitmap(157, 28);
clear_to_color(temp, makecol(255,0,255));
if (player[0].house == ATREIDES) iColor = makecol(0,0,255);
if (player[0].house == HARKONNEN) iColor = makecol(255,0,0);
if (player[0].house == ORDOS) iColor = makecol(0,255,0);
if (player[0].house == SARDAUKAR) iColor = makecol(255,0,255);
rectfill(temp, 0, 0, (157-iDrawXLimit), 30, iColor);
draw_trans_sprite(bmp_screen, temp, 30, 1);
destroy_bitmap(temp);
}
}
} // end of function
<commit_msg>- Fix bug: Upgrade completes when clicked, and clicked again. Reported by Gunner154<commit_after>/*
Dune II - The Maker
Author : Stefan Hendriks
Contact: stefanhen83@gmail.com
Website: http://d2tm.duneii.com
2001 - 2009 (c) code by Stefan Hendriks
-----------------------------------------------
Game menu items
-----------------------------------------------
*/
#include "d2tmh.h"
// Fading between menu items
void cGame::FADE_OUT()
{
iFadeAction = 1; // fade out
draw_sprite(bmp_fadeout, bmp_screen, 0, 0);
}
// Drawing of any movie/scene loaded
void cGame::draw_movie(int iType)
{
if (gfxmovie != NULL && iMovieFrame > -1)
{
// drawing only, circulating is done in think function
draw_sprite(bmp_screen, (BITMAP *)gfxmovie[iMovieFrame].dat, 256, 120);
}
}
// draw the message
void cGame::draw_message()
{
if (iMessageAlpha > -1)
{
set_trans_blender(0,0,0,iMessageAlpha);
BITMAP *temp = create_bitmap(480,30);
clear_bitmap(temp);
rectfill(temp, 0,0,480,40, makecol(255,0,255));
draw_sprite(temp, (BITMAP *)gfxinter[BMP_MESSAGEBAR].dat, 0,0);
// draw message
// alfont_textprintf(temp, game_font, 13,7, makecol(0,0,0), cMessage);
alfont_textprintf(temp, game_font, 13,21, makecol(0,0,0), cMessage);
//alfont_textprintf_aa(temp, game_font, 13,21, makecol(1,1,1), cMessage);
// draw temp
draw_trans_sprite(bmp_screen, temp, 1, 42);
destroy_bitmap(temp);
}
}
void cGame::draw_order()
{
// draw order button
if (iActiveList != LIST_STARPORT)
return;
bool bMouseHover=false;
// determine if mouse is over the button..
if ( (mouse_x > 29 && mouse_x < 187) && (mouse_y > 2 && mouse_y < 31))
bMouseHover=true;
bool bDrawOrder=false;
// we ordered stuff
for (int i = 0; i < MAX_ICONS; i++)
{
if (iconFrigate[i] > 0)
bDrawOrder=true;
}
if (TIMER_ordered > -1)
bDrawOrder=false; // grey
if (TIMER_mayorder > -1)
bDrawOrder=false;
if (bDrawOrder)
{
draw_sprite(bmp_screen, (BITMAP *)gfxinter[BTN_ORDER].dat, 29, 0);
}
else
{
// clear
BITMAP *bmp_trans=create_bitmap(((BITMAP *)gfxinter[BTN_ORDER].dat)->w,((BITMAP *)gfxinter[BTN_ORDER].dat)->h);
clear_to_color(bmp_trans, makecol(255,0,255));
// copy
draw_sprite(bmp_trans, (BITMAP *)gfxinter[BTN_ORDER].dat, 0, 0);
// make black
rectfill(bmp_screen, 29, 0, 187, 29, makecol(0,0,0));
// set blender
//set_trans_blender(0,0,0,128);
// trans
fblend_trans(bmp_trans, bmp_screen, 29, 0, 128);
//draw_trans_sprite(bmp_screen, bmp_trans, 29, 0);
// destroy - phew
destroy_bitmap(bmp_trans);
// rectfill(bmp_screen, 29, 0, 187, 29, makecol(0,0,0));
// set_trans_blender(0,0,0,128);
// draw_trans_sprite(bmp_screen, (BITMAP *)gfxinter[BTN_ORDER].dat, 29, 0);
//draw_sprite(bmp_screen, (BITMAP *)gfxinter[BTN_ORDER_GREY].dat, 29, 0);
}
// react on mouse
if (bMouseHover && bDrawOrder)
{
if (bMousePressedLeft)
{
TIMER_ordered=30; // 30 seconds
}
}
}
void cGame::draw_upgrade()
{
bool bDrawUpgradeButton=false;
bool bMouseHover=false;
int iLimit=0;
int iType=-1;
int iPrice=-1;
int iDrawXLimit=-1;
if (iActiveList == LIST_NONE)
return; // nothing selected, so nothing to upgrade
// determine if mouse is over the button..
if ( (mouse_x > 29 && mouse_x < 187) && (mouse_y > 2 && mouse_y < 31))
if (iconbuilding[iActiveList] < 0) // not building, then we may do this
bMouseHover=true;
// determine what list is selected
////////////////////////
/// CONSTRUCTION YARD UPGRADING
////////////////////////
if (iActiveList == LIST_CONSTYARD)
{
iType=CONSTYARD;
// first upgrade
if (iStructureUpgrade[CONSTYARD] == 0 && iMission >= 4)
{
bDrawUpgradeButton=true;
if (iUpgradeProgress[CONSTYARD] < 0)
{
// when mission 4 or higher, show upgrade button
// * upgrade is for 4 slabs
iLimit=10;
iPrice=200;
}
}
// second upgrade
// * Upgrade for Rocket Turret, but only when we have radar
if (iStructureUpgrade[CONSTYARD] == 1 && iMission >= 6 &&
player[0].iStructures[RADAR] > 0)
{
bDrawUpgradeButton=true;
if (iUpgradeProgress[CONSTYARD] < 0)
{
// when mission 4 or higher, show upgrade button
// * upgrade is for 4 slabs
iLimit=50;
iPrice=400;
}
}
}
////////////////////////
/// LIGHTFACTORY UPGRADING
////////////////////////
if (iActiveList == LIST_LIGHTFC)
{
// Lightfactory upgrading is done only for house Atreides and Ordos
iType=LIGHTFACTORY;
// first upgrade
if (iStructureUpgrade[LIGHTFACTORY] == 0 && iMission >= 2)
{
bDrawUpgradeButton=true;
if (iUpgradeProgress[LIGHTFACTORY] < 0)
{
// * upgrade for Quad
iLimit=50;
iPrice=500;
}
}
}
////////////////////////
/// BARRACKS/WOR UPGRADING
////////////////////////
if (iActiveList == LIST_INFANTRY)
{
// Lightfactory upgrading is done only for house Atreides and Ordos
if (player[0].house == ATREIDES ||
player[0].house == ORDOS)
iType=BARRACKS; // Note: ordos uses also wor, so this is also for wor!!
else
iType=WOR;
// first upgrade
if (iStructureUpgrade[iType] == 0 && iMission >= 2)
{
bDrawUpgradeButton=true;
if (iUpgradeProgress[iType] < 0)
{
// * upgrade for TROOPERS
iLimit=30;
iPrice=150;
if (iHouse == ORDOS)
{
iLimit=60;
iPrice=300; // double the price
}
}
}
}
////////////////////////
/// ORNI UPGRADING
////////////////////////
if (iActiveList == LIST_ORNI && player[0].house != HARKONNEN)
{
// Lightfactory upgrading is done only for house Atreides and Ordos
iType=HIGHTECH;
// first upgrade
if (iStructureUpgrade[HIGHTECH] == 0 && iMission >= 6)
{
bDrawUpgradeButton=true;
if (iUpgradeProgress[HIGHTECH] < 0)
{
// * upgrade for ORNI
iLimit=100;
iPrice=700;
}
}
}
////////////////////////
/// HEAVYFACTORY UPGRADING
////////////////////////
if (iActiveList == LIST_HEAVYFC)
{
// Lightfactory upgrading is done only for house Atreides and Ordos
iType=HEAVYFACTORY;
// first upgrade
if (iStructureUpgrade[HEAVYFACTORY] == 0 && iMission >= 4)
{
bDrawUpgradeButton=true;
if (iUpgradeProgress[HEAVYFACTORY] < 0)
{
// * upgrade for MCV
iLimit=60;
iPrice=500;
}
}
if (iStructureUpgrade[HEAVYFACTORY] == 1 && iMission >= 5)
{
bDrawUpgradeButton=true;
if (iUpgradeProgress[HEAVYFACTORY] < 0)
{
// * upgrade for LAUNCHER
iLimit=80;
iPrice=500;
}
}
if (iStructureUpgrade[HEAVYFACTORY] == 2 && iMission >= 6)
{
bDrawUpgradeButton=true;
if (iUpgradeProgress[HEAVYFACTORY] < 0)
{
// * upgrade for SIEGE
iLimit=100;
iPrice=700;
}
}
if (iStructureUpgrade[HEAVYFACTORY] == 3 && iMission >= 7 &&
player[0].iStructures[IX] > 0) // AND we do own a house of IX
{
bDrawUpgradeButton=true;
if (iUpgradeProgress[HEAVYFACTORY] < 0)
{
// * upgrade for SPECIAL WEAPON
iLimit=120;
iPrice=1000;
}
}
}
if (bMouseHover && bDrawUpgradeButton && iPrice > -1)
{
char msg[255];
sprintf(msg, "$%d | Upgrade (Shortkey 'U')", iPrice);
set_message(msg);
}
// Start upgrading sequence when pressing button and such
if (bDrawUpgradeButton) {
// when nothing is being built in the list and there is enough money (if not, the button should be dark
if (iconbuilding[iActiveList] < 0 && player[0].credits >= iPrice) {
draw_sprite(bmp_screen, (BITMAP *)gfxinter[BTN_UPGRADE].dat, 29, 0);
// determine if we should take action
bool bShouldUpgrade=false;
if (iUpgradeProgressLimit[iType] <= 0) {
if (bMousePressedLeft && bMouseHover) {
bShouldUpgrade=true;
}
if (key[KEY_U]) {
bShouldUpgrade=true;
}
}
if (bShouldUpgrade) {
// able to press button, valid and enough money
if (iType > -1) {
iUpgradeTIMER[iType]=0;
iUpgradeProgress[iType]=0;
iUpgradeProgressLimit[iType]=iLimit;
player[0].credits -= iPrice;
}
}
}
else
{
// clear
BITMAP *bmp_trans=create_bitmap(((BITMAP *)gfxinter[BTN_UPGRADE].dat)->w,((BITMAP *)gfxinter[BTN_UPGRADE].dat)->h);
clear_to_color(bmp_trans, makecol(255,0,255));
// copy
draw_sprite(bmp_trans, (BITMAP *)gfxinter[BTN_UPGRADE].dat, 0, 0);
// make black
rectfill(bmp_screen, 29, 0, 187, 29, makecol(0,0,0));
// set blender
set_trans_blender(0,0,0,128);
// trans (makes upgrade button show like it is disabled)
draw_trans_sprite(bmp_screen, bmp_trans, 29, 0);
// destroy - phew
destroy_bitmap(bmp_trans);
}
}
// Draw progress bar (when upgrading)
if (iType > -1 && iUpgradeProgress[iType] > -1)
{
iDrawXLimit = health_bar(157, iUpgradeProgress[iType], iUpgradeProgressLimit[iType]);
if (iDrawXLimit > -1)
{
int iColor=makecol(255,255,255);
BITMAP *temp = create_bitmap(157, 28);
clear_to_color(temp, makecol(255,0,255));
if (player[0].house == ATREIDES) iColor = makecol(0,0,255);
if (player[0].house == HARKONNEN) iColor = makecol(255,0,0);
if (player[0].house == ORDOS) iColor = makecol(0,255,0);
if (player[0].house == SARDAUKAR) iColor = makecol(255,0,255);
rectfill(temp, 0, 0, (157-iDrawXLimit), 30, iColor);
draw_trans_sprite(bmp_screen, temp, 30, 1);
destroy_bitmap(temp);
}
}
} // end of function
<|endoftext|> |
<commit_before>// baljsn_tokenizer.cpp -*-C++-*-
#include <baljsn_tokenizer.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(baljsn_tokenizer_cpp,"$Id$ $CSID$")
#include <bdlb_chartype.h>
#include <bsl_cstring.h>
#include <bsl_ios.h>
#include <bsl_streambuf.h>
#include <baljsn_parserutil.h> // for testing only
// IMPLEMENTATION NOTES
// --------------------
// The following table provides the various transitions that need to be handled
// with the tokenizer.
//
// Current Token Curr Char Next Char Following Token
// ------------- --------- --------- ---------------
// BEGIN BEGIN '{' START_OBJECT
// NAME ':' '{' START_OBJECT
// START_ARRAY '[' '{' START_OBJECT
// END_OBJECT ',' '{' START_OBJECT
//
// START_OBJECT '{' '"' NAME
// VALUE ',' '"' NAME
// END_OBJECT ',' '"' NAME
// END_ARRAY ',' '"' NAME
//
// NAME ':' '"' VALUE (string)
// NAME ':' Number VALUE (number)
// START_ARRAY '[' '"' VALUE (string)
// START_ARRAY '[' Number VALUE (number)
// VALUE ',' '"' VALUE (string)
// VALUE ',' Number VALUE (number)
//
// START_OBJECT '{' '}' END_OBJECT
// VALUE (number) Number '}' END_OBJECT
// VALUE (string) '"' '}' END_OBJECT
// END_OBJECT '}' '}' END_OBJECT
// END_ARRAY ']' '}' END_OBJECT
//
// NAME ':' '[' START_ARRAY
// START_ARRAY '[' '[' START_ARRAY
// END_ARRAY ',' '[' START_ARRAY
//
// START_ARRAY '[' ']' END_ARRAY
// VALUE (number) Number ']' END_ARRAY
// VALUE (string) '"' ']' END_ARRAY
// END_OBJECT '}' ']' END_ARRAY
// END_ARRAY ']' ']' END_ARRAY
//..
namespace BloombergLP {
namespace {
static const char *WHITESPACE = " \n\t\v\f\r";
static const char *TOKENS = "{}[]:,";
} // close unnamed namespace
namespace baljsn {
// ----------------
// struct Tokenizer
// ----------------
// PRIVATE MANIPULATORS
int Tokenizer::reloadStringBuffer()
{
d_stringBuffer.resize(k_MAX_STRING_SIZE);
const int numRead =
static_cast<int>(d_streambuf_p->sgetn(&d_stringBuffer[0],
k_MAX_STRING_SIZE));
d_cursor = 0;
d_stringBuffer.resize(numRead);
return numRead;
}
int Tokenizer::expandBufferForLargeValue()
{
d_stringBuffer.resize(d_stringBuffer.length() + k_MAX_STRING_SIZE);
const int numRead =
static_cast<int>(d_streambuf_p->sgetn(&d_stringBuffer[d_valueIter],
k_MAX_STRING_SIZE));
return numRead ? 0 : -1;
}
int Tokenizer::moveValueCharsToStartAndReloadBuffer()
{
d_stringBuffer.erase(d_stringBuffer.begin(),
d_stringBuffer.begin() + d_valueBegin);
d_stringBuffer.resize(k_MAX_STRING_SIZE);
d_valueIter = d_valueIter - d_valueBegin;
const int numRead =
static_cast<int>(d_streambuf_p->sgetn(&d_stringBuffer[d_valueIter],
k_MAX_STRING_SIZE - d_valueIter));
if (numRead > 0) {
d_stringBuffer.resize(d_valueIter + numRead);
d_valueBegin = 0;
}
return numRead;
}
int Tokenizer::skipWhitespace()
{
while (true) {
bsl::size_t pos = d_stringBuffer.find_first_not_of(WHITESPACE,
d_cursor);
if (bsl::string::npos != pos) {
d_cursor = pos;
break;
}
const int numRead = reloadStringBuffer();
if (0 == numRead) {
return -1; // RETURN
}
}
return 0;
}
int Tokenizer::extractStringValue()
{
bool firstTime = true;
char previousChar = 0;
while (true) {
while (d_valueIter < d_stringBuffer.length()
&& '"' != d_stringBuffer[d_valueIter]) {
if ('\\' == d_stringBuffer[d_valueIter]
&& '\\' == previousChar) {
previousChar = 0;
}
else {
previousChar = d_stringBuffer[d_valueIter];
}
++d_valueIter;
}
if (d_valueIter >= d_stringBuffer.length()) {
// There isn't enough room in the internal buffer to hold the
// value. If this is the first time through the loop, we move the
// current sequence of characters being processed to the front of
// the internal buffer, otherwise we must expand the internal
// buffer to hold additional characters. If we are at the
// beginning of the string buffer then we dont need to move any
// characters and we simply expand the string buffer.
if (0 == d_valueBegin) {
firstTime = false;
}
if (firstTime) {
const int numRead = moveValueCharsToStartAndReloadBuffer();
if (0 == numRead) {
return -1; // RETURN
}
firstTime = false;
}
else {
const int rc = expandBufferForLargeValue();
if (rc) {
return rc; // RETURN
}
}
}
else {
if ('\\' == previousChar) {
++d_valueIter;
previousChar = 0;
continue;
}
d_valueEnd = d_valueIter;
return 0; // RETURN
}
}
return 0;
}
int Tokenizer::skipNonWhitespaceOrTillToken()
{
bool firstTime = true;
while (true) {
while (d_valueIter < d_stringBuffer.length()
&& !bdlb::CharType::isSpace(d_stringBuffer[d_valueIter])
&& !bsl::strchr(TOKENS, d_stringBuffer[d_valueIter])) {
++d_valueIter;
}
if (d_valueIter >= d_stringBuffer.length()) {
// There isn't enough room in the internal buffer to hold the
// value. If this is the first time through the loop, we move the
// current sequence of characters being processed to the front of
// the internal buffer, otherwise we must expand the internal
// buffer to hold additional characters.
if (firstTime) {
const int numRead = moveValueCharsToStartAndReloadBuffer();
if (0 == numRead) {
d_valueEnd = d_valueIter;
return 0; // RETURN
}
firstTime = false;
}
else {
const int rc = expandBufferForLargeValue();
if (rc) {
return rc; // RETURN
}
}
}
else {
d_valueEnd = d_valueIter;
return 0; // RETURN
}
}
return 0;
}
// MANIPULATORS
int Tokenizer::advanceToNextToken()
{
if (e_ERROR == d_tokenType) {
return -1; // RETURN
}
if (d_cursor >= d_stringBuffer.size()) {
const int numRead = reloadStringBuffer();
if (0 == numRead) {
d_tokenType = e_ERROR;
return -1; // RETURN
}
}
bool continueFlag;
char previousChar = 0;
do {
continueFlag = false;
const int rc = skipWhitespace();
if (rc) {
d_tokenType = e_ERROR;
return -1; // RETURN
}
switch (d_stringBuffer[d_cursor]) {
case '{': {
if ((e_ELEMENT_NAME == d_tokenType && ':' == previousChar)
|| e_START_ARRAY == d_tokenType
|| (e_END_OBJECT == d_tokenType && ',' == previousChar)
|| (d_allowHeterogenousArrays
&& e_ARRAY_CONTEXT == d_context
&& ',' == previousChar)
|| e_BEGIN == d_tokenType) {
d_tokenType = e_START_OBJECT;
d_context = e_OBJECT_CONTEXT;
previousChar = '{';
++d_cursor;
}
else {
d_tokenType = e_ERROR;
return -1; // RETURN
}
} break;
case '}': {
if ((e_ELEMENT_VALUE == d_tokenType && ',' != previousChar)
|| e_START_OBJECT == d_tokenType
|| e_END_OBJECT == d_tokenType
|| e_END_ARRAY == d_tokenType) {
d_tokenType = e_END_OBJECT;
d_context = e_OBJECT_CONTEXT;
previousChar = '}';
++d_cursor;
}
else {
d_tokenType = e_ERROR;
return -1; // RETURN
}
} break;
case '[': {
if ((e_ELEMENT_NAME == d_tokenType && ':' == previousChar)
|| e_START_ARRAY == d_tokenType
|| (e_END_ARRAY == d_tokenType && ',' == previousChar)
|| (d_allowHeterogenousArrays
&& e_ARRAY_CONTEXT == d_context
&& ',' == previousChar)
|| e_BEGIN == d_tokenType) {
d_tokenType = e_START_ARRAY;
d_context = e_ARRAY_CONTEXT;
previousChar = '[';
++d_cursor;
}
else {
d_tokenType = e_ERROR;
return -1; // RETURN
}
} break;
case ']': {
if ((e_ELEMENT_VALUE == d_tokenType && ',' != previousChar)
|| e_START_ARRAY == d_tokenType
|| (e_END_ARRAY == d_tokenType && ',' != previousChar)
|| (e_END_OBJECT == d_tokenType && ',' != previousChar)) {
d_tokenType = e_END_ARRAY;
d_context = e_OBJECT_CONTEXT;
previousChar = ']';
++d_cursor;
}
else {
d_tokenType = e_ERROR;
return -1; // RETURN
}
} break;
case ',': {
if (e_ELEMENT_VALUE == d_tokenType
|| e_END_OBJECT == d_tokenType
|| e_END_ARRAY == d_tokenType) {
previousChar = ',';
continueFlag = true;
++d_cursor;
}
else {
d_tokenType = e_ERROR;
return -1; // RETURN
}
} break;
case ':': {
if (e_ELEMENT_NAME == d_tokenType) {
previousChar = ':';
continueFlag = true;
++d_cursor;
}
else {
d_tokenType = e_ERROR;
return -1; // RETURN
}
} break;
case '"': {
// Here are the scenarios for a '"':
//
// CURRENT TOKEN CONTEXT NEXT TOKEN
// ------------- ------- ----------
// START_OBJECT ('{') ELEMENT_NAME
// END_OBJECT ('}') ELEMENT_NAME
// START_ARRAY ('[') ELEMENT_VALUE
// END_ARRAY (']') ELEMENT_VALUE
// ELEMENT_NAME (':') ELEMENT_VALUE
// ELEMENT_VALUE ( ) OBJECT_CONTEXT ELEMENT_NAME
// ELEMENT_VALUE ( ) ARRAY_CONTEXT ELEMENT_VALUE
if (e_START_OBJECT == d_tokenType
|| (e_END_OBJECT == d_tokenType && ',' == previousChar)
|| (e_END_ARRAY == d_tokenType && ',' == previousChar)
|| (e_ELEMENT_VALUE == d_tokenType
&& ',' == previousChar
&& e_OBJECT_CONTEXT == d_context)) {
d_tokenType = e_ELEMENT_NAME;
d_valueBegin = d_cursor + 1;
d_valueIter = d_valueBegin;
}
else if (e_START_ARRAY == d_tokenType
|| (e_ELEMENT_NAME == d_tokenType && ':' == previousChar)
|| (e_ELEMENT_VALUE == d_tokenType
&& ',' == previousChar
&& e_ARRAY_CONTEXT == d_context)
|| (e_BEGIN == d_tokenType && d_allowStandAloneValues)) {
d_tokenType = e_ELEMENT_VALUE;
d_valueBegin = d_cursor;
d_valueIter = d_valueBegin + 1;
}
else {
d_tokenType = e_ERROR;
return -1; // RETURN
}
d_valueEnd = 0;
int rc = extractStringValue();
if (rc) {
d_tokenType = e_ERROR;
return -1; // RETURN
}
if (e_ELEMENT_NAME == d_tokenType) {
d_cursor = d_valueEnd + 1;
}
else {
// Advance past the end '"'.
++d_valueEnd;
d_cursor = d_valueEnd;
}
previousChar = '"';
} break;
default: {
if (e_START_ARRAY == d_tokenType
|| (e_ELEMENT_NAME == d_tokenType && ':' == previousChar)
|| (e_ELEMENT_VALUE == d_tokenType
&& ',' == previousChar
&& e_ARRAY_CONTEXT == d_context)
|| (d_allowHeterogenousArrays
&& e_END_ARRAY == d_tokenType
&& ',' == previousChar)
|| (e_BEGIN == d_tokenType && d_allowStandAloneValues)) {
d_tokenType = e_ELEMENT_VALUE;
d_valueBegin = d_cursor;
d_valueEnd = 0;
d_valueIter = d_valueBegin + 1;
const int rc = skipNonWhitespaceOrTillToken();
if (rc) {
d_tokenType = e_ERROR;
return -1; // RETURN
}
d_cursor = d_valueEnd;
previousChar = 0;
}
else {
d_tokenType = e_ERROR;
return -1; // RETURN
}
} break;
}
} while (continueFlag);
return 0;
}
int Tokenizer::resetStreamBufGetPointer()
{
if (d_cursor >= d_stringBuffer.size()) {
return 0; // RETURN
}
const int numExtraCharsRead = static_cast<int>(d_stringBuffer.size()
- d_cursor);
const bsl::streamoff newPos = d_streambuf_p->pubseekoff(-numExtraCharsRead,
bsl::ios_base::cur,
bsl::ios_base::in);
return newPos >= 0 ? 0 : -1;
}
// ACCESSORS
int Tokenizer::value(bslstl::StringRef *data) const
{
if ((e_ELEMENT_NAME == d_tokenType
|| e_ELEMENT_VALUE == d_tokenType)
&& d_valueBegin != d_valueEnd) {
data->assign(&d_stringBuffer[d_valueBegin],
&d_stringBuffer[d_valueEnd]);
return 0; // RETURN
}
return -1;
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>Update stringBuffer after read<commit_after>// baljsn_tokenizer.cpp -*-C++-*-
#include <baljsn_tokenizer.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(baljsn_tokenizer_cpp,"$Id$ $CSID$")
#include <bdlb_chartype.h>
#include <bsl_cstring.h>
#include <bsl_ios.h>
#include <bsl_streambuf.h>
#include <baljsn_parserutil.h> // for testing only
// IMPLEMENTATION NOTES
// --------------------
// The following table provides the various transitions that need to be handled
// with the tokenizer.
//
// Current Token Curr Char Next Char Following Token
// ------------- --------- --------- ---------------
// BEGIN BEGIN '{' START_OBJECT
// NAME ':' '{' START_OBJECT
// START_ARRAY '[' '{' START_OBJECT
// END_OBJECT ',' '{' START_OBJECT
//
// START_OBJECT '{' '"' NAME
// VALUE ',' '"' NAME
// END_OBJECT ',' '"' NAME
// END_ARRAY ',' '"' NAME
//
// NAME ':' '"' VALUE (string)
// NAME ':' Number VALUE (number)
// START_ARRAY '[' '"' VALUE (string)
// START_ARRAY '[' Number VALUE (number)
// VALUE ',' '"' VALUE (string)
// VALUE ',' Number VALUE (number)
//
// START_OBJECT '{' '}' END_OBJECT
// VALUE (number) Number '}' END_OBJECT
// VALUE (string) '"' '}' END_OBJECT
// END_OBJECT '}' '}' END_OBJECT
// END_ARRAY ']' '}' END_OBJECT
//
// NAME ':' '[' START_ARRAY
// START_ARRAY '[' '[' START_ARRAY
// END_ARRAY ',' '[' START_ARRAY
//
// START_ARRAY '[' ']' END_ARRAY
// VALUE (number) Number ']' END_ARRAY
// VALUE (string) '"' ']' END_ARRAY
// END_OBJECT '}' ']' END_ARRAY
// END_ARRAY ']' ']' END_ARRAY
//..
namespace BloombergLP {
namespace {
static const char *WHITESPACE = " \n\t\v\f\r";
static const char *TOKENS = "{}[]:,";
} // close unnamed namespace
namespace baljsn {
// ----------------
// struct Tokenizer
// ----------------
// PRIVATE MANIPULATORS
int Tokenizer::reloadStringBuffer()
{
d_stringBuffer.resize(k_MAX_STRING_SIZE);
const int numRead =
static_cast<int>(d_streambuf_p->sgetn(&d_stringBuffer[0],
k_MAX_STRING_SIZE));
d_cursor = 0;
d_stringBuffer.resize(numRead);
return numRead;
}
int Tokenizer::expandBufferForLargeValue()
{
const int currLength = d_stringBuffer.length();
d_stringBuffer.resize(currLength + k_MAX_STRING_SIZE);
const int numRead =
static_cast<int>(d_streambuf_p->sgetn(&d_stringBuffer[d_valueIter],
k_MAX_STRING_SIZE));
d_stringBuffer.resize(currLength + numRead);
return numRead ? 0 : -1;
}
int Tokenizer::moveValueCharsToStartAndReloadBuffer()
{
d_stringBuffer.erase(d_stringBuffer.begin(),
d_stringBuffer.begin() + d_valueBegin);
d_stringBuffer.resize(k_MAX_STRING_SIZE);
d_valueIter = d_valueIter - d_valueBegin;
const int numRead =
static_cast<int>(d_streambuf_p->sgetn(&d_stringBuffer[d_valueIter],
k_MAX_STRING_SIZE - d_valueIter));
if (numRead > 0) {
d_stringBuffer.resize(d_valueIter + numRead);
d_valueBegin = 0;
}
return numRead;
}
int Tokenizer::skipWhitespace()
{
while (true) {
bsl::size_t pos = d_stringBuffer.find_first_not_of(WHITESPACE,
d_cursor);
if (bsl::string::npos != pos) {
d_cursor = pos;
break;
}
const int numRead = reloadStringBuffer();
if (0 == numRead) {
return -1; // RETURN
}
}
return 0;
}
int Tokenizer::extractStringValue()
{
bool firstTime = true;
char previousChar = 0;
while (true) {
while (d_valueIter < d_stringBuffer.length()
&& '"' != d_stringBuffer[d_valueIter]) {
if ('\\' == d_stringBuffer[d_valueIter]
&& '\\' == previousChar) {
previousChar = 0;
}
else {
previousChar = d_stringBuffer[d_valueIter];
}
++d_valueIter;
}
if (d_valueIter >= d_stringBuffer.length()) {
// There isn't enough room in the internal buffer to hold the
// value. If this is the first time through the loop, we move the
// current sequence of characters being processed to the front of
// the internal buffer, otherwise we must expand the internal
// buffer to hold additional characters. If we are at the
// beginning of the string buffer then we dont need to move any
// characters and we simply expand the string buffer.
if (0 == d_valueBegin) {
firstTime = false;
}
if (firstTime) {
const int numRead = moveValueCharsToStartAndReloadBuffer();
if (0 == numRead) {
return -1; // RETURN
}
firstTime = false;
}
else {
const int rc = expandBufferForLargeValue();
if (rc) {
return rc; // RETURN
}
}
}
else {
if ('\\' == previousChar) {
++d_valueIter;
previousChar = 0;
continue;
}
d_valueEnd = d_valueIter;
return 0; // RETURN
}
}
return 0;
}
int Tokenizer::skipNonWhitespaceOrTillToken()
{
bool firstTime = true;
while (true) {
while (d_valueIter < d_stringBuffer.length()
&& !bdlb::CharType::isSpace(d_stringBuffer[d_valueIter])
&& !bsl::strchr(TOKENS, d_stringBuffer[d_valueIter])) {
++d_valueIter;
}
if (d_valueIter >= d_stringBuffer.length()) {
// There isn't enough room in the internal buffer to hold the
// value. If this is the first time through the loop, we move the
// current sequence of characters being processed to the front of
// the internal buffer, otherwise we must expand the internal
// buffer to hold additional characters.
if (firstTime) {
const int numRead = moveValueCharsToStartAndReloadBuffer();
if (0 == numRead) {
d_valueEnd = d_valueIter;
return 0; // RETURN
}
firstTime = false;
}
else {
const int rc = expandBufferForLargeValue();
if (rc) {
return rc; // RETURN
}
}
}
else {
d_valueEnd = d_valueIter;
return 0; // RETURN
}
}
return 0;
}
// MANIPULATORS
int Tokenizer::advanceToNextToken()
{
if (e_ERROR == d_tokenType) {
return -1; // RETURN
}
if (d_cursor >= d_stringBuffer.size()) {
const int numRead = reloadStringBuffer();
if (0 == numRead) {
d_tokenType = e_ERROR;
return -1; // RETURN
}
}
bool continueFlag;
char previousChar = 0;
do {
continueFlag = false;
const int rc = skipWhitespace();
if (rc) {
d_tokenType = e_ERROR;
return -1; // RETURN
}
switch (d_stringBuffer[d_cursor]) {
case '{': {
if ((e_ELEMENT_NAME == d_tokenType && ':' == previousChar)
|| e_START_ARRAY == d_tokenType
|| (e_END_OBJECT == d_tokenType && ',' == previousChar)
|| (d_allowHeterogenousArrays
&& e_ARRAY_CONTEXT == d_context
&& ',' == previousChar)
|| e_BEGIN == d_tokenType) {
d_tokenType = e_START_OBJECT;
d_context = e_OBJECT_CONTEXT;
previousChar = '{';
++d_cursor;
}
else {
d_tokenType = e_ERROR;
return -1; // RETURN
}
} break;
case '}': {
if ((e_ELEMENT_VALUE == d_tokenType && ',' != previousChar)
|| e_START_OBJECT == d_tokenType
|| e_END_OBJECT == d_tokenType
|| e_END_ARRAY == d_tokenType) {
d_tokenType = e_END_OBJECT;
d_context = e_OBJECT_CONTEXT;
previousChar = '}';
++d_cursor;
}
else {
d_tokenType = e_ERROR;
return -1; // RETURN
}
} break;
case '[': {
if ((e_ELEMENT_NAME == d_tokenType && ':' == previousChar)
|| e_START_ARRAY == d_tokenType
|| (e_END_ARRAY == d_tokenType && ',' == previousChar)
|| (d_allowHeterogenousArrays
&& e_ARRAY_CONTEXT == d_context
&& ',' == previousChar)
|| e_BEGIN == d_tokenType) {
d_tokenType = e_START_ARRAY;
d_context = e_ARRAY_CONTEXT;
previousChar = '[';
++d_cursor;
}
else {
d_tokenType = e_ERROR;
return -1; // RETURN
}
} break;
case ']': {
if ((e_ELEMENT_VALUE == d_tokenType && ',' != previousChar)
|| e_START_ARRAY == d_tokenType
|| (e_END_ARRAY == d_tokenType && ',' != previousChar)
|| (e_END_OBJECT == d_tokenType && ',' != previousChar)) {
d_tokenType = e_END_ARRAY;
d_context = e_OBJECT_CONTEXT;
previousChar = ']';
++d_cursor;
}
else {
d_tokenType = e_ERROR;
return -1; // RETURN
}
} break;
case ',': {
if (e_ELEMENT_VALUE == d_tokenType
|| e_END_OBJECT == d_tokenType
|| e_END_ARRAY == d_tokenType) {
previousChar = ',';
continueFlag = true;
++d_cursor;
}
else {
d_tokenType = e_ERROR;
return -1; // RETURN
}
} break;
case ':': {
if (e_ELEMENT_NAME == d_tokenType) {
previousChar = ':';
continueFlag = true;
++d_cursor;
}
else {
d_tokenType = e_ERROR;
return -1; // RETURN
}
} break;
case '"': {
// Here are the scenarios for a '"':
//
// CURRENT TOKEN CONTEXT NEXT TOKEN
// ------------- ------- ----------
// START_OBJECT ('{') ELEMENT_NAME
// END_OBJECT ('}') ELEMENT_NAME
// START_ARRAY ('[') ELEMENT_VALUE
// END_ARRAY (']') ELEMENT_VALUE
// ELEMENT_NAME (':') ELEMENT_VALUE
// ELEMENT_VALUE ( ) OBJECT_CONTEXT ELEMENT_NAME
// ELEMENT_VALUE ( ) ARRAY_CONTEXT ELEMENT_VALUE
if (e_START_OBJECT == d_tokenType
|| (e_END_OBJECT == d_tokenType && ',' == previousChar)
|| (e_END_ARRAY == d_tokenType && ',' == previousChar)
|| (e_ELEMENT_VALUE == d_tokenType
&& ',' == previousChar
&& e_OBJECT_CONTEXT == d_context)) {
d_tokenType = e_ELEMENT_NAME;
d_valueBegin = d_cursor + 1;
d_valueIter = d_valueBegin;
}
else if (e_START_ARRAY == d_tokenType
|| (e_ELEMENT_NAME == d_tokenType && ':' == previousChar)
|| (e_ELEMENT_VALUE == d_tokenType
&& ',' == previousChar
&& e_ARRAY_CONTEXT == d_context)
|| (e_BEGIN == d_tokenType && d_allowStandAloneValues)) {
d_tokenType = e_ELEMENT_VALUE;
d_valueBegin = d_cursor;
d_valueIter = d_valueBegin + 1;
}
else {
d_tokenType = e_ERROR;
return -1; // RETURN
}
d_valueEnd = 0;
int rc = extractStringValue();
if (rc) {
d_tokenType = e_ERROR;
return -1; // RETURN
}
if (e_ELEMENT_NAME == d_tokenType) {
d_cursor = d_valueEnd + 1;
}
else {
// Advance past the end '"'.
++d_valueEnd;
d_cursor = d_valueEnd;
}
previousChar = '"';
} break;
default: {
if (e_START_ARRAY == d_tokenType
|| (e_ELEMENT_NAME == d_tokenType && ':' == previousChar)
|| (e_ELEMENT_VALUE == d_tokenType
&& ',' == previousChar
&& e_ARRAY_CONTEXT == d_context)
|| (d_allowHeterogenousArrays
&& e_END_ARRAY == d_tokenType
&& ',' == previousChar)
|| (e_BEGIN == d_tokenType && d_allowStandAloneValues)) {
d_tokenType = e_ELEMENT_VALUE;
d_valueBegin = d_cursor;
d_valueEnd = 0;
d_valueIter = d_valueBegin + 1;
const int rc = skipNonWhitespaceOrTillToken();
if (rc) {
d_tokenType = e_ERROR;
return -1; // RETURN
}
d_cursor = d_valueEnd;
previousChar = 0;
}
else {
d_tokenType = e_ERROR;
return -1; // RETURN
}
} break;
}
} while (continueFlag);
return 0;
}
int Tokenizer::resetStreamBufGetPointer()
{
if (d_cursor >= d_stringBuffer.size()) {
return 0; // RETURN
}
const int numExtraCharsRead = static_cast<int>(d_stringBuffer.size()
- d_cursor);
const bsl::streamoff newPos = d_streambuf_p->pubseekoff(-numExtraCharsRead,
bsl::ios_base::cur,
bsl::ios_base::in);
return newPos >= 0 ? 0 : -1;
}
// ACCESSORS
int Tokenizer::value(bslstl::StringRef *data) const
{
if ((e_ELEMENT_NAME == d_tokenType
|| e_ELEMENT_VALUE == d_tokenType)
&& d_valueBegin != d_valueEnd) {
data->assign(&d_stringBuffer[d_valueBegin],
&d_stringBuffer[d_valueEnd]);
return 0; // RETURN
}
return -1;
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<|endoftext|> |
<commit_before>/*******************************************************************************
Name: Samuel Wenninger, Brandon Drumheller, and Malcolm Lorber
Date Created: 11-25-2015
Filename: bank.cpp
Description: Bank server that services requests from the ATM
using the Boost library. Compile using the following:
g++ -std=c++11 bank.cpp -lboost_system -lboost_thread -o bank.out
*******************************************************************************/
#include <iostream>
#include <string>
//#include <memory>
//#include <utility>
#include <vector>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
class User{
public:
User(std::string name, long long balance): name(name), balance(balance){}
private:
std::string name;
long long balance;
unsigned int pin;
};
/*******************************************************************************
@DESC: The Session class is responsible for reading from the ATM socket and
to the Bank socket.
@ARGS: N/A
@RTN: N/A
*******************************************************************************/
class Session : public std::enable_shared_from_this<Session> {
public:
Session(tcp::socket Socket1)
: bank_socket_(std::move(Socket1)) {}
void Start() {
DoRead();
}
private:
//Read from the listen socket (ATM socket)
void DoRead() {
auto Self(shared_from_this());
bank_socket_.async_read_some(boost::asio::buffer(data_, max_length),
[this, Self](boost::system::error_code EC, std::size_t Length) {
if (!EC) {
//instead of directly writing, perform the correct operation
if(std::string(data_).find("login") == 0){
sprintf(data_, "successful write to socket");
}
DoWrite(Length);
}
});
}
//Write to the bank socket
void DoWrite(std::size_t Length) {
auto Self(shared_from_this());
boost::asio::async_write(bank_socket_,
boost::asio::buffer(data_, Length),
[this, Self](boost::system::error_code EC, std::size_t){
if (!EC) {
DoRead();
}
});
}
tcp::socket bank_socket_;
//Max length of messages passed through the proxy
enum {max_length = 1024};
//Array to hold the incoming message
char data_[max_length];
//string data_;
};
/*******************************************************************************
@DESC: The Server class is responsible for initializing the connection to both
ATM and Bank ports and start a Session instance.
@ARGS: N/A
@RTN: N/A
*******************************************************************************/
class Server {
public:
Server(boost::asio::io_service & IOService, int BankPort)
//Call acceptor constructor with the bank's port as the endopoint
//and assign result to acceptor_
: bank_acceptor_(IOService, tcp::endpoint(tcp::v4(), BankPort)),
bank_socket_(IOService) {
DoAccept();
}
private:
void DoAccept() {
//Accept a new connection to the bank socket
bank_acceptor_.async_accept(bank_socket_,
[this](boost::system::error_code EC) {
if (!EC) {
//Accept connection and start a session by calling the
//Session constructor
std::make_shared<Session>(std::move(bank_socket_)) -> Start();
}
DoAccept();
});
}
//Bank acceptor and socket
tcp::acceptor bank_acceptor_;
tcp::socket bank_socket_;
};
bool IsValidCommand(std::string command) {
if (command.substr(0,7) != "deposit" && command.substr(0,7) != "balance") {
return false;
}
if (command.substr(7,1) != "[") {
return false;
}
bool Valid = false;
if (command.substr(0,7) == "deposit") {
int Total = 1;
int NumPairs = 0;
for (int i = 8; i < command.size(); ++i ) {
if (command[i] == '[') {
++Total;
}
else if (command[i] == ']') {
--Total;
}
if (Total == 0) {
++NumPairs;
}
}
if (NumPairs == 2) {
Valid = true;
}
/*
std::cout << "Size: " << command.size() << std::endl;
if (command.size() < 11) {
return false;
}
bool ClosingBracket = false;
bool Valid = false;
for (int i = 8; i < command.size(); ++i) {
if (command[i] == ']') {
if (ClosingBracket) {
ClosingBracket = true;
if (i + 1 < command.size() || command[i+1] != '[') {
return false;
}
}
else {
Valid = true;
}
}
}
if (!ClosingBracket || !Valid) {
return false;
}
}
if (command.substr(0,7) == "balance") {
if (command.size() < 9) {
return false;
}*/
}
if (!Valid) {
return false;
}
return true;
}
void CommandLine() {
while (true) {
std::string command;
std::cin >> command;
bool matched = IsValidCommand(command);
if (!matched) {
std::cerr << "INVALID COMMAND" << std::endl;
}
std::cout << command << std::endl;
}
}
/*******************************************************************************
@DESC: Call appropriate function(s) to initiate communication between the ATM
and the bank.
@ARGS: port to listen on, port to connect to the bank
@RTN: EXIT_SUCCESS on success, EXIT_FAILURE on failure
*******************************************************************************/
int main (int argc, char* argv[]) {
try {
if (argc != 2) {
std::cerr << "Incorrect number of arguments. Proper usage ./a.out"
" <bank-port>" << std::endl;
return EXIT_FAILURE;
}
boost::thread Thread(CommandLine);
boost::asio::io_service IOService;
int BankPort = std::stoi(argv[1]);
Server S(IOService, BankPort);
//Throws an exception if something goes wrong
IOService.run();
}
catch (std::exception & e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
return EXIT_SUCCESS;
}
<commit_msg>Basic command line error checking<commit_after>/*******************************************************************************
Name: Samuel Wenninger, Brandon Drumheller, and Malcolm Lorber
Date Created: 11-25-2015
Filename: bank.cpp
Description: Bank server that services requests from the ATM
using the Boost library. Compile using the following:
g++ -std=c++11 bank.cpp -lboost_system -lboost_thread -o bank.out
*******************************************************************************/
#include <iostream>
#include <string>
//#include <memory>
//#include <utility>
#include <vector>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
class User{
public:
User(std::string name, long long balance): name(name), balance(balance){}
private:
std::string name;
long long balance;
unsigned int pin;
};
/*******************************************************************************
@DESC: The Session class is responsible for reading from the ATM socket and
to the Bank socket.
@ARGS: N/A
@RTN: N/A
*******************************************************************************/
class Session : public std::enable_shared_from_this<Session> {
public:
Session(tcp::socket Socket1)
: bank_socket_(std::move(Socket1)) {}
void Start() {
DoRead();
}
private:
//Read from the listen socket (ATM socket)
void DoRead() {
auto Self(shared_from_this());
bank_socket_.async_read_some(boost::asio::buffer(data_, max_length),
[this, Self](boost::system::error_code EC, std::size_t Length) {
if (!EC) {
//instead of directly writing, perform the correct operation
if(std::string(data_).find("login") == 0){
sprintf(data_, "successful write to socket");
}
DoWrite(Length);
}
});
}
//Write to the bank socket
void DoWrite(std::size_t Length) {
auto Self(shared_from_this());
boost::asio::async_write(bank_socket_,
boost::asio::buffer(data_, Length),
[this, Self](boost::system::error_code EC, std::size_t){
if (!EC) {
DoRead();
}
});
}
tcp::socket bank_socket_;
//Max length of messages passed through the proxy
enum {max_length = 1024};
//Array to hold the incoming message
char data_[max_length];
//string data_;
};
/*******************************************************************************
@DESC: The Server class is responsible for initializing the connection to both
ATM and Bank ports and start a Session instance.
@ARGS: N/A
@RTN: N/A
*******************************************************************************/
class Server {
public:
Server(boost::asio::io_service & IOService, int BankPort)
//Call acceptor constructor with the bank's port as the endopoint
//and assign result to acceptor_
: bank_acceptor_(IOService, tcp::endpoint(tcp::v4(), BankPort)),
bank_socket_(IOService) {
DoAccept();
}
private:
void DoAccept() {
//Accept a new connection to the bank socket
bank_acceptor_.async_accept(bank_socket_,
[this](boost::system::error_code EC) {
if (!EC) {
//Accept connection and start a session by calling the
//Session constructor
std::make_shared<Session>(std::move(bank_socket_)) -> Start();
}
DoAccept();
});
}
//Bank acceptor and socket
tcp::acceptor bank_acceptor_;
tcp::socket bank_socket_;
};
bool IsValidCommand(std::string command) {
if (command.substr(0,7) != "deposit" && command.substr(0,7) != "balance") {
return false;
}
if (command.substr(7,1) != "[") {
return false;
}
bool Valid = false;
int Total = 1;
int NumPairs = 0;
for (int i = 8; i < command.size(); ++i ) {
if (command[i] == '[') {
++Total;
}
else if (command[i] == ']') {
--Total;
}
if (Total == 0) {
++NumPairs;
}
}
if (command.substr(0,7) == "deposit") {
if (NumPairs == 2) {
Valid = true;
}
}
else if (command.substr(0,7) == "balance") {
if (NumPairs == 1) {
Valid = true;
}
}
if (!Valid) {
return false;
}
return true;
}
void CommandLine() {
while (true) {
std::string command;
std::cin >> command;
bool matched = IsValidCommand(command);
if (!matched) {
std::cerr << "INVALID COMMAND" << std::endl;
}
else {
std::cout << command << std::endl;
}
}
}
/*******************************************************************************
@DESC: Call appropriate function(s) to initiate communication between the ATM
and the bank.
@ARGS: port to listen on, port to connect to the bank
@RTN: EXIT_SUCCESS on success, EXIT_FAILURE on failure
*******************************************************************************/
int main (int argc, char* argv[]) {
try {
if (argc != 2) {
std::cerr << "Incorrect number of arguments. Proper usage ./a.out"
" <bank-port>" << std::endl;
return EXIT_FAILURE;
}
boost::thread Thread(CommandLine);
boost::asio::io_service IOService;
int BankPort = std::stoi(argv[1]);
Server S(IOService, BankPort);
//Throws an exception if something goes wrong
IOService.run();
}
catch (std::exception & e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>//
// Created by david on 2018-01-31.
//
#include "class_flbit.h"
#include <config/nmspc_settings.h>
#include <general/nmspc_tensor_extra.h>
#include <iostream>
#include <physics/nmspc_quantum_mechanics.h>
#include <tensors/state/class_state_finite.h>
#include <tools/common/fmt.h>
#include <tools/common/io.h>
#include <tools/common/log.h>
#include <tools/common/prof.h>
#include <tools/finite/io.h>
#include <tools/finite/measure.h>
#include <tools/finite/mps.h>
#include <tools/finite/ops.h>
#include <tools/finite/opt.h>
#include <tensors/state/class_mps_site.h>
#include <unsupported/Eigen/CXX11/Tensor>
class_flbit::class_flbit(std::shared_ptr<h5pp::File> h5pp_file_) : class_algorithm_finite(std::move(h5pp_file_), AlgorithmType::fLBIT) {
tools::log->trace("Constructing class_flbit");
}
void class_flbit::resume() {
// Resume can imply many things
// 1) Resume a simulation which terminated prematurely
// 2) Resume a previously successful simulation. This may be desireable if the config
// wants something that is not present in the file.
// a) A certain number of states
// b) A state inside of a particular energy window
// c) The ground or "roof" states
// To guide the behavior, we check the setting ResumePolicy.
auto state_prefix = tools::common::io::h5resume::find_resumable_state(*h5pp_file, algo_type);
if(state_prefix.empty()) throw std::runtime_error("Could not resume: no valid state candidates found for resume");
tools::log->info("Resuming state [{}]", state_prefix);
tools::finite::io::h5resume::load_simulation(*h5pp_file, state_prefix, tensors, status);
clear_convergence_status();
// Our first task is to decide on a state name for the newly loaded state
// The simplest is to inferr it from the state prefix itself
auto name = tools::common::io::h5resume::extract_state_name(state_prefix);
// Initialize a custom task list
std::list<flbit_task> task_list;
if(not status.algorithm_has_finished) {
// This could be a checkpoint state
// Simply "continue" the algorithm until convergence
if(name.find("emax") != std::string::npos) task_list.emplace_back(flbit_task::FIND_HIGHEST_STATE);
else if(name.find("emin") != std::string::npos)
task_list.emplace_back(flbit_task::FIND_GROUND_STATE);
else
throw std::runtime_error(fmt::format("Unrecognized state name for flbit: [{}]", name));
task_list.emplace_back(flbit_task::POST_DEFAULT);
run_task_list(task_list);
}
// If we reached this point the current state has finished for one reason or another.
// TODO: We may still have some more things to do, e.g. the config may be asking for more states
}
void class_flbit::run_task_list(std::list<flbit_task> &task_list) {
while(not task_list.empty()) {
auto task = task_list.front();
switch(task) {
case flbit_task::INIT_RANDOMIZE_MODEL: randomize_model(); break;
case flbit_task::INIT_RANDOMIZE_INTO_PRODUCT_STATE: randomize_state(ResetReason::INIT, StateInit::RANDOM_PRODUCT_STATE); break;
case flbit_task::INIT_RANDOMIZE_INTO_ENTANGLED_STATE: randomize_state(ResetReason::INIT, StateInit::RANDOM_ENTANGLED_STATE); break;
case flbit_task::INIT_BOND_DIM_LIMITS: init_bond_dimension_limits(); break;
case flbit_task::INIT_WRITE_MODEL: write_to_file(StorageReason::MODEL); break;
case flbit_task::INIT_CLEAR_STATUS: status.clear(); break;
case flbit_task::INIT_DEFAULT: run_preprocessing(); break;
case flbit_task::FIND_GROUND_STATE:
ritz = StateRitz::SR;
state_name = "state_e_min";
run_algorithm();
break;
case flbit_task::FIND_HIGHEST_STATE:
ritz = StateRitz::LR;
state_name = "state_e_max";
run_algorithm();
break;
case flbit_task::POST_WRITE_RESULT: write_to_file(StorageReason::FINISHED); break;
case flbit_task::POST_PRINT_RESULT: print_status_full(); break;
case flbit_task::POST_PRINT_PROFILING: tools::common::profile::print_profiling(algo_type); break;
case flbit_task::POST_DEFAULT: run_postprocessing(); break;
case flbit_task::PROF_RESET: tools::common::profile::reset_profiling(algo_type); break;
}
task_list.pop_front();
}
}
void class_flbit::run_default_task_list() {
std::list<flbit_task> default_task_list = {
flbit_task::INIT_DEFAULT,
flbit_task::FIND_GROUND_STATE,
flbit_task::POST_DEFAULT,
};
run_task_list(default_task_list);
if(not default_task_list.empty()) {
for(auto &task : default_task_list) tools::log->critical("Unfinished task: {}", enum2str(task));
throw std::runtime_error("Simulation ended with unfinished tasks");
}
}
void class_flbit::run_preprocessing() {
tools::log->info("Running {} preprocessing", algo_name);
tools::common::profile::prof[algo_type]["t_pre"]->tic();
status.clear();
randomize_model(); // First use of random!
init_bond_dimension_limits();
randomize_state(ResetReason::INIT, settings::strategy::initial_state);
Eigen::Tensor<Scalar,3> zminus_spinor = Textra::MatrixToTensor(tools::finite::mps::internal::get_spinor("z", -1).normalized(), 2, 1, 1);
tensors.state->get_mps_site(2).set_M(zminus_spinor);
auto unitary_twosite_operators0 = qm::lbit::get_unitary_twosite_operators(settings::model::model_size,0.1);
auto unitary_twosite_operators1 = qm::lbit::get_unitary_twosite_operators(settings::model::model_size,0.1);
auto unitary_twosite_operators2 = qm::lbit::get_unitary_twosite_operators(settings::model::model_size,0.1);
auto unitary_twosite_operators3 = qm::lbit::get_unitary_twosite_operators(settings::model::model_size,0.1);
tools::finite::mps::apply_twosite_gates(*tensors.state,unitary_twosite_operators0,false, status.chi_lim);
tools::finite::mps::apply_twosite_gates(*tensors.state,unitary_twosite_operators1,false, status.chi_lim);
tools::finite::mps::apply_twosite_gates(*tensors.state,unitary_twosite_operators2,false, status.chi_lim);
tools::finite::mps::apply_twosite_gates(*tensors.state,unitary_twosite_operators3,false, status.chi_lim);
// Time evolve here
tools::finite::mps::apply_twosite_gates(*tensors.state,unitary_twosite_operators3,true, status.chi_lim);
tools::finite::mps::apply_twosite_gates(*tensors.state,unitary_twosite_operators2,true, status.chi_lim);
tools::finite::mps::apply_twosite_gates(*tensors.state,unitary_twosite_operators1,true, status.chi_lim);
tools::finite::mps::apply_twosite_gates(*tensors.state,unitary_twosite_operators0,true, status.chi_lim);
exit(0);
tools::common::profile::prof[algo_type]["t_pre"]->toc();
tools::log->info("Finished {} preprocessing", algo_name);
}
void class_flbit::run_algorithm() {
if(state_name.empty()) state_name = ritz == StateRitz::SR ? "state_emin" : "state_emax";
tools::log->info("Starting {} algorithm with model [{}] for state [{}]", algo_name, enum2str(settings::model::model_type), state_name);
tools::common::profile::prof[algo_type]["t_sim"]->tic();
while(true) {
single_flbit_step();
// Update record holder
if(tensors.position_is_any_edge() or tensors.measurements.energy_variance_per_site) {
tools::log->trace("Updating variance record holder");
auto var = tools::finite::measure::energy_variance(tensors);
if(var < status.energy_variance_lowest) status.energy_variance_lowest = var;
}
check_convergence();
print_status_update();
print_profiling_lap();
write_to_file();
tools::log->trace("Finished step {}, iter {}, pos {}, dir {}", status.step, status.iter, status.position, status.direction);
// It's important not to perform the last move, so we break now: that last state would not get optimized
if(stop_reason != StopReason::NONE) break;
update_bond_dimension_limit(); // Will update bond dimension if the state precision is being limited by bond dimension
try_projection();
reduce_mpo_energy();
move_center_point();
}
tools::log->info("Finished {} simulation of state [{}] -- stop reason: {}", algo_name, state_name, enum2str(stop_reason));
status.algorithm_has_finished = true;
tools::common::profile::prof[algo_type]["t_sim"]->toc();
}
void class_flbit::single_flbit_step() {
/*!
* \fn void single_DMRG_step(std::string ritz)
*/
tools::log->trace("Starting single flbit step with ritz [{}]", enum2str(ritz));
tensors.activate_sites(settings::precision::max_size_part_diag, 2);
Eigen::Tensor<Scalar, 3> multisite_tensor = tools::finite::opt::find_ground_state(tensors, ritz);
if constexpr(settings::debug)
tools::log->debug("Variance after opt: {:.8f}", std::log10(tools::finite::measure::energy_variance_per_site(multisite_tensor, tensors)));
tensors.merge_multisite_tensor(multisite_tensor, status.chi_lim);
if constexpr(settings::debug)
tools::log->debug("Variance after svd: {:.8f} | trunc: {}", std::log10(tools::finite::measure::energy_variance_per_site(tensors)),
tools::finite::measure::truncation_errors_active(*tensors.state));
status.wall_time = tools::common::profile::t_tot->get_measured_time();
status.algo_time = tools::common::profile::prof[algo_type]["t_sim"]->get_measured_time();
}
void class_flbit::check_convergence() {
tools::common::profile::prof[algo_type]["t_con"]->tic();
if(tensors.position_is_any_edge()) {
check_convergence_variance();
check_convergence_entg_entropy();
}
status.algorithm_has_saturated =
(status.variance_mpo_saturated_for >= min_saturation_iters and status.entanglement_saturated_for >= min_saturation_iters);
// or
// (status.variance_mpo_saturated_for >= max_saturation_iters or status.entanglement_saturated_for >= max_saturation_iters);
status.algorithm_has_converged = status.variance_mpo_has_converged and status.entanglement_has_converged;
status.algorithm_has_succeeded = status.algorithm_has_saturated and status.algorithm_has_converged;
status.algorithm_has_got_stuck = status.algorithm_has_saturated and not status.algorithm_has_converged;
if(tensors.state->position_is_any_edge()) status.algorithm_has_stuck_for = status.algorithm_has_got_stuck ? status.algorithm_has_stuck_for + 1 : 0;
status.algorithm_has_to_stop = status.algorithm_has_stuck_for >= max_stuck_iters;
if(tensors.state->position_is_any_edge()) {
tools::log->debug("Simulation report: converged {} | saturated {} | succeeded {} | stuck {} for {} iters | has to stop {}",
status.algorithm_has_converged, status.algorithm_has_saturated, status.algorithm_has_succeeded, status.algorithm_has_got_stuck,
status.algorithm_has_stuck_for, status.algorithm_has_to_stop);
}
if(tensors.position_is_any_edge()) {
stop_reason = StopReason::NONE;
if(status.iter >= settings::flbit::max_iters) stop_reason = StopReason::MAX_ITERS;
if(status.algorithm_has_succeeded) stop_reason = StopReason::SUCCEEDED;
if(status.algorithm_has_to_stop) stop_reason = StopReason::SATURATED;
if(status.num_resets > settings::strategy::max_resets) stop_reason = StopReason::MAX_RESET;
}
tools::common::profile::prof[algo_type]["t_con"]->toc();
}
bool class_flbit::cfg_algorithm_is_on() { return settings::flbit::on; }
long class_flbit::cfg_chi_lim_max() { return settings::flbit::chi_lim_max; }
size_t class_flbit::cfg_print_freq() { return settings::flbit::print_freq; }
bool class_flbit::cfg_chi_lim_grow() { return settings::flbit::chi_lim_grow; }
long class_flbit::cfg_chi_lim_init() { return settings::flbit::chi_lim_init; }
bool class_flbit::cfg_store_wave_function() { return settings::flbit::store_wavefn; }
<commit_msg>Work in progress: building flbit algorithm<commit_after>//
// Created by david on 2018-01-31.
//
#include "class_flbit.h"
#include <config/nmspc_settings.h>
#include <general/nmspc_tensor_extra.h>
#include <physics/nmspc_quantum_mechanics.h>
#include <tensors/model/class_model_finite.h>
#include <tensors/state/class_mps_site.h>
#include <tensors/state/class_state_finite.h>
#include <tools/common/fmt.h>
#include <tools/common/io.h>
#include <tools/common/log.h>
#include <tools/common/prof.h>
#include <tools/finite/io.h>
#include <tools/finite/measure.h>
#include <tools/finite/mps.h>
#include <tools/finite/ops.h>
#include <tools/finite/opt.h>
#include <tools/finite/print.h>
#include <unsupported/Eigen/CXX11/Tensor>
class_flbit::class_flbit(std::shared_ptr<h5pp::File> h5pp_file_) : class_algorithm_finite(std::move(h5pp_file_), AlgorithmType::fLBIT) {
tools::log->trace("Constructing class_flbit");
}
void class_flbit::resume() {
// Resume can imply many things
// 1) Resume a simulation which terminated prematurely
// 2) Resume a previously successful simulation. This may be desireable if the config
// wants something that is not present in the file.
// a) A certain number of states
// b) A state inside of a particular energy window
// c) The ground or "roof" states
// To guide the behavior, we check the setting ResumePolicy.
auto state_prefix = tools::common::io::h5resume::find_resumable_state(*h5pp_file, algo_type);
if(state_prefix.empty()) throw std::runtime_error("Could not resume: no valid state candidates found for resume");
tools::log->info("Resuming state [{}]", state_prefix);
tools::finite::io::h5resume::load_simulation(*h5pp_file, state_prefix, tensors, status);
clear_convergence_status();
// Our first task is to decide on a state name for the newly loaded state
// The simplest is to inferr it from the state prefix itself
auto name = tools::common::io::h5resume::extract_state_name(state_prefix);
// Initialize a custom task list
std::list<flbit_task> task_list;
if(not status.algorithm_has_finished) {
// This could be a checkpoint state
// Simply "continue" the algorithm until convergence
if(name.find("emax") != std::string::npos) task_list.emplace_back(flbit_task::FIND_HIGHEST_STATE);
else if(name.find("emin") != std::string::npos)
task_list.emplace_back(flbit_task::FIND_GROUND_STATE);
else
throw std::runtime_error(fmt::format("Unrecognized state name for flbit: [{}]", name));
task_list.emplace_back(flbit_task::POST_DEFAULT);
run_task_list(task_list);
}
// If we reached this point the current state has finished for one reason or another.
// TODO: We may still have some more things to do, e.g. the config may be asking for more states
}
void class_flbit::run_task_list(std::list<flbit_task> &task_list) {
while(not task_list.empty()) {
auto task = task_list.front();
switch(task) {
case flbit_task::INIT_RANDOMIZE_MODEL: randomize_model(); break;
case flbit_task::INIT_RANDOMIZE_INTO_PRODUCT_STATE: randomize_state(ResetReason::INIT, StateInit::RANDOM_PRODUCT_STATE); break;
case flbit_task::INIT_RANDOMIZE_INTO_ENTANGLED_STATE: randomize_state(ResetReason::INIT, StateInit::RANDOM_ENTANGLED_STATE); break;
case flbit_task::INIT_BOND_DIM_LIMITS: init_bond_dimension_limits(); break;
case flbit_task::INIT_WRITE_MODEL: write_to_file(StorageReason::MODEL); break;
case flbit_task::INIT_CLEAR_STATUS: status.clear(); break;
case flbit_task::INIT_DEFAULT: run_preprocessing(); break;
case flbit_task::FIND_GROUND_STATE:
ritz = StateRitz::SR;
state_name = "state_e_min";
run_algorithm();
break;
case flbit_task::FIND_HIGHEST_STATE:
ritz = StateRitz::LR;
state_name = "state_e_max";
run_algorithm();
break;
case flbit_task::POST_WRITE_RESULT: write_to_file(StorageReason::FINISHED); break;
case flbit_task::POST_PRINT_RESULT: print_status_full(); break;
case flbit_task::POST_PRINT_PROFILING: tools::common::profile::print_profiling(algo_type); break;
case flbit_task::POST_DEFAULT: run_postprocessing(); break;
case flbit_task::PROF_RESET: tools::common::profile::reset_profiling(algo_type); break;
}
task_list.pop_front();
}
}
void class_flbit::run_default_task_list() {
std::list<flbit_task> default_task_list = {
flbit_task::INIT_DEFAULT,
flbit_task::FIND_GROUND_STATE,
flbit_task::POST_DEFAULT,
};
run_task_list(default_task_list);
if(not default_task_list.empty()) {
for(auto &task : default_task_list) tools::log->critical("Unfinished task: {}", enum2str(task));
throw std::runtime_error("Simulation ended with unfinished tasks");
}
}
void class_flbit::run_preprocessing() {
tools::log->info("Running {} preprocessing", algo_name);
tools::common::profile::prof[algo_type]["t_pre"]->tic();
status.clear();
randomize_model(); // First use of random!
init_bond_dimension_limits();
randomize_state(ResetReason::INIT, settings::strategy::initial_state);
Eigen::Tensor<Scalar,3> xplus_spinor = Textra::MatrixToTensor(tools::finite::mps::internal::get_spinor("x", 1).normalized(), 2, 1, 1);
Eigen::Tensor<Scalar,3> zminus_spinor = Textra::MatrixToTensor(tools::finite::mps::internal::get_spinor("z", -1).normalized(), 2, 1, 1);
tensors.state->get_mps_site(1).set_M(xplus_spinor);
tensors.state->get_mps_site(2).set_M(zminus_spinor);
tools::finite::print::model(*tensors.model);
// Time evolve here
auto delta_t = std::complex<double>(0.0,-0.3);
std::vector<Eigen::Tensor<Scalar,2>> twosite_hamiltonian_operators;
for(size_t pos = 0; pos < settings::model::model_size-1; pos++)
twosite_hamiltonian_operators.emplace_back(tensors.model->get_multisite_ham({pos,pos+1}));
auto time_evolution_operators = qm::lbit::get_twosite_time_evolution_operators(settings::model::model_size, delta_t, twosite_hamiltonian_operators);
tools::finite::mps::apply_twosite_gates(*tensors.state,time_evolution_operators,false, status.chi_lim);
// tools::finite::mps::apply_twosite_gates(*tensors.state,time_evolution_operators,true, status.chi_lim);
exit(0);
auto unitary_twosite_operators0 = qm::lbit::get_unitary_twosite_operators(settings::model::model_size,0.1);
auto unitary_twosite_operators1 = qm::lbit::get_unitary_twosite_operators(settings::model::model_size,0.1);
auto unitary_twosite_operators2 = qm::lbit::get_unitary_twosite_operators(settings::model::model_size,0.1);
auto unitary_twosite_operators3 = qm::lbit::get_unitary_twosite_operators(settings::model::model_size,0.1);
tools::finite::mps::apply_twosite_gates(*tensors.state,unitary_twosite_operators0,false, status.chi_lim);
tools::finite::mps::apply_twosite_gates(*tensors.state,unitary_twosite_operators1,false, status.chi_lim);
tools::finite::mps::apply_twosite_gates(*tensors.state,unitary_twosite_operators2,false, status.chi_lim);
tools::finite::mps::apply_twosite_gates(*tensors.state,unitary_twosite_operators3,false, status.chi_lim);
tools::finite::mps::apply_twosite_gates(*tensors.state,unitary_twosite_operators3,true, status.chi_lim);
tools::finite::mps::apply_twosite_gates(*tensors.state,unitary_twosite_operators2,true, status.chi_lim);
tools::finite::mps::apply_twosite_gates(*tensors.state,unitary_twosite_operators1,true, status.chi_lim);
tools::finite::mps::apply_twosite_gates(*tensors.state,unitary_twosite_operators0,true, status.chi_lim);
exit(0);
tools::common::profile::prof[algo_type]["t_pre"]->toc();
tools::log->info("Finished {} preprocessing", algo_name);
}
void class_flbit::run_algorithm() {
if(state_name.empty()) state_name = ritz == StateRitz::SR ? "state_emin" : "state_emax";
tools::log->info("Starting {} algorithm with model [{}] for state [{}]", algo_name, enum2str(settings::model::model_type), state_name);
tools::common::profile::prof[algo_type]["t_sim"]->tic();
while(true) {
single_flbit_step();
// Update record holder
if(tensors.position_is_any_edge() or tensors.measurements.energy_variance_per_site) {
tools::log->trace("Updating variance record holder");
auto var = tools::finite::measure::energy_variance(tensors);
if(var < status.energy_variance_lowest) status.energy_variance_lowest = var;
}
check_convergence();
print_status_update();
print_profiling_lap();
write_to_file();
tools::log->trace("Finished step {}, iter {}, pos {}, dir {}", status.step, status.iter, status.position, status.direction);
// It's important not to perform the last move, so we break now: that last state would not get optimized
if(stop_reason != StopReason::NONE) break;
update_bond_dimension_limit(); // Will update bond dimension if the state precision is being limited by bond dimension
try_projection();
reduce_mpo_energy();
move_center_point();
}
tools::log->info("Finished {} simulation of state [{}] -- stop reason: {}", algo_name, state_name, enum2str(stop_reason));
status.algorithm_has_finished = true;
tools::common::profile::prof[algo_type]["t_sim"]->toc();
}
void class_flbit::single_flbit_step() {
/*!
* \fn void single_DMRG_step(std::string ritz)
*/
tools::log->trace("Starting single flbit step with ritz [{}]", enum2str(ritz));
tensors.activate_sites(settings::precision::max_size_part_diag, 2);
Eigen::Tensor<Scalar, 3> multisite_tensor = tools::finite::opt::find_ground_state(tensors, ritz);
if constexpr(settings::debug)
tools::log->debug("Variance after opt: {:.8f}", std::log10(tools::finite::measure::energy_variance_per_site(multisite_tensor, tensors)));
tensors.merge_multisite_tensor(multisite_tensor, status.chi_lim);
if constexpr(settings::debug)
tools::log->debug("Variance after svd: {:.8f} | trunc: {}", std::log10(tools::finite::measure::energy_variance_per_site(tensors)),
tools::finite::measure::truncation_errors_active(*tensors.state));
status.wall_time = tools::common::profile::t_tot->get_measured_time();
status.algo_time = tools::common::profile::prof[algo_type]["t_sim"]->get_measured_time();
}
void class_flbit::check_convergence() {
tools::common::profile::prof[algo_type]["t_con"]->tic();
if(tensors.position_is_any_edge()) {
check_convergence_variance();
check_convergence_entg_entropy();
}
status.algorithm_has_saturated =
(status.variance_mpo_saturated_for >= min_saturation_iters and status.entanglement_saturated_for >= min_saturation_iters);
// or
// (status.variance_mpo_saturated_for >= max_saturation_iters or status.entanglement_saturated_for >= max_saturation_iters);
status.algorithm_has_converged = status.variance_mpo_has_converged and status.entanglement_has_converged;
status.algorithm_has_succeeded = status.algorithm_has_saturated and status.algorithm_has_converged;
status.algorithm_has_got_stuck = status.algorithm_has_saturated and not status.algorithm_has_converged;
if(tensors.state->position_is_any_edge()) status.algorithm_has_stuck_for = status.algorithm_has_got_stuck ? status.algorithm_has_stuck_for + 1 : 0;
status.algorithm_has_to_stop = status.algorithm_has_stuck_for >= max_stuck_iters;
if(tensors.state->position_is_any_edge()) {
tools::log->debug("Simulation report: converged {} | saturated {} | succeeded {} | stuck {} for {} iters | has to stop {}",
status.algorithm_has_converged, status.algorithm_has_saturated, status.algorithm_has_succeeded, status.algorithm_has_got_stuck,
status.algorithm_has_stuck_for, status.algorithm_has_to_stop);
}
if(tensors.position_is_any_edge()) {
stop_reason = StopReason::NONE;
if(status.iter >= settings::flbit::max_iters) stop_reason = StopReason::MAX_ITERS;
if(status.algorithm_has_succeeded) stop_reason = StopReason::SUCCEEDED;
if(status.algorithm_has_to_stop) stop_reason = StopReason::SATURATED;
if(status.num_resets > settings::strategy::max_resets) stop_reason = StopReason::MAX_RESET;
}
tools::common::profile::prof[algo_type]["t_con"]->toc();
}
bool class_flbit::cfg_algorithm_is_on() { return settings::flbit::on; }
long class_flbit::cfg_chi_lim_max() { return settings::flbit::chi_lim_max; }
size_t class_flbit::cfg_print_freq() { return settings::flbit::print_freq; }
bool class_flbit::cfg_chi_lim_grow() { return settings::flbit::chi_lim_grow; }
long class_flbit::cfg_chi_lim_init() { return settings::flbit::chi_lim_init; }
bool class_flbit::cfg_store_wave_function() { return settings::flbit::store_wavefn; }
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login_manager_view.h"
#include <signal.h>
#include <sys/types.h>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_path.h"
#include "base/keyboard_codes.h"
#include "base/logging.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "chrome/browser/chromeos/image_background.h"
#include "chrome/browser/chromeos/login_library.h"
#include "chrome/browser/chromeos/network_library.h"
#include "chrome/common/chrome_switches.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/controls/label.h"
#include "views/widget/widget.h"
#include "views/window/non_client_view.h"
#include "views/window/window.h"
#include "views/window/window_gtk.h"
using views::Background;
using views::Label;
using views::Textfield;
using views::View;
using views::Widget;
const int kUsernameY = 386;
const int kPanelSpacing = 36;
const int kVersionPad = 4;
const int kTextfieldWidth = 286;
const SkColor kVersionColor = 0xFF7691DA;
const SkColor kErrorColor = 0xFF8F384F;
const char *kDefaultDomain = "@gmail.com";
namespace browser {
// Acts as a frame view with no UI.
class LoginManagerNonClientFrameView : public views::NonClientFrameView {
public:
explicit LoginManagerNonClientFrameView() : views::NonClientFrameView() {}
// Returns just the bounds of the window.
virtual gfx::Rect GetBoundsForClientView() const { return bounds(); }
// Doesn't add any size to the client bounds.
virtual gfx::Rect GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
return client_bounds;
}
// There is no system menu.
virtual gfx::Point GetSystemMenuPoint() const { return gfx::Point(); }
// There is no non client area.
virtual int NonClientHitTest(const gfx::Point& point) { return 0; }
// There is no non client area.
virtual void GetWindowMask(const gfx::Size& size,
gfx::Path* window_mask) {}
virtual void EnableClose(bool enable) {}
virtual void ResetWindowControls() {}
DISALLOW_COPY_AND_ASSIGN(LoginManagerNonClientFrameView);
};
// Subclass of WindowGtk, for use as the top level login window.
class LoginManagerWindow : public views::WindowGtk {
public:
static LoginManagerWindow* CreateLoginManagerWindow() {
LoginManagerWindow* login_manager_window =
new LoginManagerWindow();
login_manager_window->GetNonClientView()->SetFrameView(
new LoginManagerNonClientFrameView());
login_manager_window->Init(NULL, gfx::Rect());
return login_manager_window;
}
private:
LoginManagerWindow() : views::WindowGtk(new LoginManagerView) {
}
DISALLOW_COPY_AND_ASSIGN(LoginManagerWindow);
};
// Declared in browser_dialogs.h so that others don't need to depend on our .h.
void ShowLoginManager() {
// if we can't load the library, we'll tell the user in LoginManagerView.
views::WindowGtk* window =
LoginManagerWindow::CreateLoginManagerWindow();
window->Show();
if (chromeos::LoginLibrary::EnsureLoaded())
chromeos::LoginLibrary::Get()->EmitLoginPromptReady();
bool old_state = MessageLoop::current()->NestableTasksAllowed();
MessageLoop::current()->SetNestableTasksAllowed(true);
MessageLoop::current()->Run();
MessageLoop::current()->SetNestableTasksAllowed(old_state);
}
} // namespace browser
LoginManagerView::LoginManagerView() {
Init();
}
LoginManagerView::~LoginManagerView() {
MessageLoop::current()->Quit();
}
void LoginManagerView::Init() {
username_field_ = new views::Textfield;
username_field_->RemoveBorder();
password_field_ = new views::Textfield(views::Textfield::STYLE_PASSWORD);
password_field_->RemoveBorder();
os_version_label_ = new views::Label();
os_version_label_->SetColor(kVersionColor);
os_version_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
error_label_ = new views::Label();
error_label_->SetColor(kErrorColor);
error_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
// Creates the main window
BuildWindow();
// Controller to handle events from textfields
username_field_->SetController(this);
password_field_->SetController(this);
if (chromeos::LoginLibrary::EnsureLoaded()) {
loader_.GetVersion(
&consumer_, NewCallback(this, &LoginManagerView::OnOSVersion));
}
}
gfx::Size LoginManagerView::GetPreferredSize() {
return dialog_dimensions_;
}
void LoginManagerView::BuildWindow() {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
panel_pixbuf_ = rb.GetPixbufNamed(IDR_LOGIN_PANEL);
background_pixbuf_ = rb.GetPixbufNamed(IDR_LOGIN_BACKGROUND);
// --------------------- Get attributes of images -----------------------
dialog_dimensions_.SetSize(gdk_pixbuf_get_width(background_pixbuf_),
gdk_pixbuf_get_height(background_pixbuf_));
int panel_height = gdk_pixbuf_get_height(panel_pixbuf_);
int panel_width = gdk_pixbuf_get_width(panel_pixbuf_);
// ---------------------- Set up root View ------------------------------
set_background(new views::ImageBackground(background_pixbuf_));
View* login_prompt = new View();
login_prompt->set_background(new views::ImageBackground(panel_pixbuf_));
login_prompt->SetBounds(0, 0, panel_width, panel_height);
int x = (panel_width - kTextfieldWidth) / 2;
int y = kUsernameY;
username_field_->SetBounds(x, y, kTextfieldWidth, kPanelSpacing);
y += 2 * kPanelSpacing;
password_field_->SetBounds(x, y, kTextfieldWidth, kPanelSpacing);
y += 2 * kPanelSpacing;
os_version_label_->SetBounds(
x,
y,
panel_width - (x + kVersionPad),
os_version_label_->GetPreferredSize().height());
y += kPanelSpacing;
error_label_->SetBounds(
x,
y,
panel_width - (x + kVersionPad),
error_label_->GetPreferredSize().height());
login_prompt->AddChildView(username_field_);
login_prompt->AddChildView(password_field_);
login_prompt->AddChildView(os_version_label_);
login_prompt->AddChildView(error_label_);
AddChildView(login_prompt);
if (!chromeos::LoginLibrary::EnsureLoaded()) {
username_field_->SetText(
l10n_util::GetStringUTF16(IDS_LOGIN_DISABLED_NO_LIBCROS));
username_field_->SetReadOnly(true);
password_field_->SetReadOnly(true);
}
return;
}
views::View* LoginManagerView::GetContentsView() {
return this;
}
bool LoginManagerView::Authenticate(const std::string& username,
const std::string& password) {
base::ProcessHandle handle;
std::vector<std::string> argv;
// TODO(cmasone): we'll want this to be configurable.
argv.push_back("/opt/google/chrome/session");
argv.push_back(username);
argv.push_back(password);
base::environment_vector no_env;
base::file_handle_mapping_vector no_files;
base::LaunchApp(argv, no_env, no_files, false, &handle);
int child_exit_code;
return base::WaitForExitCode(handle, &child_exit_code) &&
child_exit_code == 0;
}
void LoginManagerView::SetupSession(const std::string& username) {
if (window()) {
window()->Close();
}
if (username.find("@google.com") != std::string::npos) {
// This isn't thread-safe. However, the login window is specifically
// supposed to be run in a blocking fashion, before any other threads are
// created by the initial browser process.
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAutoSSLClientAuth);
}
if (chromeos::LoginLibrary::EnsureLoaded())
chromeos::LoginLibrary::Get()->StartSession(username, "");
}
bool LoginManagerView::HandleKeystroke(views::Textfield* s,
const views::Textfield::Keystroke& keystroke) {
if (!chromeos::LoginLibrary::EnsureLoaded())
return false;
if (keystroke.GetKeyboardCode() == base::VKEY_TAB) {
if (username_field_->text().length() != 0) {
std::string username = UTF16ToUTF8(username_field_->text());
if (username.find('@') == std::string::npos) {
username += kDefaultDomain;
username_field_->SetText(UTF8ToUTF16(username));
}
return false;
}
} else if (keystroke.GetKeyboardCode() == base::VKEY_RETURN) {
// Disallow 0 size username.
if (username_field_->text().length() == 0) {
// Return true so that processing ends
return true;
} else {
chromeos::NetworkLibrary* network = chromeos::NetworkLibrary::Get();
if (!network || !network->EnsureLoaded()) {
error_label_->SetText(
l10n_util::GetString(IDS_LOGIN_ERROR_NO_NETWORK_LIBRARY));
return true;
}
if (!network->Connected()) {
error_label_->SetText(
l10n_util::GetString(IDS_LOGIN_ERROR_NETWORK_NOT_CONNECTED));
return true;
}
std::string username = UTF16ToUTF8(username_field_->text());
// todo(cmasone) Need to sanitize memory used to store password.
std::string password = UTF16ToUTF8(password_field_->text());
if (username.find('@') == std::string::npos) {
username += kDefaultDomain;
username_field_->SetText(UTF8ToUTF16(username));
}
// Set up credentials to prepare for authentication.
if (!Authenticate(username, password)) {
error_label_->SetText(
l10n_util::GetString(IDS_LOGIN_ERROR_AUTHENTICATING));
return true;
}
// TODO(cmasone): something sensible if errors occur.
SetupSession(username);
// Return true so that processing ends
return true;
}
}
// Return false so that processing does not end
return false;
}
void LoginManagerView::OnOSVersion(
chromeos::VersionLoader::Handle handle,
std::string version) {
os_version_label_->SetText(ASCIIToWide(version));
}
<commit_msg>allow login without network This allows locally cached logins and admin logins to work.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login_manager_view.h"
#include <signal.h>
#include <sys/types.h>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_path.h"
#include "base/keyboard_codes.h"
#include "base/logging.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "chrome/browser/chromeos/image_background.h"
#include "chrome/browser/chromeos/login_library.h"
#include "chrome/browser/chromeos/network_library.h"
#include "chrome/common/chrome_switches.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/controls/label.h"
#include "views/widget/widget.h"
#include "views/window/non_client_view.h"
#include "views/window/window.h"
#include "views/window/window_gtk.h"
using views::Background;
using views::Label;
using views::Textfield;
using views::View;
using views::Widget;
const int kUsernameY = 386;
const int kPanelSpacing = 36;
const int kVersionPad = 4;
const int kTextfieldWidth = 286;
const SkColor kVersionColor = 0xFF7691DA;
const SkColor kErrorColor = 0xFF8F384F;
const char *kDefaultDomain = "@gmail.com";
namespace browser {
// Acts as a frame view with no UI.
class LoginManagerNonClientFrameView : public views::NonClientFrameView {
public:
explicit LoginManagerNonClientFrameView() : views::NonClientFrameView() {}
// Returns just the bounds of the window.
virtual gfx::Rect GetBoundsForClientView() const { return bounds(); }
// Doesn't add any size to the client bounds.
virtual gfx::Rect GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
return client_bounds;
}
// There is no system menu.
virtual gfx::Point GetSystemMenuPoint() const { return gfx::Point(); }
// There is no non client area.
virtual int NonClientHitTest(const gfx::Point& point) { return 0; }
// There is no non client area.
virtual void GetWindowMask(const gfx::Size& size,
gfx::Path* window_mask) {}
virtual void EnableClose(bool enable) {}
virtual void ResetWindowControls() {}
DISALLOW_COPY_AND_ASSIGN(LoginManagerNonClientFrameView);
};
// Subclass of WindowGtk, for use as the top level login window.
class LoginManagerWindow : public views::WindowGtk {
public:
static LoginManagerWindow* CreateLoginManagerWindow() {
LoginManagerWindow* login_manager_window =
new LoginManagerWindow();
login_manager_window->GetNonClientView()->SetFrameView(
new LoginManagerNonClientFrameView());
login_manager_window->Init(NULL, gfx::Rect());
return login_manager_window;
}
private:
LoginManagerWindow() : views::WindowGtk(new LoginManagerView) {
}
DISALLOW_COPY_AND_ASSIGN(LoginManagerWindow);
};
// Declared in browser_dialogs.h so that others don't need to depend on our .h.
void ShowLoginManager() {
// if we can't load the library, we'll tell the user in LoginManagerView.
views::WindowGtk* window =
LoginManagerWindow::CreateLoginManagerWindow();
window->Show();
if (chromeos::LoginLibrary::EnsureLoaded())
chromeos::LoginLibrary::Get()->EmitLoginPromptReady();
bool old_state = MessageLoop::current()->NestableTasksAllowed();
MessageLoop::current()->SetNestableTasksAllowed(true);
MessageLoop::current()->Run();
MessageLoop::current()->SetNestableTasksAllowed(old_state);
}
} // namespace browser
LoginManagerView::LoginManagerView() {
Init();
}
LoginManagerView::~LoginManagerView() {
MessageLoop::current()->Quit();
}
void LoginManagerView::Init() {
username_field_ = new views::Textfield;
username_field_->RemoveBorder();
password_field_ = new views::Textfield(views::Textfield::STYLE_PASSWORD);
password_field_->RemoveBorder();
os_version_label_ = new views::Label();
os_version_label_->SetColor(kVersionColor);
os_version_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
error_label_ = new views::Label();
error_label_->SetColor(kErrorColor);
error_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
// Creates the main window
BuildWindow();
// Controller to handle events from textfields
username_field_->SetController(this);
password_field_->SetController(this);
if (chromeos::LoginLibrary::EnsureLoaded()) {
loader_.GetVersion(
&consumer_, NewCallback(this, &LoginManagerView::OnOSVersion));
}
}
gfx::Size LoginManagerView::GetPreferredSize() {
return dialog_dimensions_;
}
void LoginManagerView::BuildWindow() {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
panel_pixbuf_ = rb.GetPixbufNamed(IDR_LOGIN_PANEL);
background_pixbuf_ = rb.GetPixbufNamed(IDR_LOGIN_BACKGROUND);
// --------------------- Get attributes of images -----------------------
dialog_dimensions_.SetSize(gdk_pixbuf_get_width(background_pixbuf_),
gdk_pixbuf_get_height(background_pixbuf_));
int panel_height = gdk_pixbuf_get_height(panel_pixbuf_);
int panel_width = gdk_pixbuf_get_width(panel_pixbuf_);
// ---------------------- Set up root View ------------------------------
set_background(new views::ImageBackground(background_pixbuf_));
View* login_prompt = new View();
login_prompt->set_background(new views::ImageBackground(panel_pixbuf_));
login_prompt->SetBounds(0, 0, panel_width, panel_height);
int x = (panel_width - kTextfieldWidth) / 2;
int y = kUsernameY;
username_field_->SetBounds(x, y, kTextfieldWidth, kPanelSpacing);
y += 2 * kPanelSpacing;
password_field_->SetBounds(x, y, kTextfieldWidth, kPanelSpacing);
y += 2 * kPanelSpacing;
os_version_label_->SetBounds(
x,
y,
panel_width - (x + kVersionPad),
os_version_label_->GetPreferredSize().height());
y += kPanelSpacing;
error_label_->SetBounds(
x,
y,
panel_width - (x + kVersionPad),
error_label_->GetPreferredSize().height());
login_prompt->AddChildView(username_field_);
login_prompt->AddChildView(password_field_);
login_prompt->AddChildView(os_version_label_);
login_prompt->AddChildView(error_label_);
AddChildView(login_prompt);
if (!chromeos::LoginLibrary::EnsureLoaded()) {
error_label->SetText(
l10n_util::GetStringUTF16(IDS_LOGIN_DISABLED_NO_LIBCROS));
username_field_->SetReadOnly(true);
password_field_->SetReadOnly(true);
}
return;
}
views::View* LoginManagerView::GetContentsView() {
return this;
}
bool LoginManagerView::Authenticate(const std::string& username,
const std::string& password) {
base::ProcessHandle handle;
std::vector<std::string> argv;
// TODO(cmasone): we'll want this to be configurable.
argv.push_back("/opt/google/chrome/session");
argv.push_back(username);
argv.push_back(password);
base::environment_vector no_env;
base::file_handle_mapping_vector no_files;
base::LaunchApp(argv, no_env, no_files, false, &handle);
int child_exit_code;
return base::WaitForExitCode(handle, &child_exit_code) &&
child_exit_code == 0;
}
void LoginManagerView::SetupSession(const std::string& username) {
if (window()) {
window()->Close();
}
if (username.find("@google.com") != std::string::npos) {
// This isn't thread-safe. However, the login window is specifically
// supposed to be run in a blocking fashion, before any other threads are
// created by the initial browser process.
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAutoSSLClientAuth);
}
if (chromeos::LoginLibrary::EnsureLoaded())
chromeos::LoginLibrary::Get()->StartSession(username, "");
}
bool LoginManagerView::HandleKeystroke(views::Textfield* s,
const views::Textfield::Keystroke& keystroke) {
if (!chromeos::LoginLibrary::EnsureLoaded())
return false;
if (keystroke.GetKeyboardCode() == base::VKEY_TAB) {
if (username_field_->text().length() != 0) {
std::string username = UTF16ToUTF8(username_field_->text());
if (username.find('@') == std::string::npos) {
username += kDefaultDomain;
username_field_->SetText(UTF8ToUTF16(username));
}
return false;
}
} else if (keystroke.GetKeyboardCode() == base::VKEY_RETURN) {
// Disallow 0 size username.
if (username_field_->text().length() == 0) {
// Return true so that processing ends
return true;
} else {
std::string username = UTF16ToUTF8(username_field_->text());
// todo(cmasone) Need to sanitize memory used to store password.
std::string password = UTF16ToUTF8(password_field_->text());
if (username.find('@') == std::string::npos) {
username += kDefaultDomain;
username_field_->SetText(UTF8ToUTF16(username));
}
// Set up credentials to prepare for authentication.
if (!Authenticate(username, password)) {
chromeos::NetworkLibrary* network = chromeos::NetworkLibrary::Get();
int errorID;
// Check networking after trying to login in case user is
// cached locally or the local admin account.
if (!network || !network->EnsureLoaded())
errorID = IDS_LOGIN_ERROR_NO_NETWORK_LIBRARY;
else if (!network->Connected())
errorID = IDS_LOGIN_ERROR_NETWORK_NOT_CONNECTED;
else
errorID = IDS_LOGIN_ERROR_AUTHENTICATING;
error_label_->SetText(l10n_util::GetString(errorID));
return true;
}
// TODO(cmasone): something sensible if errors occur.
SetupSession(username);
// Return true so that processing ends
return true;
}
}
// Return false so that processing does not end
return false;
}
void LoginManagerView::OnOSVersion(
chromeos::VersionLoader::Handle handle,
std::string version) {
os_version_label_->SetText(ASCIIToWide(version));
}
<|endoftext|> |
<commit_before>// MidiClient.cpp
#include "stdafx.h"
#include "WinRTMidi.h"
#include <iostream>
#include <mutex>
#include <string>
using namespace std;
using namespace WinRT;
std::mutex g_mutex;
WinRTWatcherPortCountFunc gWatcherPortCountFunc = nullptr;
WinRTWatcherPortNameFunc gWatcherPortNameFunc = nullptr;
WinRTWatcherPortTypeFunc gWatcherPortTypeFunc = nullptr;
void printPortNames(const WinRTMidiPortWatcherPtr watcher)
{
if (watcher == nullptr)
{
return;
}
WinRTMidiPortType type = gWatcherPortTypeFunc(watcher);
if (type == WinRTMidiPortType::In)
{
cout << "MIDI In Ports" << endl;
}
else
{
cout << "MIDI Out Ports" << endl;
}
int nPorts = gWatcherPortCountFunc(watcher);
for (int i = 0; i < nPorts; i++)
{
const char* name = gWatcherPortNameFunc(watcher, i);
cout << i << ": " << gWatcherPortNameFunc(watcher, i) << endl;
}
cout << endl;
}
void midiPortChangedCallback(const WinRTMidiPortWatcherPtr portWatcher, WinRTMidiPortUpdateType update)
{
lock_guard<mutex> lock(g_mutex);
//string portName = portWatcher->GetPortType() == WinRTMidiPortType::In ? "In" : "Out";
std::string portName = "In";
switch (update)
{
case WinRTMidiPortUpdateType::PortAdded:
cout << "***MIDI " << portName << " port added***" << endl;
break;
case WinRTMidiPortUpdateType::PortRemoved:
cout << "***MIDI " << portName << " port removed***" << endl;
break;
case WinRTMidiPortUpdateType::EnumerationComplete:
cout << "***MIDI " << portName << " port enumeration complete***" << endl;
break;
}
printPortNames(portWatcher);
}
void midiInCallback(const WinRTMidiInPortPtr port, double timeStamp, const unsigned char* message, unsigned int nBytes)
{
for (unsigned int i = 0; i < nBytes; i++)
{
cout << "Byte " << i << " = " << (int)message[i] << ", ";
}
if (nBytes > 0)
{
cout << "timestamp = " << timeStamp << endl;
}
}
int main()
{
HINSTANCE dllHandle = NULL;
WinRTMidiPtr midiPtr = nullptr;
WinRTMidiInPortPtr midiInPort = nullptr;
//Load the dll and keep the handle to it
dllHandle = LoadLibrary(L"WinRTMidi.dll");
// If the handle is valid, try to get the function addresses.
if (NULL != dllHandle)
{
//Get pointer to the WinRTWatcherPortCountFunc function using GetProcAddress:
gWatcherPortCountFunc = reinterpret_cast<WinRTWatcherPortCountFunc>(::GetProcAddress(dllHandle, "winrt_watcher_get_port_count"));
//Get pointer to the WinRTWatcherPortCountFunc function using GetProcAddress:
gWatcherPortNameFunc = reinterpret_cast<WinRTWatcherPortNameFunc>(::GetProcAddress(dllHandle, "winrt_watcher_get_port_name"));
//Get pointer to the WinRTWatcherPortCountFunc function using GetProcAddress:
gWatcherPortTypeFunc = reinterpret_cast<WinRTWatcherPortTypeFunc>(::GetProcAddress(dllHandle, "winrt_watcher_get_port_type"));
//Get pointer to the WinRTMidiInitializeFunc function using GetProcAddress:
WinRTMidiInitializeFunc MidiInitFunc = reinterpret_cast<WinRTMidiInitializeFunc>(::GetProcAddress(dllHandle, "winrt_initialize_midi"));
if (NULL != MidiInitFunc)
{
midiPtr = MidiInitFunc(midiPortChangedCallback);
}
//Get pointer to the WinRTMidiInitializeFunc function using GetProcAddress:
WinRTMidiFreeFunc MidiFreeFunc = reinterpret_cast<WinRTMidiFreeFunc>(::GetProcAddress(dllHandle, "winrt_free_midi"));
#if 0
//Get pointer to the setMidiPortChangedCallback function using GetProcAddress:
SetMidiPortChangedCallbackFunc setCallbackFunc = reinterpret_cast<SetMidiPortChangedCallbackFunc>(::GetProcAddress(dllHandle, "SetMidiPortChangedCallback"));
if (NULL != setCallbackFunc)
{
setCallbackFunc(&midiPortChangedCallback);
}
//Get pointer to the setMidiPortChangedCallback function using GetProcAddress:
GetMidiPortWatcherFunc getMidiPortWatcherFunc = reinterpret_cast<GetMidiPortWatcherFunc>(::GetProcAddress(dllHandle, "GetMidiPortWatcher"));
if (NULL != getMidiPortWatcherFunc)
{
IWinRTMidiPortWatcher* watcher = getMidiPortWatcherFunc(WinRTMidiPortType::In);
int n = watcher->GetPortCount();
std::string name = watcher->GetPortName(0);
}
#endif
//Get pointer to the MidiInPortFreeFunc function using GetProcAddress:
WinRTMidiInPortFreeFunc MidiInPortFreeFunc = reinterpret_cast<WinRTMidiInPortFreeFunc>(::GetProcAddress(dllHandle, "winrt_free_midi_in_port"));
//Get pointer to the MidiInPortOpenFunc function using GetProcAddress:
WinRTMidiInPortOpenFunc MidiInPortOpenFunc = reinterpret_cast<WinRTMidiInPortOpenFunc>(::GetProcAddress(dllHandle, "winrt_open_midi_in_port"));
if (NULL != MidiInPortOpenFunc)
{
midiInPort = MidiInPortOpenFunc(midiPtr, 0, midiInCallback);
}
char c = getchar();
// clean up Midi objects
MidiInPortFreeFunc(midiInPort);
MidiFreeFunc(midiPtr);
//Free the library:
FreeLibrary(dllHandle);
}
return 0;
}<commit_msg>refactor code<commit_after>// MidiClient.cpp
#include "stdafx.h"
#include "WinRTMidi.h"
#include <iostream>
#include <mutex>
#include <string>
using namespace std;
using namespace WinRT;
std::mutex g_mutex;
WinRTWatcherPortCountFunc gWatcherPortCountFunc = nullptr;
WinRTWatcherPortNameFunc gWatcherPortNameFunc = nullptr;
WinRTWatcherPortTypeFunc gWatcherPortTypeFunc = nullptr;
WinRTMidiInitializeFunc gMidiInitFunc = nullptr;
WinRTMidiFreeFunc gMidiFreeFunc = nullptr;
WinRTMidiInPortOpenFunc gMidiInPortOpenFunc = nullptr;
WinRTMidiInPortFreeFunc gMidiInPortFreeFunc = nullptr;
void printPortNames(const WinRTMidiPortWatcherPtr watcher)
{
if (watcher == nullptr)
{
return;
}
WinRTMidiPortType type = gWatcherPortTypeFunc(watcher);
if (type == WinRTMidiPortType::In)
{
cout << "MIDI In Ports" << endl;
}
else
{
cout << "MIDI Out Ports" << endl;
}
int nPorts = gWatcherPortCountFunc(watcher);
for (int i = 0; i < nPorts; i++)
{
const char* name = gWatcherPortNameFunc(watcher, i);
cout << i << ": " << gWatcherPortNameFunc(watcher, i) << endl;
}
cout << endl;
}
void midiPortChangedCallback(const WinRTMidiPortWatcherPtr portWatcher, WinRTMidiPortUpdateType update)
{
lock_guard<mutex> lock(g_mutex);
//string portName = portWatcher->GetPortType() == WinRTMidiPortType::In ? "In" : "Out";
std::string portName = "In";
switch (update)
{
case WinRTMidiPortUpdateType::PortAdded:
cout << "***MIDI " << portName << " port added***" << endl;
break;
case WinRTMidiPortUpdateType::PortRemoved:
cout << "***MIDI " << portName << " port removed***" << endl;
break;
case WinRTMidiPortUpdateType::EnumerationComplete:
cout << "***MIDI " << portName << " port enumeration complete***" << endl;
break;
}
printPortNames(portWatcher);
}
void midiInCallback(const WinRTMidiInPortPtr port, double timeStamp, const unsigned char* message, unsigned int nBytes)
{
for (unsigned int i = 0; i < nBytes; i++)
{
cout << "Byte " << i << " = " << (int)message[i] << ", ";
}
if (nBytes > 0)
{
cout << "timestamp = " << timeStamp << endl;
}
}
int main()
{
HINSTANCE dllHandle = NULL;
WinRTMidiPtr midiPtr = nullptr;
WinRTMidiInPortPtr midiInPort = nullptr;
//Load the dll and keep the handle to it
dllHandle = LoadLibrary(L"WinRTMidi.dll");
if (NULL == dllHandle)
{
cout << "Unable to load WinRTMidi.dll" << endl;
return -1;
}
//Get pointer to the WinRTMidiInitializeFunc function using GetProcAddress:
gMidiInitFunc = reinterpret_cast<WinRTMidiInitializeFunc>(::GetProcAddress(dllHandle, "winrt_initialize_midi"));
//Get pointer to the WinRTMidiFreeFunc function using GetProcAddress:
gMidiFreeFunc = reinterpret_cast<WinRTMidiFreeFunc>(::GetProcAddress(dllHandle, "winrt_free_midi"));
//Get pointer to the MidiInPortOpenFunc function using GetProcAddress:
gMidiInPortOpenFunc = reinterpret_cast<WinRTMidiInPortOpenFunc>(::GetProcAddress(dllHandle, "winrt_open_midi_in_port"));
//Get pointer to the MidiInPortFreeFunc function using GetProcAddress:
gMidiInPortFreeFunc = reinterpret_cast<WinRTMidiInPortFreeFunc>(::GetProcAddress(dllHandle, "winrt_free_midi_in_port"));
//Get pointer to the WinRTWatcherPortCountFunc function using GetProcAddress:
gWatcherPortCountFunc = reinterpret_cast<WinRTWatcherPortCountFunc>(::GetProcAddress(dllHandle, "winrt_watcher_get_port_count"));
//Get pointer to the WinRTWatcherPortCountFunc function using GetProcAddress:
gWatcherPortNameFunc = reinterpret_cast<WinRTWatcherPortNameFunc>(::GetProcAddress(dllHandle, "winrt_watcher_get_port_name"));
//Get pointer to the WinRTWatcherPortCountFunc function using GetProcAddress:
gWatcherPortTypeFunc = reinterpret_cast<WinRTWatcherPortTypeFunc>(::GetProcAddress(dllHandle, "winrt_watcher_get_port_type"));
// initialize Midi interface
midiPtr = gMidiInitFunc(midiPortChangedCallback);
// open Midi In port 0
midiInPort = gMidiInPortOpenFunc(midiPtr, 0, midiInCallback);
// process midi until user presses key on keyboard
char c = getchar();
// clean up midi objects
gMidiInPortFreeFunc(midiInPort);
gMidiFreeFunc(midiPtr);
//Free the library:
FreeLibrary(dllHandle);
return 0;
}<|endoftext|> |
<commit_before>/*
* WIN32 Events for POSIX
* Author: Mahmoud Al-Qudsi <mqudsi@neosmart.net>
* Copyright (C) 2011 - 2015 by NeoSmart Technologies
* This code is released under the terms of the MIT License
*/
#ifdef _WIN32
#include <Windows.h>
#include "pevents.h"
namespace neosmart
{
neosmart_event_t CreateEvent(bool manualReset, bool initialState)
{
return static_cast<neosmart_event_t>(::CreateEvent(NULL, manualReset, initialState, NULL));
}
int DestroyEvent(neosmart_event_t event)
{
HANDLE handle = static_cast<HANDLE>(event);
return CloseHandle(handle) ? 0 : GetLastError();
}
int WaitForEvent(neosmart_event_t event, uint64_t milliseconds)
{
uint32_t result = 0;
HANDLE handle = static_cast<HANDLE>(event);
//WaitForSingleObject(Ex) and WaitForMultipleObjects(Ex) only support 32-bit timeout
if (milliseconds == ((uint64_t) -1) || (milliseconds >> 32) == 0)
{
result = WaitForSingleObject(handle, static_cast<uint32_t>(milliseconds));
}
else
{
//Cannot wait for 0xFFFFFFFF because that means infinity to WIN32
uint32_t waitUnit = (INFINITE - 1);
uint64_t rounds = milliseconds / waitUnit;
uint32_t remainder = milliseconds % waitUnit;
uint32_t result = WaitForSingleObject(handle, remainder);
while (result == WAIT_TIMEOUT && rounds-- != 0)
{
result = WaitForSingleObject(handle, waitUnit);
}
}
if (result == WAIT_OBJECT_0 || result == WAIT_ABANDONED)
{
return 0;
}
return result == WAIT_TIMEOUT ? 0 : GetLastError();
}
int SetEvent(neosmart_event_t event)
{
HANDLE handle = static_cast<HANDLE>(event);
return ::SetEvent(handle) ? 0 : GetLastError();
}
int ResetEvent(neosmart_event_t event)
{
HANDLE handle = static_cast<HANDLE>(event);
return ::ResetEvent(handle) ? 0 : GetLastError();
}
#ifdef WFMO
int WaitForMultipleEvents(neosmart_event_t *events, int count, bool waitAll, uint64_t milliseconds)
{
int index = 0;
return WaitForMultipleEvents(events, count, waitAll, milliseconds, index);
}
int WaitForMultipleEvents(neosmart_event_t *events, int count, bool waitAll, uint64_t milliseconds, int &index)
{
HANDLE *handles = reinterpret_cast<HANDLE*>(events);
uint32_t result = 0;
//WaitForSingleObject(Ex) and WaitForMultipleObjects(Ex) only support 32-bit timeout
if (milliseconds == ((uint64_t) -1) || (milliseconds >> 32) == 0)
{
result = WaitForMultipleObjects(count, handles, waitAll, static_cast<uint32_t>(milliseconds));
}
else
{
//Cannot wait for 0xFFFFFFFF because that means infinity to WIN32
uint32_t waitUnit = (INFINITE - 1);
uint64_t rounds = milliseconds / waitUnit;
uint32_t remainder = milliseconds % waitUnit;
uint32_t result = WaitForMultipleObjects(count, handles, waitAll, remainder);
while (result == WAIT_TIMEOUT && rounds-- != 0)
{
result = WaitForMultipleObjects(count, handles, waitAll, waitUnit);
}
}
if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + count)
{
index = result - WAIT_OBJECT_0;
return 0;
}
else if (result >= WAIT_ABANDONED_0 && result < WAIT_ABANDONED_0 + count)
{
index = result - WAIT_ABANDONED_0;
return 0;
}
if (result == WAIT_FAILED)
{
return GetLastError();
}
return result;
}
#endif
#ifdef PULSE
int PulseEvent(neosmart_event_t event)
{
HANDLE handle = static_cast<HANDLE>(event);
return ::PulseEvent(handle) ? 0 : GetLastError();
}
#endif
}
#endif //_WIN32
<commit_msg>Fixed incorrect return value on timeout on Windows<commit_after>/*
* WIN32 Events for POSIX
* Author: Mahmoud Al-Qudsi <mqudsi@neosmart.net>
* Copyright (C) 2011 - 2015 by NeoSmart Technologies
* This code is released under the terms of the MIT License
*/
#ifdef _WIN32
#include <Windows.h>
#include "pevents.h"
namespace neosmart
{
neosmart_event_t CreateEvent(bool manualReset, bool initialState)
{
return static_cast<neosmart_event_t>(::CreateEvent(NULL, manualReset, initialState, NULL));
}
int DestroyEvent(neosmart_event_t event)
{
HANDLE handle = static_cast<HANDLE>(event);
return CloseHandle(handle) ? 0 : GetLastError();
}
int WaitForEvent(neosmart_event_t event, uint64_t milliseconds)
{
uint32_t result = 0;
HANDLE handle = static_cast<HANDLE>(event);
//WaitForSingleObject(Ex) and WaitForMultipleObjects(Ex) only support 32-bit timeout
if (milliseconds == ((uint64_t) -1) || (milliseconds >> 32) == 0)
{
result = WaitForSingleObject(handle, static_cast<uint32_t>(milliseconds));
}
else
{
//Cannot wait for 0xFFFFFFFF because that means infinity to WIN32
uint32_t waitUnit = (INFINITE - 1);
uint64_t rounds = milliseconds / waitUnit;
uint32_t remainder = milliseconds % waitUnit;
uint32_t result = WaitForSingleObject(handle, remainder);
while (result == WAIT_TIMEOUT && rounds-- != 0)
{
result = WaitForSingleObject(handle, waitUnit);
}
}
if (result == WAIT_OBJECT_0 || result == WAIT_ABANDONED)
{
//We must swallow WAIT_ABANDONED because there is no such equivalent on *nix
return 0;
}
if (result == WAIT_TIMEOUT)
{
return WAIT_TIMEOUT;
}
return GetLastError();
}
int SetEvent(neosmart_event_t event)
{
HANDLE handle = static_cast<HANDLE>(event);
return ::SetEvent(handle) ? 0 : GetLastError();
}
int ResetEvent(neosmart_event_t event)
{
HANDLE handle = static_cast<HANDLE>(event);
return ::ResetEvent(handle) ? 0 : GetLastError();
}
#ifdef WFMO
int WaitForMultipleEvents(neosmart_event_t *events, int count, bool waitAll, uint64_t milliseconds)
{
int index = 0;
return WaitForMultipleEvents(events, count, waitAll, milliseconds, index);
}
int WaitForMultipleEvents(neosmart_event_t *events, int count, bool waitAll, uint64_t milliseconds, int &index)
{
HANDLE *handles = reinterpret_cast<HANDLE*>(events);
uint32_t result = 0;
//WaitForSingleObject(Ex) and WaitForMultipleObjects(Ex) only support 32-bit timeout
if (milliseconds == ((uint64_t) -1) || (milliseconds >> 32) == 0)
{
result = WaitForMultipleObjects(count, handles, waitAll, static_cast<uint32_t>(milliseconds));
}
else
{
//Cannot wait for 0xFFFFFFFF because that means infinity to WIN32
uint32_t waitUnit = (INFINITE - 1);
uint64_t rounds = milliseconds / waitUnit;
uint32_t remainder = milliseconds % waitUnit;
uint32_t result = WaitForMultipleObjects(count, handles, waitAll, remainder);
while (result == WAIT_TIMEOUT && rounds-- != 0)
{
result = WaitForMultipleObjects(count, handles, waitAll, waitUnit);
}
}
if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + count)
{
index = result - WAIT_OBJECT_0;
return 0;
}
else if (result >= WAIT_ABANDONED_0 && result < WAIT_ABANDONED_0 + count)
{
index = result - WAIT_ABANDONED_0;
return 0;
}
if (result == WAIT_FAILED)
{
return GetLastError();
}
return result;
}
#endif
#ifdef PULSE
int PulseEvent(neosmart_event_t event)
{
HANDLE handle = static_cast<HANDLE>(event);
return ::PulseEvent(handle) ? 0 : GetLastError();
}
#endif
}
#endif //_WIN32
<|endoftext|> |
<commit_before>/*
* Task.cc
*
* Created on: Feb 27, 2014
*/
#include "Task.h"
#include <stdlib.h>
#include <ucontext.h>
#include <stdio.h>
namespace BOOOS
{
volatile Task * Task::__running;
Task* Task::__main;
int Task::STACK_SIZE = 32768;
int Task::__tid_counter = 1;
Task::Task(void (*entry_point)(void), int nargs, void * arg) {
this->_state = Task::READY;
this->_stack = new char[Task::STACK_SIZE];
this->_tid = ++Task::__tid_counter;
getcontext(&(this->context));
this->context.uc_link = (ucontext_t*) &(Task::__running->context);
this->context.uc_stack.ss_sp = this->_stack;
this->context.uc_stack.ss_size = Task::STACK_SIZE;
makecontext(&(this->context), (void (*)()) entry_point, nargs, arg);
}
Task::Task(void (*entry_point)(void*), int nargs, void * arg) {
this->_state = Task::READY;
this->_stack = new char[Task::STACK_SIZE];
this->_tid = ++Task::__tid_counter;
getcontext(&(this->context));
this->context.uc_link = (ucontext_t*) &(Task::__running->context);
this->context.uc_stack.ss_sp = this->_stack;
this->context.uc_stack.ss_size = Task::STACK_SIZE;
makecontext(&(this->context), (void (*)()) entry_point, nargs, arg);
}
Task::Task() {
this->_state = Task::READY;
this->_stack = new char[Task::STACK_SIZE];
this->context.uc_stack.ss_sp = this->_stack;
this->context.uc_stack.ss_size = Task::STACK_SIZE;
this->_tid = 0;
}
Task::~Task() {
delete this->_stack;
}
void Task::pass_to(Task *t, State s) {
this->_state = s;
Task::__running = t;
t->_state = Task::RUNNING;
swapcontext(&(this->context), &(t->context));
}
void Task::init() {
Task::__tid_counter = 1;
Task::__main = new Task();
Task::__running = Task::__main;
Task::__running->_state = Task::RUNNING;
}
void Task::exit(int code) {
this->pass_to(Task::__main, Task::FINISHING);
}
} /* namespace BOOOS */
<commit_msg>Little fix to Task.cc<commit_after>/* Fernando Jorge Mota (13200641) e Caique Rodrigues Marques (13204303)
* Task.cc
*
* Created on: Feb 27, 2014
*/
#include "Task.h"
#include <stdlib.h>
#include <ucontext.h>
#include <stdio.h>
namespace BOOOS
{
volatile Task * Task::__running;
Task* Task::__main;
int Task::STACK_SIZE = 32768;
int Task::__tid_counter = 1;
Task::Task(void (*entry_point)(void), int nargs, void * arg) {
this->_state = Task::READY;
this->_stack = new char[Task::STACK_SIZE];
this->_tid = ++Task::__tid_counter;
getcontext(&(this->context));
this->context.uc_link = (ucontext_t*) &(Task::__running->context);
this->context.uc_stack.ss_sp = this->_stack;
this->context.uc_stack.ss_size = Task::STACK_SIZE;
makecontext(&(this->context), (void (*)(void)) entry_point, nargs, arg);
}
Task::Task(void (*entry_point)(void*), int nargs, void * arg) {
this->_state = Task::READY;
this->_stack = new char[Task::STACK_SIZE];
this->_tid = ++Task::__tid_counter;
getcontext(&(this->context));
this->context.uc_link = (ucontext_t*) &(Task::__running->context);
this->context.uc_stack.ss_sp = this->_stack;
this->context.uc_stack.ss_size = Task::STACK_SIZE;
makecontext(&(this->context), (void (*)(void)) entry_point, nargs, arg);
}
Task::Task() {
this->_state = Task::READY;
this->_stack = new char[Task::STACK_SIZE];
this->context.uc_stack.ss_sp = this->_stack;
this->context.uc_stack.ss_size = Task::STACK_SIZE;
this->_tid = 0;
}
Task::~Task() {
delete this->_stack;
}
void Task::pass_to(Task *t, State s) {
this->_state = s;
Task::__running = t;
t->_state = Task::RUNNING;
swapcontext(&(this->context), &(t->context));
}
void Task::init() {
Task::__tid_counter = 1;
Task::__main = new Task();
Task::__running = Task::__main;
Task::__running->_state = Task::RUNNING;
}
void Task::exit(int code) {
this->pass_to(Task::__main, Task::FINISHING);
}
} /* namespace BOOOS */
<|endoftext|> |
<commit_before>#include <iostream>
#include <memory>
#include <thread>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Main
#include <boost/test/unit_test.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include "tcp_server.h"
#include "logger.h"
using namespace Akumuli;
static Logger logger_ = Logger("tcp-server-test");
typedef std::tuple<aku_ParamId, aku_Timestamp, double> ValueT;
struct SessionMock : DbSession {
std::vector<ValueT>& results;
SessionMock(std::vector<ValueT>& results)
: results(results) {}
virtual aku_Status write(const aku_Sample &sample) override {
logger_.trace() << "write_double(" << sample.paramid << ", " << sample.timestamp << ", " << sample.payload.float64 << ")";
results.push_back(std::make_tuple(sample.paramid, sample.timestamp, sample.payload.float64));
return AKU_SUCCESS;
}
virtual std::shared_ptr<DbCursor> query(std::string) override {
throw "not implemented";
}
virtual std::shared_ptr<DbCursor> suggest(std::string) override {
throw "not implemented";
}
virtual std::shared_ptr<DbCursor> search(std::string) override {
throw "not implemented";
}
virtual int param_id_to_series(aku_ParamId id, char* buf, size_t sz) override {
auto str = std::to_string(id);
assert(str.size() <= sz);
memcpy(buf, str.data(), str.size());
return static_cast<int>(str.size());
}
virtual aku_Status series_to_param_id(const char* begin, size_t sz, aku_Sample* sample) override {
std::string num(begin, begin + sz);
sample->paramid = boost::lexical_cast<u64>(num);
return AKU_SUCCESS;
}
virtual int name_to_param_id_list(const char* begin, const char* end, aku_ParamId* ids, u32 cap) override {
auto nelem = std::count(begin, end, ':') + 1;
if (nelem > cap) {
return -1*static_cast<int>(nelem);
}
const char* it_begin = begin;
const char* it_end = begin;
for (int i = 0; i < nelem; i++) {
//move it_end
while(*it_end != ':' && it_end != end) {
it_end++;
}
std::string val(it_begin, it_end);
ids[i] = boost::lexical_cast<u64>(val);
}
return static_cast<int>(nelem);
}
};
struct ConnectionMock : DbConnection {
std::vector<ValueT> results;
virtual std::string get_all_stats() override { throw "not impelemnted"; }
virtual std::shared_ptr<DbSession> create_session() override {
return std::make_shared<SessionMock>(results);
}
};
template<aku_Status ERR>
struct DbSessionErrorMock : DbSession {
aku_Status err = ERR;
virtual aku_Status write(const aku_Sample&) override {
return err;
}
virtual std::shared_ptr<DbCursor> query(std::string) override {
throw "not implemented";
}
virtual std::shared_ptr<DbCursor> suggest(std::string) override {
throw "not implemented";
}
virtual std::shared_ptr<DbCursor> search(std::string) override {
throw "not implemented";
}
virtual int param_id_to_series(aku_ParamId id, char* buf, size_t sz) override {
auto str = std::to_string(id);
assert(str.size() <= sz);
memcpy(buf, str.data(), str.size());
return static_cast<int>(str.size());
}
virtual aku_Status series_to_param_id(const char* begin, size_t sz, aku_Sample* sample) override {
std::string num(begin, begin + sz);
sample->paramid = boost::lexical_cast<u64>(num);
return AKU_SUCCESS;
}
virtual int name_to_param_id_list(const char* begin, const char* end, aku_ParamId* ids, u32 cap) override {
auto nelem = std::count(begin, end, '|') + 1;
if (nelem > cap) {
return -1*static_cast<int>(nelem);
}
const char* it_begin = begin;
const char* it_end = begin;
for (int i = 0; i < nelem; i++) {
//move it_end
while(*it_end != '|' && it_end != end) {
it_end++;
}
std::string val(it_begin, it_end);
ids[i] = boost::lexical_cast<u64>(val);
}
return static_cast<int>(nelem);
}
};
template<aku_Status ERR>
struct DbConnectionErrorMock : DbConnection {
virtual std::string get_all_stats() override { throw "not impelemented"; }
virtual std::shared_ptr<DbSession> create_session() override {
return std::make_shared<DbSessionErrorMock<ERR>>();
}
};
const int PORT = 14096;
template<class Mock>
struct TCPServerTestSuite {
std::shared_ptr<Mock> dbcon;
IOServiceT io;
std::shared_ptr<TcpAcceptor> serv;
TCPServerTestSuite() {
// Create mock pipeline
dbcon = std::make_shared<Mock>();
// Run server
std::vector<IOServiceT*> iovec = { &io };
serv = std::make_shared<TcpAcceptor>(iovec, PORT, dbcon);
// Start reading but don't start iorun thread
serv->_start();
}
~TCPServerTestSuite() {
logger_.info() << "Clean up suite resources";
if (serv) {
serv->_stop();
}
}
template<class Fn>
void run(Fn const& fn) {
// Connect to server
SocketT socket(io);
auto loopback = boost::asio::ip::address_v4::loopback();
boost::asio::ip::tcp::endpoint peer(loopback, PORT);
socket.connect(peer);
serv->_run_one(); // run handle_accept one time
// Run tests
fn(socket);
}
};
BOOST_AUTO_TEST_CASE(Test_tcp_server_loopback_1) {
TCPServerTestSuite<ConnectionMock> suite;
suite.run([&](SocketT& socket) {
boost::asio::streambuf stream;
std::ostream os(&stream);
os << "+1\r\n" << ":2\r\n" << "+3.14\r\n";
boost::asio::write(socket, stream);
// TCPSession.handle_read
suite.io.run_one();
// Check
if (suite.dbcon->results.size() != 1) {
logger_.error() << "Error detected";
BOOST_REQUIRE_EQUAL(suite.dbcon->results.size(), 1);
}
aku_ParamId id;
aku_Timestamp ts;
double value;
std::tie(id, ts, value) = suite.dbcon->results.at(0);
BOOST_REQUIRE_EQUAL(id, 1);
BOOST_REQUIRE_EQUAL(ts, 2);
BOOST_REQUIRE_CLOSE_FRACTION(value, 3.14, 0.00001);
});
}
BOOST_AUTO_TEST_CASE(Test_tcp_server_loopback_2) {
TCPServerTestSuite<ConnectionMock> suite;
suite.run([&](SocketT& socket) {
boost::asio::streambuf stream;
std::ostream os(&stream);
os << "+1\r\n" << ":2\r\n";
size_t n = boost::asio::write(socket, stream);
stream.consume(n);
// Process first part of the message
suite.io.run_one();
os << "+3.14\r\n";
n = boost::asio::write(socket, stream);
// Process last
suite.io.run_one();
// Check
BOOST_REQUIRE_EQUAL(suite.dbcon->results.size(), 1);
aku_ParamId id;
aku_Timestamp ts;
double value;
std::tie(id, ts, value) = suite.dbcon->results.at(0);
BOOST_REQUIRE_EQUAL(id, 1);
BOOST_REQUIRE_EQUAL(ts, 2);
BOOST_REQUIRE_CLOSE_FRACTION(value, 3.14, 0.00001);
});
}
BOOST_AUTO_TEST_CASE(Test_tcp_server_loopback_3) {
TCPServerTestSuite<ConnectionMock> suite;
suite.run([&](SocketT& socket) {
boost::asio::streambuf stream;
std::ostream os(&stream);
// Fist message
os << "+1\r\n" << ":2\r\n" << "+3.14\r\n";
size_t n = boost::asio::write(socket, stream);
stream.consume(n);
// Process first part of the message
suite.io.run_one();
// Second message
os << "+3\r\n" << ":4\r\n" << "+1.61\r\n";
n = boost::asio::write(socket, stream);
// Process last
suite.io.run_one();
// Check
BOOST_REQUIRE_EQUAL(suite.dbcon->results.size(), 2);
aku_ParamId id;
aku_Timestamp ts;
double value;
// First message
std::tie(id, ts, value) = suite.dbcon->results.at(0);
BOOST_REQUIRE_EQUAL(id, 1);
BOOST_REQUIRE_EQUAL(ts, 2);
BOOST_REQUIRE_CLOSE_FRACTION(value, 3.14, 0.00001);
// Second message
std::tie(id, ts, value) = suite.dbcon->results.at(1);
BOOST_REQUIRE_EQUAL(id, 3);
BOOST_REQUIRE_EQUAL(ts, 4);
BOOST_REQUIRE_CLOSE_FRACTION(value, 1.61, 0.00001);
});
}
BOOST_AUTO_TEST_CASE(Test_tcp_server_parser_error_handling) {
TCPServerTestSuite<ConnectionMock> suite;
suite.run([&](SocketT& socket) {
boost::asio::streambuf stream;
std::ostream os(&stream);
os << "+1\r\n:E\r\n+3.14\r\n";
// error ^
boost::asio::streambuf instream;
std::istream is(&instream);
boost::asio::write(socket, stream);
bool handler_called = false;
auto cb = [&](boost::system::error_code err) {
BOOST_REQUIRE(err == boost::asio::error::eof);
handler_called = true;
};
boost::asio::async_read(socket, instream, boost::bind<void>(cb, boost::asio::placeholders::error));
// TCPSession.handle_read
suite.io.run_one(); // run message handler (should send error back to us)
while(!handler_called) {
suite.io.run_one(); // run error handler
}
BOOST_REQUIRE(handler_called);
// Check
BOOST_REQUIRE_EQUAL(suite.dbcon->results.size(), 0);
char buffer[0x1000];
is.getline(buffer, 0x1000);
BOOST_REQUIRE_EQUAL(std::string(buffer, buffer + 7), "-PARSER");
});
}
BOOST_AUTO_TEST_CASE(Test_tcp_server_backend_error_handling) {
TCPServerTestSuite<DbConnectionErrorMock<AKU_EBAD_DATA>> suite;
suite.run([&](SocketT& socket) {
boost::asio::streambuf stream;
std::ostream os(&stream);
os << "+1\r\n:2\r\n+3.14\r\n";
boost::asio::streambuf instream;
std::istream is(&instream);
boost::asio::write(socket, stream);
bool handler_called = false;
auto cb = [&](boost::system::error_code err) {
BOOST_REQUIRE(err == boost::asio::error::eof);
handler_called = true;
};
boost::asio::async_read(socket, instream, boost::bind<void>(cb, boost::asio::placeholders::error));
// TCPSession.handle_read
suite.io.run_one(); // run message handler (should send error back to us)
while(!handler_called) {
suite.io.run_one(); // run error handler
}
BOOST_REQUIRE(handler_called);
// Check
char buffer[0x1000];
is.getline(buffer, 0x1000);
BOOST_REQUIRE_EQUAL(std::string(buffer, buffer + 3), "-DB");
});
}
<commit_msg>Fix: Corrected types<commit_after>#include <iostream>
#include <memory>
#include <thread>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Main
#include <boost/test/unit_test.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include "tcp_server.h"
#include "logger.h"
using namespace Akumuli;
static Logger logger_ = Logger("tcp-server-test");
typedef std::tuple<aku_ParamId, aku_Timestamp, double> ValueT;
struct SessionMock : DbSession {
std::vector<ValueT>& results;
SessionMock(std::vector<ValueT>& results)
: results(results) {}
virtual aku_Status write(const aku_Sample &sample) override {
logger_.trace() << "write_double(" << sample.paramid << ", " << sample.timestamp << ", " << sample.payload.float64 << ")";
results.push_back(std::make_tuple(sample.paramid, sample.timestamp, sample.payload.float64));
return AKU_SUCCESS;
}
virtual std::shared_ptr<DbCursor> query(std::string) override {
throw "not implemented";
}
virtual std::shared_ptr<DbCursor> suggest(std::string) override {
throw "not implemented";
}
virtual std::shared_ptr<DbCursor> search(std::string) override {
throw "not implemented";
}
virtual int param_id_to_series(aku_ParamId id, char* buf, size_t sz) override {
auto str = std::to_string(id);
assert(str.size() <= sz);
memcpy(buf, str.data(), str.size());
return static_cast<int>(str.size());
}
virtual aku_Status series_to_param_id(const char* begin, size_t sz, aku_Sample* sample) override {
std::string num(begin, begin + sz);
sample->paramid = boost::lexical_cast<u64>(num);
return AKU_SUCCESS;
}
virtual int name_to_param_id_list(const char* begin, const char* end, aku_ParamId* ids, u32 cap) override {
u32 nelem = std::count(begin, end, ':') + 1;
if (nelem > cap) {
return -1*static_cast<int>(nelem);
}
const char* it_begin = begin;
const char* it_end = begin;
for (u32 i = 0; i < nelem; i++) {
//move it_end
while(*it_end != ':' && it_end != end) {
it_end++;
}
std::string val(it_begin, it_end);
ids[i] = boost::lexical_cast<u64>(val);
}
return static_cast<int>(nelem);
}
};
struct ConnectionMock : DbConnection {
std::vector<ValueT> results;
virtual std::string get_all_stats() override { throw "not impelemnted"; }
virtual std::shared_ptr<DbSession> create_session() override {
return std::make_shared<SessionMock>(results);
}
};
template<aku_Status ERR>
struct DbSessionErrorMock : DbSession {
aku_Status err = ERR;
virtual aku_Status write(const aku_Sample&) override {
return err;
}
virtual std::shared_ptr<DbCursor> query(std::string) override {
throw "not implemented";
}
virtual std::shared_ptr<DbCursor> suggest(std::string) override {
throw "not implemented";
}
virtual std::shared_ptr<DbCursor> search(std::string) override {
throw "not implemented";
}
virtual int param_id_to_series(aku_ParamId id, char* buf, size_t sz) override {
auto str = std::to_string(id);
assert(str.size() <= sz);
memcpy(buf, str.data(), str.size());
return static_cast<int>(str.size());
}
virtual aku_Status series_to_param_id(const char* begin, size_t sz, aku_Sample* sample) override {
std::string num(begin, begin + sz);
sample->paramid = boost::lexical_cast<u64>(num);
return AKU_SUCCESS;
}
virtual int name_to_param_id_list(const char* begin, const char* end, aku_ParamId* ids, u32 cap) override {
u32 nelem = std::count(begin, end, '|') + 1;
if (nelem > cap) {
return -1*static_cast<int>(nelem);
}
const char* it_begin = begin;
const char* it_end = begin;
for (u32 i = 0; i < nelem; i++) {
//move it_end
while(*it_end != '|' && it_end != end) {
it_end++;
}
std::string val(it_begin, it_end);
ids[i] = boost::lexical_cast<u64>(val);
}
return static_cast<int>(nelem);
}
};
template<aku_Status ERR>
struct DbConnectionErrorMock : DbConnection {
virtual std::string get_all_stats() override { throw "not impelemented"; }
virtual std::shared_ptr<DbSession> create_session() override {
return std::make_shared<DbSessionErrorMock<ERR>>();
}
};
const int PORT = 14096;
template<class Mock>
struct TCPServerTestSuite {
std::shared_ptr<Mock> dbcon;
IOServiceT io;
std::shared_ptr<TcpAcceptor> serv;
TCPServerTestSuite() {
// Create mock pipeline
dbcon = std::make_shared<Mock>();
// Run server
std::vector<IOServiceT*> iovec = { &io };
serv = std::make_shared<TcpAcceptor>(iovec, PORT, dbcon);
// Start reading but don't start iorun thread
serv->_start();
}
~TCPServerTestSuite() {
logger_.info() << "Clean up suite resources";
if (serv) {
serv->_stop();
}
}
template<class Fn>
void run(Fn const& fn) {
// Connect to server
SocketT socket(io);
auto loopback = boost::asio::ip::address_v4::loopback();
boost::asio::ip::tcp::endpoint peer(loopback, PORT);
socket.connect(peer);
serv->_run_one(); // run handle_accept one time
// Run tests
fn(socket);
}
};
BOOST_AUTO_TEST_CASE(Test_tcp_server_loopback_1) {
TCPServerTestSuite<ConnectionMock> suite;
suite.run([&](SocketT& socket) {
boost::asio::streambuf stream;
std::ostream os(&stream);
os << "+1\r\n" << ":2\r\n" << "+3.14\r\n";
boost::asio::write(socket, stream);
// TCPSession.handle_read
suite.io.run_one();
// Check
if (suite.dbcon->results.size() != 1) {
logger_.error() << "Error detected";
BOOST_REQUIRE_EQUAL(suite.dbcon->results.size(), 1);
}
aku_ParamId id;
aku_Timestamp ts;
double value;
std::tie(id, ts, value) = suite.dbcon->results.at(0);
BOOST_REQUIRE_EQUAL(id, 1);
BOOST_REQUIRE_EQUAL(ts, 2);
BOOST_REQUIRE_CLOSE_FRACTION(value, 3.14, 0.00001);
});
}
BOOST_AUTO_TEST_CASE(Test_tcp_server_loopback_2) {
TCPServerTestSuite<ConnectionMock> suite;
suite.run([&](SocketT& socket) {
boost::asio::streambuf stream;
std::ostream os(&stream);
os << "+1\r\n" << ":2\r\n";
size_t n = boost::asio::write(socket, stream);
stream.consume(n);
// Process first part of the message
suite.io.run_one();
os << "+3.14\r\n";
n = boost::asio::write(socket, stream);
// Process last
suite.io.run_one();
// Check
BOOST_REQUIRE_EQUAL(suite.dbcon->results.size(), 1);
aku_ParamId id;
aku_Timestamp ts;
double value;
std::tie(id, ts, value) = suite.dbcon->results.at(0);
BOOST_REQUIRE_EQUAL(id, 1);
BOOST_REQUIRE_EQUAL(ts, 2);
BOOST_REQUIRE_CLOSE_FRACTION(value, 3.14, 0.00001);
});
}
BOOST_AUTO_TEST_CASE(Test_tcp_server_loopback_3) {
TCPServerTestSuite<ConnectionMock> suite;
suite.run([&](SocketT& socket) {
boost::asio::streambuf stream;
std::ostream os(&stream);
// Fist message
os << "+1\r\n" << ":2\r\n" << "+3.14\r\n";
size_t n = boost::asio::write(socket, stream);
stream.consume(n);
// Process first part of the message
suite.io.run_one();
// Second message
os << "+3\r\n" << ":4\r\n" << "+1.61\r\n";
n = boost::asio::write(socket, stream);
// Process last
suite.io.run_one();
// Check
BOOST_REQUIRE_EQUAL(suite.dbcon->results.size(), 2);
aku_ParamId id;
aku_Timestamp ts;
double value;
// First message
std::tie(id, ts, value) = suite.dbcon->results.at(0);
BOOST_REQUIRE_EQUAL(id, 1);
BOOST_REQUIRE_EQUAL(ts, 2);
BOOST_REQUIRE_CLOSE_FRACTION(value, 3.14, 0.00001);
// Second message
std::tie(id, ts, value) = suite.dbcon->results.at(1);
BOOST_REQUIRE_EQUAL(id, 3);
BOOST_REQUIRE_EQUAL(ts, 4);
BOOST_REQUIRE_CLOSE_FRACTION(value, 1.61, 0.00001);
});
}
BOOST_AUTO_TEST_CASE(Test_tcp_server_parser_error_handling) {
TCPServerTestSuite<ConnectionMock> suite;
suite.run([&](SocketT& socket) {
boost::asio::streambuf stream;
std::ostream os(&stream);
os << "+1\r\n:E\r\n+3.14\r\n";
// error ^
boost::asio::streambuf instream;
std::istream is(&instream);
boost::asio::write(socket, stream);
bool handler_called = false;
auto cb = [&](boost::system::error_code err) {
BOOST_REQUIRE(err == boost::asio::error::eof);
handler_called = true;
};
boost::asio::async_read(socket, instream, boost::bind<void>(cb, boost::asio::placeholders::error));
// TCPSession.handle_read
suite.io.run_one(); // run message handler (should send error back to us)
while(!handler_called) {
suite.io.run_one(); // run error handler
}
BOOST_REQUIRE(handler_called);
// Check
BOOST_REQUIRE_EQUAL(suite.dbcon->results.size(), 0);
char buffer[0x1000];
is.getline(buffer, 0x1000);
BOOST_REQUIRE_EQUAL(std::string(buffer, buffer + 7), "-PARSER");
});
}
BOOST_AUTO_TEST_CASE(Test_tcp_server_backend_error_handling) {
TCPServerTestSuite<DbConnectionErrorMock<AKU_EBAD_DATA>> suite;
suite.run([&](SocketT& socket) {
boost::asio::streambuf stream;
std::ostream os(&stream);
os << "+1\r\n:2\r\n+3.14\r\n";
boost::asio::streambuf instream;
std::istream is(&instream);
boost::asio::write(socket, stream);
bool handler_called = false;
auto cb = [&](boost::system::error_code err) {
BOOST_REQUIRE(err == boost::asio::error::eof);
handler_called = true;
};
boost::asio::async_read(socket, instream, boost::bind<void>(cb, boost::asio::placeholders::error));
// TCPSession.handle_read
suite.io.run_one(); // run message handler (should send error back to us)
while(!handler_called) {
suite.io.run_one(); // run error handler
}
BOOST_REQUIRE(handler_called);
// Check
char buffer[0x1000];
is.getline(buffer, 0x1000);
BOOST_REQUIRE_EQUAL(std::string(buffer, buffer + 3), "-DB");
});
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkChooserPainter.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 "vtkChooserPainter.h"
#include "vtkCommand.h"
#include "vtkGarbageCollector.h"
#include "vtkInformation.h"
#include "vtkInstantiator.h"
#include "vtkObjectFactory.h"
#include "vtkPolyData.h"
#include "vtkRenderer.h"
#include "vtkStandardPolyDataPainter.h"
vtkCxxRevisionMacro(vtkChooserPainter, "1.2");
vtkStandardNewMacro(vtkChooserPainter);
vtkCxxSetObjectMacro(vtkChooserPainter, VertPainter, vtkPolyDataPainter);
vtkCxxSetObjectMacro(vtkChooserPainter, LinePainter, vtkPolyDataPainter);
vtkCxxSetObjectMacro(vtkChooserPainter, PolyPainter, vtkPolyDataPainter);
vtkCxxSetObjectMacro(vtkChooserPainter, StripPainter, vtkPolyDataPainter);
//-----------------------------------------------------------------------------
vtkChooserPainter::vtkChooserPainter()
{
this->VertPainter = NULL;
this->LinePainter = NULL;
this->PolyPainter = NULL;
this->StripPainter = NULL;
this->LastRenderer = NULL;
}
//-----------------------------------------------------------------------------
vtkChooserPainter::~vtkChooserPainter()
{
if (this->VertPainter) this->VertPainter->Delete();
if (this->LinePainter) this->LinePainter->Delete();
if (this->PolyPainter) this->PolyPainter->Delete();
if (this->StripPainter) this->StripPainter->Delete();
}
/*
//-----------------------------------------------------------------------------
void vtkChooserPainter::ReleaseGraphicsResources(vtkWindow* w)
{
if (this->VertPainter)
{
this->VertPainter->ReleaseGraphicsResources(w);
}
if (this->LinePainter)
{
this->LinePainter->ReleaseGraphicsResources(w);
}
if (this->PolyPainter)
{
this->PolyPainter->ReleaseGraphicsResources(w);
}
if (this->StripPainter)
{
this->StripPainter->ReleaseGraphicsResources(w);
}
this->Superclass::ReleaseGraphicsResources(w);
}
*/
//-----------------------------------------------------------------------------
void vtkChooserPainter::ReportReferences(vtkGarbageCollector *collector)
{
this->Superclass::ReportReferences(collector);
vtkGarbageCollectorReport(collector, this->VertPainter, "Vert Painter");
vtkGarbageCollectorReport(collector, this->LinePainter, "Line Painter");
vtkGarbageCollectorReport(collector, this->PolyPainter, "Poly Painter");
vtkGarbageCollectorReport(collector, this->StripPainter, "Strip Painter");
}
//-----------------------------------------------------------------------------
void vtkChooserPainter::PrepareForRendering(vtkRenderer* ren, vtkActor* actor)
{
// Ensure that the renderer chain is up-to-date.
if (this->PaintersChoiceTime < this->MTime ||
this->PaintersChoiceTime < this->Information->GetMTime() ||
this->LastRenderer != ren ||
this->PaintersChoiceTime < this->PolyData->GetMTime())
{
this->LastRenderer = ren;
// Choose the painters.
this->ChoosePainters(ren);
// Pass them the information and poly data we have.
this->UpdateChoosenPainters();
this->PaintersChoiceTime.Modified();
}
this->Superclass::PrepareForRendering(ren, actor);
}
//-----------------------------------------------------------------------------
void vtkChooserPainter::UpdateChoosenPainters()
{
if (this->VertPainter)
{
this->PassInformation(this->VertPainter);
}
if (this->LinePainter)
{
this->PassInformation(this->LinePainter);
}
if (this->PolyPainter)
{
this->PassInformation(this->PolyPainter);
}
if (this->StripPainter)
{
this->PassInformation(this->StripPainter);
}
}
//-----------------------------------------------------------------------------
void vtkChooserPainter::ChoosePainters(vtkRenderer *renderer)
{
const char *vertpaintertype;
const char *linepaintertype;
const char *polypaintertype;
const char *strippaintertype;
vtkPolyDataPainter* painter;
this->SelectPainters(renderer, vertpaintertype, linepaintertype,
polypaintertype, strippaintertype);
vtkDebugMacro(<< "Selected " << vertpaintertype << ", "
<< linepaintertype << ", " << polypaintertype << ", "
<< strippaintertype);
if (!this->VertPainter || !this->VertPainter->IsA(vertpaintertype))
{
painter = this->CreatePainter(vertpaintertype);
this->SetVertPainter(painter);
painter->Delete();
vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New();
painter->SetDelegatePainter(sp);
sp->Delete();
}
if (!this->LinePainter || !this->LinePainter->IsA(linepaintertype))
{
if (strcmp(vertpaintertype, linepaintertype) == 0)
{
this->SetLinePainter(this->VertPainter);
}
else
{
painter = this->CreatePainter(linepaintertype);
this->SetLinePainter(painter);
painter->Delete();
vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New();
painter->SetDelegatePainter(sp);
sp->Delete();
}
}
if (!this->PolyPainter || !this->PolyPainter->IsA(polypaintertype))
{
if (strcmp(vertpaintertype, polypaintertype) == 0)
{
this->SetPolyPainter(this->VertPainter);
}
else if (strcmp(linepaintertype, polypaintertype) == 0)
{
this->SetPolyPainter(this->LinePainter);
}
else
{
painter = this->CreatePainter(polypaintertype);
this->SetPolyPainter(painter);
painter->Delete();
vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New();
painter->SetDelegatePainter(sp);
sp->Delete();
}
}
if (!this->StripPainter || !this->StripPainter->IsA(strippaintertype))
{
if (strcmp(vertpaintertype, strippaintertype) == 0)
{
this->SetStripPainter(this->VertPainter);
}
else if (strcmp(linepaintertype, strippaintertype) == 0)
{
this->SetStripPainter(this->LinePainter);
}
else if (strcmp(polypaintertype, strippaintertype) == 0)
{
this->SetStripPainter(this->PolyPainter);
}
else
{
painter = this->CreatePainter(strippaintertype);
this->SetStripPainter(painter);
painter->Delete();
vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New();
painter->SetDelegatePainter(sp);
sp->Delete();
}
}
}
//-----------------------------------------------------------------------------
void vtkChooserPainter::SelectPainters(vtkRenderer *vtkNotUsed(renderer),
const char *&vertptype,
const char *&lineptype,
const char *&polyptype,
const char *&stripptype)
{
vertptype = "vtkPointsPainter";
lineptype = "vtkLinesPainter";
polyptype = "vtkPolygonsPainter";
stripptype = "vtkTStripsPainter";
// No elaborate selection as yet.
// Merely create the pipeline as the vtkOpenGLPolyDataMapper.
}
//-----------------------------------------------------------------------------
vtkPolyDataPainter* vtkChooserPainter::CreatePainter(const char *paintertype)
{
vtkObject* o = vtkInstantiator::CreateInstance(paintertype);
vtkPolyDataPainter* p = vtkPolyDataPainter::SafeDownCast(o);
if (!p && o)
{
o->Delete();
}
this->ObserverPainterProgress(p);
return p;
}
//-----------------------------------------------------------------------------
void vtkChooserPainter::RenderInternal(vtkRenderer* renderer, vtkActor* actor,
unsigned long typeflags)
{
vtkIdType numVerts = this->PolyData->GetNumberOfVerts();
vtkIdType numLines = this->PolyData->GetNumberOfLines();
vtkIdType numPolys = this->PolyData->GetNumberOfPolys();
vtkIdType numStrips = this->PolyData->GetNumberOfStrips();
vtkIdType total_cells = (typeflags & vtkPainter::VERTS)?
this->PolyData->GetNumberOfVerts() : 0;
total_cells += (typeflags & vtkPainter::LINES)?
this->PolyData->GetNumberOfLines() : 0;
total_cells += (typeflags & vtkPainter::POLYS)?
this->PolyData->GetNumberOfPolys() : 0;
total_cells += (typeflags & vtkPainter::STRIPS)?
this->PolyData->GetNumberOfStrips() : 0;
if (total_cells == 0)
{
// nothing to render.
return;
}
this->ProgressOffset = 0.0;
this->TimeToDraw = 0.0;
if (typeflags & vtkPainter::VERTS)
{
//cout << this << "Verts" << endl;
this->ProgressScaleFactor = static_cast<double>(numVerts)/total_cells;
this->VertPainter->Render(renderer, actor, vtkPainter::VERTS);
this->TimeToDraw += this->VertPainter->GetTimeToDraw();
this->ProgressOffset += this->ProgressScaleFactor;
}
if (typeflags & vtkPainter::LINES)
{
//cout << this << "Lines" << endl;
this->ProgressScaleFactor = static_cast<double>(numLines)/total_cells;
this->LinePainter->Render(renderer, actor, vtkPainter::LINES);
this->TimeToDraw += this->LinePainter->GetTimeToDraw();
this->ProgressOffset += this->ProgressScaleFactor;
}
if (typeflags & vtkPainter::POLYS)
{
//cout << this << "Polys" << endl;
this->ProgressScaleFactor = static_cast<double>(numPolys)/total_cells;
this->PolyPainter->Render(renderer, actor, vtkPainter::POLYS);
this->TimeToDraw += this->PolyPainter->GetTimeToDraw();
this->ProgressOffset += this->ProgressScaleFactor;
}
if (typeflags & vtkPainter::STRIPS)
{
//cout << this << "Strips" << endl;
this->ProgressScaleFactor = static_cast<double>(numStrips)/total_cells;
this->StripPainter->Render(renderer, actor, vtkPainter::STRIPS);
this->TimeToDraw += this->StripPainter->GetTimeToDraw();
}
this->Superclass::RenderInternal(renderer, actor, typeflags);
}
//-----------------------------------------------------------------------------
void vtkChooserPainter::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "VertPainter: " << this->VertPainter << endl;
os << indent << "LinePainter: " << this->LinePainter << endl;
os << indent << "PolyPainter: " << this->PolyPainter << endl;
os << indent << "StripPainter: " << this->StripPainter << endl;
}
<commit_msg>BUG: vtkInstantiator fails in static builds. Overcame the use of vtkInstantiator. Should fix dashboard seg faults<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkChooserPainter.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 "vtkChooserPainter.h"
#include "vtkCommand.h"
#include "vtkGarbageCollector.h"
#include "vtkInformation.h"
#include "vtkLinesPainter.h"
#include "vtkObjectFactory.h"
#include "vtkPointsPainter.h"
#include "vtkPolyData.h"
#include "vtkPolygonsPainter.h"
#include "vtkRenderer.h"
#include "vtkStandardPolyDataPainter.h"
#include "vtkTStripsPainter.h"
vtkCxxRevisionMacro(vtkChooserPainter, "1.3");
vtkStandardNewMacro(vtkChooserPainter);
vtkCxxSetObjectMacro(vtkChooserPainter, VertPainter, vtkPolyDataPainter);
vtkCxxSetObjectMacro(vtkChooserPainter, LinePainter, vtkPolyDataPainter);
vtkCxxSetObjectMacro(vtkChooserPainter, PolyPainter, vtkPolyDataPainter);
vtkCxxSetObjectMacro(vtkChooserPainter, StripPainter, vtkPolyDataPainter);
//-----------------------------------------------------------------------------
vtkChooserPainter::vtkChooserPainter()
{
this->VertPainter = NULL;
this->LinePainter = NULL;
this->PolyPainter = NULL;
this->StripPainter = NULL;
this->LastRenderer = NULL;
}
//-----------------------------------------------------------------------------
vtkChooserPainter::~vtkChooserPainter()
{
if (this->VertPainter) this->VertPainter->Delete();
if (this->LinePainter) this->LinePainter->Delete();
if (this->PolyPainter) this->PolyPainter->Delete();
if (this->StripPainter) this->StripPainter->Delete();
}
/*
//-----------------------------------------------------------------------------
void vtkChooserPainter::ReleaseGraphicsResources(vtkWindow* w)
{
if (this->VertPainter)
{
this->VertPainter->ReleaseGraphicsResources(w);
}
if (this->LinePainter)
{
this->LinePainter->ReleaseGraphicsResources(w);
}
if (this->PolyPainter)
{
this->PolyPainter->ReleaseGraphicsResources(w);
}
if (this->StripPainter)
{
this->StripPainter->ReleaseGraphicsResources(w);
}
this->Superclass::ReleaseGraphicsResources(w);
}
*/
//-----------------------------------------------------------------------------
void vtkChooserPainter::ReportReferences(vtkGarbageCollector *collector)
{
this->Superclass::ReportReferences(collector);
vtkGarbageCollectorReport(collector, this->VertPainter, "Vert Painter");
vtkGarbageCollectorReport(collector, this->LinePainter, "Line Painter");
vtkGarbageCollectorReport(collector, this->PolyPainter, "Poly Painter");
vtkGarbageCollectorReport(collector, this->StripPainter, "Strip Painter");
}
//-----------------------------------------------------------------------------
void vtkChooserPainter::PrepareForRendering(vtkRenderer* ren, vtkActor* actor)
{
// Ensure that the renderer chain is up-to-date.
if (this->PaintersChoiceTime < this->MTime ||
this->PaintersChoiceTime < this->Information->GetMTime() ||
this->LastRenderer != ren ||
this->PaintersChoiceTime < this->PolyData->GetMTime())
{
this->LastRenderer = ren;
// Choose the painters.
this->ChoosePainters(ren);
// Pass them the information and poly data we have.
this->UpdateChoosenPainters();
this->PaintersChoiceTime.Modified();
}
this->Superclass::PrepareForRendering(ren, actor);
}
//-----------------------------------------------------------------------------
void vtkChooserPainter::UpdateChoosenPainters()
{
if (this->VertPainter)
{
this->PassInformation(this->VertPainter);
}
if (this->LinePainter)
{
this->PassInformation(this->LinePainter);
}
if (this->PolyPainter)
{
this->PassInformation(this->PolyPainter);
}
if (this->StripPainter)
{
this->PassInformation(this->StripPainter);
}
}
//-----------------------------------------------------------------------------
void vtkChooserPainter::ChoosePainters(vtkRenderer *renderer)
{
const char *vertpaintertype;
const char *linepaintertype;
const char *polypaintertype;
const char *strippaintertype;
vtkPolyDataPainter* painter;
this->SelectPainters(renderer, vertpaintertype, linepaintertype,
polypaintertype, strippaintertype);
vtkDebugMacro(<< "Selected " << vertpaintertype << ", "
<< linepaintertype << ", " << polypaintertype << ", "
<< strippaintertype);
if (!this->VertPainter || !this->VertPainter->IsA(vertpaintertype))
{
painter = this->CreatePainter(vertpaintertype);
if (painter)
{
this->SetVertPainter(painter);
painter->Delete();
vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New();
painter->SetDelegatePainter(sp);
sp->Delete();
}
}
if (!this->LinePainter || !this->LinePainter->IsA(linepaintertype))
{
if (strcmp(vertpaintertype, linepaintertype) == 0)
{
this->SetLinePainter(this->VertPainter);
}
else
{
painter = this->CreatePainter(linepaintertype);
if (painter)
{
this->SetLinePainter(painter);
painter->Delete();
vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New();
painter->SetDelegatePainter(sp);
sp->Delete();
}
}
}
if (!this->PolyPainter || !this->PolyPainter->IsA(polypaintertype))
{
if (strcmp(vertpaintertype, polypaintertype) == 0)
{
this->SetPolyPainter(this->VertPainter);
}
else if (strcmp(linepaintertype, polypaintertype) == 0)
{
this->SetPolyPainter(this->LinePainter);
}
else
{
painter = this->CreatePainter(polypaintertype);
if (painter)
{
this->SetPolyPainter(painter);
painter->Delete();
vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New();
painter->SetDelegatePainter(sp);
sp->Delete();
}
}
}
if (!this->StripPainter || !this->StripPainter->IsA(strippaintertype))
{
if (strcmp(vertpaintertype, strippaintertype) == 0)
{
this->SetStripPainter(this->VertPainter);
}
else if (strcmp(linepaintertype, strippaintertype) == 0)
{
this->SetStripPainter(this->LinePainter);
}
else if (strcmp(polypaintertype, strippaintertype) == 0)
{
this->SetStripPainter(this->PolyPainter);
}
else
{
painter = this->CreatePainter(strippaintertype);
if (painter)
{
this->SetStripPainter(painter);
painter->Delete();
vtkStandardPolyDataPainter* sp = vtkStandardPolyDataPainter::New();
painter->SetDelegatePainter(sp);
sp->Delete();
}
}
}
}
//-----------------------------------------------------------------------------
void vtkChooserPainter::SelectPainters(vtkRenderer *vtkNotUsed(renderer),
const char *&vertptype,
const char *&lineptype,
const char *&polyptype,
const char *&stripptype)
{
vertptype = "vtkPointsPainter";
lineptype = "vtkLinesPainter";
polyptype = "vtkPolygonsPainter";
stripptype = "vtkTStripsPainter";
// No elaborate selection as yet.
// Merely create the pipeline as the vtkOpenGLPolyDataMapper.
}
//-----------------------------------------------------------------------------
vtkPolyDataPainter* vtkChooserPainter::CreatePainter(const char *paintertype)
{
vtkPolyDataPainter* p = 0;
if (strcmp(paintertype, "vtkPointsPainter") == 0)
{
p = vtkPointsPainter::New();
}
else if (strcmp(paintertype, "vtkLinesPainter") == 0)
{
p = vtkLinesPainter::New();
}
else if (strcmp(paintertype, "vtkPolygonsPainter") == 0)
{
p = vtkPolygonsPainter::New();
}
else if (strcmp(paintertype, "vtkTStripsPainter") == 0)
{
p = vtkTStripsPainter::New();
}
else
{
vtkErrorMacro("Cannot create painter " << paintertype);
return 0;
}
this->ObserverPainterProgress(p);
return p;
}
//-----------------------------------------------------------------------------
void vtkChooserPainter::RenderInternal(vtkRenderer* renderer, vtkActor* actor,
unsigned long typeflags)
{
vtkIdType numVerts = this->PolyData->GetNumberOfVerts();
vtkIdType numLines = this->PolyData->GetNumberOfLines();
vtkIdType numPolys = this->PolyData->GetNumberOfPolys();
vtkIdType numStrips = this->PolyData->GetNumberOfStrips();
vtkIdType total_cells = (typeflags & vtkPainter::VERTS)?
this->PolyData->GetNumberOfVerts() : 0;
total_cells += (typeflags & vtkPainter::LINES)?
this->PolyData->GetNumberOfLines() : 0;
total_cells += (typeflags & vtkPainter::POLYS)?
this->PolyData->GetNumberOfPolys() : 0;
total_cells += (typeflags & vtkPainter::STRIPS)?
this->PolyData->GetNumberOfStrips() : 0;
if (total_cells == 0)
{
// nothing to render.
return;
}
this->ProgressOffset = 0.0;
this->TimeToDraw = 0.0;
if (typeflags & vtkPainter::VERTS)
{
//cout << this << "Verts" << endl;
this->ProgressScaleFactor = static_cast<double>(numVerts)/total_cells;
this->VertPainter->Render(renderer, actor, vtkPainter::VERTS);
this->TimeToDraw += this->VertPainter->GetTimeToDraw();
this->ProgressOffset += this->ProgressScaleFactor;
}
if (typeflags & vtkPainter::LINES)
{
//cout << this << "Lines" << endl;
this->ProgressScaleFactor = static_cast<double>(numLines)/total_cells;
this->LinePainter->Render(renderer, actor, vtkPainter::LINES);
this->TimeToDraw += this->LinePainter->GetTimeToDraw();
this->ProgressOffset += this->ProgressScaleFactor;
}
if (typeflags & vtkPainter::POLYS)
{
//cout << this << "Polys" << endl;
this->ProgressScaleFactor = static_cast<double>(numPolys)/total_cells;
this->PolyPainter->Render(renderer, actor, vtkPainter::POLYS);
this->TimeToDraw += this->PolyPainter->GetTimeToDraw();
this->ProgressOffset += this->ProgressScaleFactor;
}
if (typeflags & vtkPainter::STRIPS)
{
//cout << this << "Strips" << endl;
this->ProgressScaleFactor = static_cast<double>(numStrips)/total_cells;
this->StripPainter->Render(renderer, actor, vtkPainter::STRIPS);
this->TimeToDraw += this->StripPainter->GetTimeToDraw();
}
this->Superclass::RenderInternal(renderer, actor, typeflags);
}
//-----------------------------------------------------------------------------
void vtkChooserPainter::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "VertPainter: " << this->VertPainter << endl;
os << indent << "LinePainter: " << this->LinePainter << endl;
os << indent << "PolyPainter: " << this->PolyPainter << endl;
os << indent << "StripPainter: " << this->StripPainter << endl;
}
<|endoftext|> |
<commit_before>#include <glow/LogMessageBuilder.h>
#include <glow/logging.h>
namespace glow {
LogMessageBuilder::LogMessageBuilder(LogMessage::Level level, AbstractLogHandler* handler)
: std::stringstream()
, m_level(level)
, m_handler(handler)
{
}
LogMessageBuilder::LogMessageBuilder(const LogMessageBuilder& builder)
: m_level(builder.m_level)
, m_handler(builder.m_handler)
{
str(builder.str());
}
LogMessageBuilder::~LogMessageBuilder()
{
if (m_handler)
m_handler->handle(LogMessage(m_level, str()));
}
LogMessageBuilder& LogMessageBuilder::operator<<(const char * c)
{
write(c, std::strlen(c));
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(const std::string & str)
{
write(str.c_str(), str.length());
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(bool b)
{
*this << (b ? "true" : "false");
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(char c)
{
std::stringstream::operator<<(c);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(int i)
{
std::stringstream::operator<<(i);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(float f)
{
std::stringstream::operator<<(f);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(double d)
{
std::stringstream::operator<<(d);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(long double d)
{
std::stringstream::operator<<(d);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(unsigned u)
{
std::stringstream::operator<<(u);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(long l)
{
std::stringstream::operator<<(l);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(unsigned long ul)
{
std::stringstream::operator<<(ul);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(unsigned char uc)
{
std::stringstream::operator<<(uc);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(void * pointer)
{
std::stringstream::operator<<(pointer);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(std::ostream & (*manipulator)(std::ostream &))
{
std::stringstream::operator<<(manipulator);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(const glm::vec2 & v)
{
std::stringstream::operator<<("vec2(") << v.x << "," << v.y << ")";
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(const glm::vec3 & v)
{
std::stringstream::operator<<("vec3(") << v.x << "," << v.y << "," << v.z << ")";
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(const glm::vec4 & v)
{
std::stringstream::operator<<("vec4(") << v.x << "," << v.y << "," << v.z << "," << v.w << ")";
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(const glm::mat2 & m)
{
std::stringstream::operator<<("mat2(")
<< "(" << m[0][0] << ", " << m[0][1] << "), "
<< "(" << m[1][0] << ", " << m[1][1] << ")"
<< ")";
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(const glm::mat3 & m)
{
std::stringstream::operator<<("mat3(")
<< "(" << m[0][0] << ", " << m[0][1] << ", " << m[0][2] << "), "
<< "(" << m[1][0] << ", " << m[1][1] << ", " << m[1][2] <<"), "
<< "(" << m[2][0] << ", " << m[2][1] << ", " << m[2][2] <<")"
<< ")";
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(const glm::mat4 & m)
{
std::stringstream::operator<<("mat4(")
<< "(" << m[0][0] << ", " << m[0][1] << ", " << m[0][2] << ", " << m[0][3] << "), "
<< "(" << m[1][0] << ", " << m[1][1] << ", " << m[1][2] << ", " << m[1][3] <<"), "
<< "(" << m[2][0] << ", " << m[2][1] << ", " << m[2][2] << ", " << m[2][3] <<"), "
<< "(" << m[3][0] << ", " << m[3][1] << ", " << m[3][2] << ", " << m[3][3] <<")"
<< ")";
return *this;
}
} // namespace glow
<commit_msg>Rewrite logging code for glm::vec and glm::mat (fixes #55)<commit_after>#include <glow/LogMessageBuilder.h>
#include <glow/logging.h>
namespace glow {
LogMessageBuilder::LogMessageBuilder(LogMessage::Level level, AbstractLogHandler* handler)
: std::stringstream()
, m_level(level)
, m_handler(handler)
{
}
LogMessageBuilder::LogMessageBuilder(const LogMessageBuilder& builder)
: m_level(builder.m_level)
, m_handler(builder.m_handler)
{
str(builder.str());
}
LogMessageBuilder::~LogMessageBuilder()
{
if (m_handler)
m_handler->handle(LogMessage(m_level, str()));
}
LogMessageBuilder& LogMessageBuilder::operator<<(const char * c)
{
write(c, std::strlen(c));
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(const std::string & str)
{
write(str.c_str(), str.length());
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(bool b)
{
*this << (b ? "true" : "false");
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(char c)
{
std::stringstream::operator<<(c);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(int i)
{
std::stringstream::operator<<(i);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(float f)
{
std::stringstream::operator<<(f);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(double d)
{
std::stringstream::operator<<(d);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(long double d)
{
std::stringstream::operator<<(d);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(unsigned u)
{
std::stringstream::operator<<(u);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(long l)
{
std::stringstream::operator<<(l);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(unsigned long ul)
{
std::stringstream::operator<<(ul);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(unsigned char uc)
{
std::stringstream::operator<<(uc);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(void * pointer)
{
std::stringstream::operator<<(pointer);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(std::ostream & (*manipulator)(std::ostream &))
{
std::stringstream::operator<<(manipulator);
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(const glm::vec2 & v)
{
*this
<< "vec2("
<< v.x << ","
<< v.y << ")";
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(const glm::vec3 & v)
{
*this
<< "vec3("
<< v.x << ","
<< v.y << ","
<< v.z << ")";
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(const glm::vec4 & v)
{
*this
<< "vec4("
<< v.x << ","
<< v.y << ","
<< v.z << ","
<< v.w << ")";
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(const glm::mat2 & m)
{
*this
<< "mat2("
<< "(" << m[0][0] << ", " << m[0][1] << "), "
<< "(" << m[1][0] << ", " << m[1][1] << ")"
<< ")";
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(const glm::mat3 & m)
{
*this
<< "mat3("
<< "(" << m[0][0] << ", " << m[0][1] << ", " << m[0][2] << "), "
<< "(" << m[1][0] << ", " << m[1][1] << ", " << m[1][2] <<"), "
<< "(" << m[2][0] << ", " << m[2][1] << ", " << m[2][2] <<")"
<< ")";
return *this;
}
LogMessageBuilder& LogMessageBuilder::operator<<(const glm::mat4 & m)
{
*this
<< "mat4("
<< "(" << m[0][0] << ", " << m[0][1] << ", " << m[0][2] << ", " << m[0][3] << "), "
<< "(" << m[1][0] << ", " << m[1][1] << ", " << m[1][2] << ", " << m[1][3] <<"), "
<< "(" << m[2][0] << ", " << m[2][1] << ", " << m[2][2] << ", " << m[2][3] <<"), "
<< "(" << m[3][0] << ", " << m[3][1] << ", " << m[3][2] << ", " << m[3][3] <<")"
<< ")";
return *this;
}
} // namespace glow
<|endoftext|> |
<commit_before>#include "SerializationEssentials.h"
#ifndef OBJECTFACTORY_H
#include "ObjectFactory.h"
#endif
#ifndef OBJECTFORMATTER_H
#include "ObjectFormatter.h"
#endif
#ifndef OBJECTSERIALIZER_H
#include "ObjectSerializer.h"
#endif
#ifndef CASEBASEEX_H
#include "CaseBaseEx.h"
#endif
#ifndef CASEEX_H
#include "CaseEx.h"
#endif
#ifndef GAMESTATEEX_H
#include "GameStateEx.h"
#endif
#ifndef DESTROYENTITYTYPEGOAL_H
#include "DestroyEntityTypeGoal.h"
#endif
#ifndef COLLECTRESOURCEGOAL_H
#include "CollectResourceGoal.h"
#endif
#ifndef WINGAMEGOAL_H
#include "WinGameGoal.h"
#endif
#ifndef TRAINFORCEGOAL_H
#include "TrainForceGoal.h"
#endif
#ifndef DEPLOYARMYGOAL_H
#include "DeployArmyGoal.h"
#endif
#ifndef ATTACKENTITYACTION_H
#include "AttackEntityAction.h"
#endif
#ifndef ATTACKGROUNDACTION_H
#include "AttackGroundAction.h"
#endif
#ifndef BUILDACTIONEX_H
#include "BuildActionEx.h"
#endif
#ifndef RESEARCHACTION_H
#include "ResearchAction.h"
#endif
#ifndef TRAINACTION_H
#include "TrainAction.h"
#endif
#ifndef MOVEENTITYACTION_H
#include "MoveEntityAction.h"
#endif
#ifndef MOVEACTION_H
#include "MoveAction.h"
#ifndef GATHERRESOURCEACTION_H
#include "GatherResourceAction.h"
#endif
#ifndef RESOURCEEXIST_H
#include "ResourceExist.h"
#endif
#ifndef RESEARCHDONE_H
#include "ResearchDone.h"
#endif
#ifndef ENTITYCLASSNEARAREA_H
#include "EntityClassNearArea.h"
#endif
#ifndef NOT_H
#include "Not.h"
#endif
#ifndef OR_H
#include "Or.h"
#endif
#ifndef CELLFEATURE_H
#include "CellFeature.h"
#endif
#ifndef PLANGRAPH_H
#include "PlanGraph.h"
#endif
using namespace IStrategizer;
void SerializationEssentials::Init()
{
static bool initialized = false;
if (initialized)
return;
g_ObjectFactory.AddPrototype(new CaseEx);
g_ObjectFactory.AddPrototype(new GameStateEx);
g_ObjectFactory.AddPrototype(new CollectResourceGoal);
g_ObjectFactory.AddPrototype(new TrainForceGoal);
g_ObjectFactory.AddPrototype(new DeployArmyGoal);
g_ObjectFactory.AddPrototype(new DestroyEntityTypeGoal);
g_ObjectFactory.AddPrototype(new WinGameGoal);
g_ObjectFactory.AddPrototype(new AttackEntityAction);
g_ObjectFactory.AddPrototype(new AttackGroundAction);
g_ObjectFactory.AddPrototype(new ResearchAction);
g_ObjectFactory.AddPrototype(new TrainAction);
g_ObjectFactory.AddPrototype(new BuildActionEx);
g_ObjectFactory.AddPrototype(new MoveEntityAction);
g_ObjectFactory.AddPrototype(new MoveAction);
g_ObjectFactory.AddPrototype(new GatherResourceAction);
g_ObjectFactory.AddPrototype(new ResourceExist);
g_ObjectFactory.AddPrototype(new ResearchDone);
g_ObjectFactory.AddPrototype(new EntityClassExist);
g_ObjectFactory.AddPrototype(new EntityClassNearArea);
g_ObjectFactory.AddPrototype(new And);
g_ObjectFactory.AddPrototype(new Not);
g_ObjectFactory.AddPrototype(new Or);
g_ObjectFactory.AddPrototype(new PlanGraph);
g_ObjectFactory.AddPrototype(new Diagraph<NodeValue, EdgeAnnotation>, "Diagraph(PlanStepEx*,vector(Expression*))");
g_ObjectFactory.AddPrototype(new GraphNode<NodeValue, EdgeAnnotation>, "GraphNode(PlanStepEx*,vector(Expression*))");
g_ObjectFactory.AddPrototype(new GraphEdge<EdgeAnnotation>, "GraphEdge(vector(Expression*))");
g_ObjectFactory.AddPrototype(new CaseBaseEx);
g_ObjectFormatter.FinalizeTypeTable(g_ObjectSerializer.TypeTable(), g_ObjectFactory.GetObjectTable());
initialized = true;
}
<commit_msg>Fix missed #endif after rebase<commit_after>#include "SerializationEssentials.h"
#ifndef OBJECTFACTORY_H
#include "ObjectFactory.h"
#endif
#ifndef OBJECTFORMATTER_H
#include "ObjectFormatter.h"
#endif
#ifndef OBJECTSERIALIZER_H
#include "ObjectSerializer.h"
#endif
#ifndef CASEBASEEX_H
#include "CaseBaseEx.h"
#endif
#ifndef CASEEX_H
#include "CaseEx.h"
#endif
#ifndef GAMESTATEEX_H
#include "GameStateEx.h"
#endif
#ifndef DESTROYENTITYTYPEGOAL_H
#include "DestroyEntityTypeGoal.h"
#endif
#ifndef COLLECTRESOURCEGOAL_H
#include "CollectResourceGoal.h"
#endif
#ifndef WINGAMEGOAL_H
#include "WinGameGoal.h"
#endif
#ifndef TRAINFORCEGOAL_H
#include "TrainForceGoal.h"
#endif
#ifndef DEPLOYARMYGOAL_H
#include "DeployArmyGoal.h"
#endif
#ifndef ATTACKENTITYACTION_H
#include "AttackEntityAction.h"
#endif
#ifndef ATTACKGROUNDACTION_H
#include "AttackGroundAction.h"
#endif
#ifndef BUILDACTIONEX_H
#include "BuildActionEx.h"
#endif
#ifndef RESEARCHACTION_H
#include "ResearchAction.h"
#endif
#ifndef TRAINACTION_H
#include "TrainAction.h"
#endif
#ifndef MOVEENTITYACTION_H
#include "MoveEntityAction.h"
#endif
#ifndef MOVEACTION_H
#include "MoveAction.h"
#endif
#ifndef GATHERRESOURCEACTION_H
#include "GatherResourceAction.h"
#endif
#ifndef RESOURCEEXIST_H
#include "ResourceExist.h"
#endif
#ifndef RESEARCHDONE_H
#include "ResearchDone.h"
#endif
#ifndef ENTITYCLASSNEARAREA_H
#include "EntityClassNearArea.h"
#endif
#ifndef NOT_H
#include "Not.h"
#endif
#ifndef OR_H
#include "Or.h"
#endif
#ifndef CELLFEATURE_H
#include "CellFeature.h"
#endif
#ifndef PLANGRAPH_H
#include "PlanGraph.h"
#endif
using namespace IStrategizer;
void SerializationEssentials::Init()
{
static bool initialized = false;
if (initialized)
return;
g_ObjectFactory.AddPrototype(new CaseEx);
g_ObjectFactory.AddPrototype(new GameStateEx);
g_ObjectFactory.AddPrototype(new CollectResourceGoal);
g_ObjectFactory.AddPrototype(new TrainForceGoal);
g_ObjectFactory.AddPrototype(new DeployArmyGoal);
g_ObjectFactory.AddPrototype(new DestroyEntityTypeGoal);
g_ObjectFactory.AddPrototype(new WinGameGoal);
g_ObjectFactory.AddPrototype(new AttackEntityAction);
g_ObjectFactory.AddPrototype(new AttackGroundAction);
g_ObjectFactory.AddPrototype(new ResearchAction);
g_ObjectFactory.AddPrototype(new TrainAction);
g_ObjectFactory.AddPrototype(new BuildActionEx);
g_ObjectFactory.AddPrototype(new MoveEntityAction);
g_ObjectFactory.AddPrototype(new MoveAction);
g_ObjectFactory.AddPrototype(new GatherResourceAction);
g_ObjectFactory.AddPrototype(new ResourceExist);
g_ObjectFactory.AddPrototype(new ResearchDone);
g_ObjectFactory.AddPrototype(new EntityClassExist);
g_ObjectFactory.AddPrototype(new EntityClassNearArea);
g_ObjectFactory.AddPrototype(new And);
g_ObjectFactory.AddPrototype(new Not);
g_ObjectFactory.AddPrototype(new Or);
g_ObjectFactory.AddPrototype(new PlanGraph);
g_ObjectFactory.AddPrototype(new Diagraph<NodeValue, EdgeAnnotation>, "Diagraph(PlanStepEx*,vector(Expression*))");
g_ObjectFactory.AddPrototype(new GraphNode<NodeValue, EdgeAnnotation>, "GraphNode(PlanStepEx*,vector(Expression*))");
g_ObjectFactory.AddPrototype(new GraphEdge<EdgeAnnotation>, "GraphEdge(vector(Expression*))");
g_ObjectFactory.AddPrototype(new CaseBaseEx);
g_ObjectFormatter.FinalizeTypeTable(g_ObjectSerializer.TypeTable(), g_ObjectFactory.GetObjectTable());
initialized = true;
}
<|endoftext|> |
<commit_before>//===-- cc1as_main.cpp - Clang Assembler ---------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the entry point to the clang -cc1as functionality, which implements
// the direct interface to the LLVM MC based assembler.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/Diagnostic.h"
#include "clang/Driver/Arg.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/CC1AsOptions.h"
#include "clang/Driver/OptTable.h"
#include "clang/Driver/Options.h"
#include "clang/Frontend/DiagnosticOptions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Triple.h"
#include "llvm/MC/MCParser/MCAsmParser.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/system_error.h"
#include "llvm/Target/TargetAsmBackend.h"
#include "llvm/Target/TargetAsmInfo.h"
#include "llvm/Target/TargetAsmParser.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetLowering.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Target/TargetSelect.h"
using namespace clang;
using namespace clang::driver;
using namespace llvm;
namespace {
/// \brief Helper class for representing a single invocation of the assembler.
struct AssemblerInvocation {
/// @name Target Options
/// @{
std::string Triple;
/// @}
/// @name Language Options
/// @{
std::vector<std::string> IncludePaths;
unsigned NoInitialTextSection : 1;
unsigned SaveTemporaryLabels : 1;
/// @}
/// @name Frontend Options
/// @{
std::string InputFile;
std::vector<std::string> LLVMArgs;
std::string OutputPath;
enum FileType {
FT_Asm, ///< Assembly (.s) output, transliterate mode.
FT_Null, ///< No output, for timing purposes.
FT_Obj ///< Object file output.
};
FileType OutputType;
unsigned ShowHelp : 1;
unsigned ShowVersion : 1;
/// @}
/// @name Transliterate Options
/// @{
unsigned OutputAsmVariant;
unsigned ShowEncoding : 1;
unsigned ShowInst : 1;
/// @}
/// @name Assembler Options
/// @{
unsigned RelaxAll : 1;
unsigned NoExecStack : 1;
/// @}
public:
AssemblerInvocation() {
Triple = "";
NoInitialTextSection = 0;
InputFile = "-";
OutputPath = "-";
OutputType = FT_Asm;
OutputAsmVariant = 0;
ShowInst = 0;
ShowEncoding = 0;
RelaxAll = 0;
NoExecStack = 0;
}
static void CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
const char **ArgEnd, Diagnostic &Diags);
};
}
void AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
const char **ArgBegin,
const char **ArgEnd,
Diagnostic &Diags) {
using namespace clang::driver::cc1asoptions;
// Parse the arguments.
OwningPtr<OptTable> OptTbl(createCC1AsOptTable());
unsigned MissingArgIndex, MissingArgCount;
OwningPtr<InputArgList> Args(
OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
// Check for missing argument error.
if (MissingArgCount)
Diags.Report(diag::err_drv_missing_argument)
<< Args->getArgString(MissingArgIndex) << MissingArgCount;
// Issue errors on unknown arguments.
for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),
ie = Args->filtered_end(); it != ie; ++it)
Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);
// Construct the invocation.
// Target Options
Opts.Triple = Triple::normalize(Args->getLastArgValue(OPT_triple));
if (Opts.Triple.empty()) // Use the host triple if unspecified.
Opts.Triple = sys::getHostTriple();
// Language Options
Opts.IncludePaths = Args->getAllArgValues(OPT_I);
Opts.NoInitialTextSection = Args->hasArg(OPT_n);
Opts.SaveTemporaryLabels = Args->hasArg(OPT_L);
// Frontend Options
if (Args->hasArg(OPT_INPUT)) {
bool First = true;
for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
ie = Args->filtered_end(); it != ie; ++it, First=false) {
const Arg *A = it;
if (First)
Opts.InputFile = A->getValue(*Args);
else
Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
}
}
Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
if (Args->hasArg(OPT_fatal_warnings))
Opts.LLVMArgs.push_back("-fatal-assembler-warnings");
Opts.OutputPath = Args->getLastArgValue(OPT_o);
if (Arg *A = Args->getLastArg(OPT_filetype)) {
StringRef Name = A->getValue(*Args);
unsigned OutputType = StringSwitch<unsigned>(Name)
.Case("asm", FT_Asm)
.Case("null", FT_Null)
.Case("obj", FT_Obj)
.Default(~0U);
if (OutputType == ~0U)
Diags.Report(diag::err_drv_invalid_value)
<< A->getAsString(*Args) << Name;
else
Opts.OutputType = FileType(OutputType);
}
Opts.ShowHelp = Args->hasArg(OPT_help);
Opts.ShowVersion = Args->hasArg(OPT_version);
// Transliterate Options
Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant,
0, Diags);
Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
Opts.ShowInst = Args->hasArg(OPT_show_inst);
// Assemble Options
Opts.RelaxAll = Args->hasArg(OPT_relax_all);
Opts.NoExecStack = Args->hasArg(OPT_no_exec_stack);
}
static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
Diagnostic &Diags,
bool Binary) {
if (Opts.OutputPath.empty())
Opts.OutputPath = "-";
// Make sure that the Out file gets unlinked from the disk if we get a
// SIGINT.
if (Opts.OutputPath != "-")
sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath));
std::string Error;
raw_fd_ostream *Out =
new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
(Binary ? raw_fd_ostream::F_Binary : 0));
if (!Error.empty()) {
Diags.Report(diag::err_fe_unable_to_open_output)
<< Opts.OutputPath << Error;
return 0;
}
return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
}
static bool ExecuteAssembler(AssemblerInvocation &Opts, Diagnostic &Diags) {
// Get the target specific parser.
std::string Error;
const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));
if (!TheTarget) {
Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
return false;
}
OwningPtr<MemoryBuffer> BufferPtr;
if (error_code ec = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, BufferPtr)) {
Error = ec.message();
Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
return false;
}
MemoryBuffer *Buffer = BufferPtr.take();
SourceMgr SrcMgr;
// Tell SrcMgr about this buffer, which is what the parser will pick up.
SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
// Record the location of the include directories so that the lexer can find
// it later.
SrcMgr.setIncludeDirs(Opts.IncludePaths);
OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(Opts.Triple));
assert(MAI && "Unable to create target asm info!");
bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);
if (!Out)
return false;
// FIXME: We shouldn't need to do this (and link in codegen).
OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(Opts.Triple,
"", ""));
if (!TM) {
Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
return false;
}
const TargetAsmInfo *tai = new TargetAsmInfo(*TM);
MCContext Ctx(*MAI, tai);
if (Opts.SaveTemporaryLabels)
Ctx.setAllowTemporaryLabels(false);
OwningPtr<MCStreamer> Str;
const TargetLoweringObjectFile &TLOF =
TM->getTargetLowering()->getObjFileLowering();
const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(Ctx, *TM);
// FIXME: There is a bit of code duplication with addPassesToEmitFile.
if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
MCInstPrinter *IP =
TheTarget->createMCInstPrinter(*TM, Opts.OutputAsmVariant, *MAI);
MCCodeEmitter *CE = 0;
TargetAsmBackend *TAB = 0;
if (Opts.ShowEncoding) {
CE = TheTarget->createCodeEmitter(*TM, Ctx);
TAB = TheTarget->createAsmBackend(Opts.Triple);
}
Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true,
/*useLoc*/ true,
/*useCFI*/ true, IP, CE, TAB,
Opts.ShowInst));
} else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
Str.reset(createNullStreamer(Ctx));
} else {
assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
"Invalid file type!");
MCCodeEmitter *CE = TheTarget->createCodeEmitter(*TM, Ctx);
TargetAsmBackend *TAB = TheTarget->createAsmBackend(Opts.Triple);
Str.reset(TheTarget->createObjectStreamer(Opts.Triple, Ctx, *TAB, *Out,
CE, Opts.RelaxAll,
Opts.NoExecStack));
Str.get()->InitSections();
}
OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
*Str.get(), *MAI));
OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*Parser, *TM));
if (!TAP) {
Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
return false;
}
Parser->setTargetParser(*TAP.get());
bool Success = !Parser->Run(Opts.NoInitialTextSection);
// Close the output.
delete Out;
// Delete output on errors.
if (!Success && Opts.OutputPath != "-")
sys::Path(Opts.OutputPath).eraseFromDisk();
return Success;
}
static void LLVMErrorHandler(void *UserData, const std::string &Message) {
Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
Diags.Report(diag::err_fe_error_backend) << Message;
// We cannot recover from llvm errors.
exit(1);
}
int cc1as_main(const char **ArgBegin, const char **ArgEnd,
const char *Argv0, void *MainAddr) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
// Initialize targets and assembly printers/parsers.
InitializeAllTargetInfos();
// FIXME: We shouldn't need to initialize the Target(Machine)s.
InitializeAllTargets();
InitializeAllAsmPrinters();
InitializeAllAsmParsers();
// Construct our diagnostic client.
TextDiagnosticPrinter *DiagClient
= new TextDiagnosticPrinter(errs(), DiagnosticOptions());
DiagClient->setPrefix("clang -cc1as");
llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
Diagnostic Diags(DiagID, DiagClient);
// Set an error handler, so that any LLVM backend diagnostics go through our
// error handler.
ScopedFatalErrorHandler FatalErrorHandler
(LLVMErrorHandler, static_cast<void*>(&Diags));
// Parse the arguments.
AssemblerInvocation Asm;
AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags);
// Honor -help.
if (Asm.ShowHelp) {
llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable());
Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler");
return 0;
}
// Honor -version.
//
// FIXME: Use a better -version message?
if (Asm.ShowVersion) {
llvm::cl::PrintVersionMessage();
return 0;
}
// Honor -mllvm.
//
// FIXME: Remove this, one day.
if (!Asm.LLVMArgs.empty()) {
unsigned NumArgs = Asm.LLVMArgs.size();
const char **Args = new const char*[NumArgs + 2];
Args[0] = "clang (LLVM option parsing)";
for (unsigned i = 0; i != NumArgs; ++i)
Args[i + 1] = Asm.LLVMArgs[i].c_str();
Args[NumArgs + 1] = 0;
llvm::cl::ParseCommandLineOptions(NumArgs + 1, const_cast<char **>(Args));
}
// Execute the invocation, unless there were parsing errors.
bool Success = false;
if (!Diags.hasErrorOccurred())
Success = ExecuteAssembler(Asm, Diags);
// If any timers were active but haven't been destroyed yet, print their
// results now.
TimerGroup::printAll(errs());
return !Success;
}
<commit_msg>createMCInstPrinter doesn't need TargetMachine anymore.<commit_after>//===-- cc1as_main.cpp - Clang Assembler ---------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the entry point to the clang -cc1as functionality, which implements
// the direct interface to the LLVM MC based assembler.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/Diagnostic.h"
#include "clang/Driver/Arg.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/CC1AsOptions.h"
#include "clang/Driver/OptTable.h"
#include "clang/Driver/Options.h"
#include "clang/Frontend/DiagnosticOptions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Triple.h"
#include "llvm/MC/MCParser/MCAsmParser.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/system_error.h"
#include "llvm/Target/TargetAsmBackend.h"
#include "llvm/Target/TargetAsmInfo.h"
#include "llvm/Target/TargetAsmParser.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetLowering.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Target/TargetSelect.h"
using namespace clang;
using namespace clang::driver;
using namespace llvm;
namespace {
/// \brief Helper class for representing a single invocation of the assembler.
struct AssemblerInvocation {
/// @name Target Options
/// @{
std::string Triple;
/// @}
/// @name Language Options
/// @{
std::vector<std::string> IncludePaths;
unsigned NoInitialTextSection : 1;
unsigned SaveTemporaryLabels : 1;
/// @}
/// @name Frontend Options
/// @{
std::string InputFile;
std::vector<std::string> LLVMArgs;
std::string OutputPath;
enum FileType {
FT_Asm, ///< Assembly (.s) output, transliterate mode.
FT_Null, ///< No output, for timing purposes.
FT_Obj ///< Object file output.
};
FileType OutputType;
unsigned ShowHelp : 1;
unsigned ShowVersion : 1;
/// @}
/// @name Transliterate Options
/// @{
unsigned OutputAsmVariant;
unsigned ShowEncoding : 1;
unsigned ShowInst : 1;
/// @}
/// @name Assembler Options
/// @{
unsigned RelaxAll : 1;
unsigned NoExecStack : 1;
/// @}
public:
AssemblerInvocation() {
Triple = "";
NoInitialTextSection = 0;
InputFile = "-";
OutputPath = "-";
OutputType = FT_Asm;
OutputAsmVariant = 0;
ShowInst = 0;
ShowEncoding = 0;
RelaxAll = 0;
NoExecStack = 0;
}
static void CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
const char **ArgEnd, Diagnostic &Diags);
};
}
void AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
const char **ArgBegin,
const char **ArgEnd,
Diagnostic &Diags) {
using namespace clang::driver::cc1asoptions;
// Parse the arguments.
OwningPtr<OptTable> OptTbl(createCC1AsOptTable());
unsigned MissingArgIndex, MissingArgCount;
OwningPtr<InputArgList> Args(
OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
// Check for missing argument error.
if (MissingArgCount)
Diags.Report(diag::err_drv_missing_argument)
<< Args->getArgString(MissingArgIndex) << MissingArgCount;
// Issue errors on unknown arguments.
for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),
ie = Args->filtered_end(); it != ie; ++it)
Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);
// Construct the invocation.
// Target Options
Opts.Triple = Triple::normalize(Args->getLastArgValue(OPT_triple));
if (Opts.Triple.empty()) // Use the host triple if unspecified.
Opts.Triple = sys::getHostTriple();
// Language Options
Opts.IncludePaths = Args->getAllArgValues(OPT_I);
Opts.NoInitialTextSection = Args->hasArg(OPT_n);
Opts.SaveTemporaryLabels = Args->hasArg(OPT_L);
// Frontend Options
if (Args->hasArg(OPT_INPUT)) {
bool First = true;
for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
ie = Args->filtered_end(); it != ie; ++it, First=false) {
const Arg *A = it;
if (First)
Opts.InputFile = A->getValue(*Args);
else
Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
}
}
Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
if (Args->hasArg(OPT_fatal_warnings))
Opts.LLVMArgs.push_back("-fatal-assembler-warnings");
Opts.OutputPath = Args->getLastArgValue(OPT_o);
if (Arg *A = Args->getLastArg(OPT_filetype)) {
StringRef Name = A->getValue(*Args);
unsigned OutputType = StringSwitch<unsigned>(Name)
.Case("asm", FT_Asm)
.Case("null", FT_Null)
.Case("obj", FT_Obj)
.Default(~0U);
if (OutputType == ~0U)
Diags.Report(diag::err_drv_invalid_value)
<< A->getAsString(*Args) << Name;
else
Opts.OutputType = FileType(OutputType);
}
Opts.ShowHelp = Args->hasArg(OPT_help);
Opts.ShowVersion = Args->hasArg(OPT_version);
// Transliterate Options
Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant,
0, Diags);
Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
Opts.ShowInst = Args->hasArg(OPT_show_inst);
// Assemble Options
Opts.RelaxAll = Args->hasArg(OPT_relax_all);
Opts.NoExecStack = Args->hasArg(OPT_no_exec_stack);
}
static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
Diagnostic &Diags,
bool Binary) {
if (Opts.OutputPath.empty())
Opts.OutputPath = "-";
// Make sure that the Out file gets unlinked from the disk if we get a
// SIGINT.
if (Opts.OutputPath != "-")
sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath));
std::string Error;
raw_fd_ostream *Out =
new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
(Binary ? raw_fd_ostream::F_Binary : 0));
if (!Error.empty()) {
Diags.Report(diag::err_fe_unable_to_open_output)
<< Opts.OutputPath << Error;
return 0;
}
return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
}
static bool ExecuteAssembler(AssemblerInvocation &Opts, Diagnostic &Diags) {
// Get the target specific parser.
std::string Error;
const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));
if (!TheTarget) {
Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
return false;
}
OwningPtr<MemoryBuffer> BufferPtr;
if (error_code ec = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, BufferPtr)) {
Error = ec.message();
Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
return false;
}
MemoryBuffer *Buffer = BufferPtr.take();
SourceMgr SrcMgr;
// Tell SrcMgr about this buffer, which is what the parser will pick up.
SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
// Record the location of the include directories so that the lexer can find
// it later.
SrcMgr.setIncludeDirs(Opts.IncludePaths);
OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(Opts.Triple));
assert(MAI && "Unable to create target asm info!");
bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);
if (!Out)
return false;
// FIXME: We shouldn't need to do this (and link in codegen).
OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(Opts.Triple,
"", ""));
if (!TM) {
Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
return false;
}
const TargetAsmInfo *tai = new TargetAsmInfo(*TM);
MCContext Ctx(*MAI, tai);
if (Opts.SaveTemporaryLabels)
Ctx.setAllowTemporaryLabels(false);
OwningPtr<MCStreamer> Str;
const TargetLoweringObjectFile &TLOF =
TM->getTargetLowering()->getObjFileLowering();
const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(Ctx, *TM);
// FIXME: There is a bit of code duplication with addPassesToEmitFile.
if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
MCInstPrinter *IP =
TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI);
MCCodeEmitter *CE = 0;
TargetAsmBackend *TAB = 0;
if (Opts.ShowEncoding) {
CE = TheTarget->createCodeEmitter(*TM, Ctx);
TAB = TheTarget->createAsmBackend(Opts.Triple);
}
Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true,
/*useLoc*/ true,
/*useCFI*/ true, IP, CE, TAB,
Opts.ShowInst));
} else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
Str.reset(createNullStreamer(Ctx));
} else {
assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
"Invalid file type!");
MCCodeEmitter *CE = TheTarget->createCodeEmitter(*TM, Ctx);
TargetAsmBackend *TAB = TheTarget->createAsmBackend(Opts.Triple);
Str.reset(TheTarget->createObjectStreamer(Opts.Triple, Ctx, *TAB, *Out,
CE, Opts.RelaxAll,
Opts.NoExecStack));
Str.get()->InitSections();
}
OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
*Str.get(), *MAI));
OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*Parser, *TM));
if (!TAP) {
Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
return false;
}
Parser->setTargetParser(*TAP.get());
bool Success = !Parser->Run(Opts.NoInitialTextSection);
// Close the output.
delete Out;
// Delete output on errors.
if (!Success && Opts.OutputPath != "-")
sys::Path(Opts.OutputPath).eraseFromDisk();
return Success;
}
static void LLVMErrorHandler(void *UserData, const std::string &Message) {
Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
Diags.Report(diag::err_fe_error_backend) << Message;
// We cannot recover from llvm errors.
exit(1);
}
int cc1as_main(const char **ArgBegin, const char **ArgEnd,
const char *Argv0, void *MainAddr) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
// Initialize targets and assembly printers/parsers.
InitializeAllTargetInfos();
// FIXME: We shouldn't need to initialize the Target(Machine)s.
InitializeAllTargets();
InitializeAllAsmPrinters();
InitializeAllAsmParsers();
// Construct our diagnostic client.
TextDiagnosticPrinter *DiagClient
= new TextDiagnosticPrinter(errs(), DiagnosticOptions());
DiagClient->setPrefix("clang -cc1as");
llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
Diagnostic Diags(DiagID, DiagClient);
// Set an error handler, so that any LLVM backend diagnostics go through our
// error handler.
ScopedFatalErrorHandler FatalErrorHandler
(LLVMErrorHandler, static_cast<void*>(&Diags));
// Parse the arguments.
AssemblerInvocation Asm;
AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags);
// Honor -help.
if (Asm.ShowHelp) {
llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable());
Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler");
return 0;
}
// Honor -version.
//
// FIXME: Use a better -version message?
if (Asm.ShowVersion) {
llvm::cl::PrintVersionMessage();
return 0;
}
// Honor -mllvm.
//
// FIXME: Remove this, one day.
if (!Asm.LLVMArgs.empty()) {
unsigned NumArgs = Asm.LLVMArgs.size();
const char **Args = new const char*[NumArgs + 2];
Args[0] = "clang (LLVM option parsing)";
for (unsigned i = 0; i != NumArgs; ++i)
Args[i + 1] = Asm.LLVMArgs[i].c_str();
Args[NumArgs + 1] = 0;
llvm::cl::ParseCommandLineOptions(NumArgs + 1, const_cast<char **>(Args));
}
// Execute the invocation, unless there were parsing errors.
bool Success = false;
if (!Diags.hasErrorOccurred())
Success = ExecuteAssembler(Asm, Diags);
// If any timers were active but haven't been destroyed yet, print their
// results now.
TimerGroup::printAll(errs());
return !Success;
}
<|endoftext|> |
<commit_before>/*
* molecularmaps.cpp
* Copyright (C) 2009-2015 by MegaMol Team
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "molecularmaps/molecularmaps.h"
#include "MapGenerator.h"
#include "mmcore/api/MegaMolCore.std.h"
#include "mmcore/utility/plugins/Plugin200Instance.h"
#include "mmcore/versioninfo.h"
#include "vislib/vislibversion.h"
/* anonymous namespace hides this type from any other object files */
namespace {
/** Implementing the instance class of this plugin */
class plugin_instance : public ::megamol::core::utility::plugins::Plugin200Instance {
public:
/** ctor */
plugin_instance(void)
: ::megamol::core::utility::plugins::Plugin200Instance(
/* machine-readable plugin assembly name */
"molecularmaps", // TODO: Change this!
/* human-readable plugin description */
"New version of the molecular maps creator") {
// here we could perform addition initialization
};
/** Dtor */
virtual ~plugin_instance(void) {
// here we could perform addition de-initialization
}
/** Registers modules and calls */
virtual void registerClasses(void) {
// register modules here:
//
// TODO: Register your plugin's modules here
// like:
// this->module_descriptions.RegisterAutoDescription<megamol::molecularmaps::MyModule1>();
// this->module_descriptions.RegisterAutoDescription<megamol::molecularmaps::MyModule2>();
// ...
//
this->module_descriptions.RegisterAutoDescription<megamol::molecularmaps::MapGenerator>();
// register calls here:
//
// TODO: Register your plugin's calls here
// like:
// this->call_descriptions.RegisterAutoDescription<megamol::molecularmaps::MyCall1>();
// this->call_descriptions.RegisterAutoDescription<megamol::molecularmaps::MyCall2>();
// ...
//
}
MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_plugininstance_connectStatics
};
}
/*
* mmplgPluginAPIVersion
*/
MOLECULARMAPS_API int mmplgPluginAPIVersion(void) {
MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgPluginAPIVersion
}
/*
* mmplgGetPluginCompatibilityInfo
*/
MOLECULARMAPS_API
::megamol::core::utility::plugins::PluginCompatibilityInfo *
mmplgGetPluginCompatibilityInfo(
::megamol::core::utility::plugins::ErrorCallback onError) {
// compatibility information with core and vislib
using ::megamol::core::utility::plugins::PluginCompatibilityInfo;
using ::megamol::core::utility::plugins::LibraryVersionInfo;
PluginCompatibilityInfo *ci = new PluginCompatibilityInfo;
ci->libs_cnt = 2;
ci->libs = new LibraryVersionInfo[2];
SetLibraryVersionInfo(ci->libs[0], "MegaMolCore",
MEGAMOL_CORE_MAJOR_VER, MEGAMOL_CORE_MINOR_VER, MEGAMOL_CORE_COMP_REV, 0
#if defined(DEBUG) || defined(_DEBUG)
| MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DEBUG_BUILD
#endif
#if defined(MEGAMOL_CORE_DIRTY) && (MEGAMOL_CORE_DIRTY != 0)
| MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DIRTY_BUILD
#endif
);
SetLibraryVersionInfo(ci->libs[1], "vislib",
VISLIB_VERSION_MAJOR, VISLIB_VERSION_MINOR, VISLIB_VERSION_REVISION, 0
#if defined(DEBUG) || defined(_DEBUG)
| MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DEBUG_BUILD
#endif
#if defined(VISLIB_DIRTY_BUILD) && (VISLIB_DIRTY_BUILD != 0)
| MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DIRTY_BUILD
#endif
);
//
// If you want to test additional compatibilties, add the corresponding versions here
//
return ci;
}
/*
* mmplgReleasePluginCompatibilityInfo
*/
MOLECULARMAPS_API
void mmplgReleasePluginCompatibilityInfo(
::megamol::core::utility::plugins::PluginCompatibilityInfo* ci) {
// release compatiblity data on the correct heap
MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgReleasePluginCompatibilityInfo(ci)
}
/*
* mmplgGetPluginInstance
*/
MOLECULARMAPS_API
::megamol::core::utility::plugins::AbstractPluginInstance*
mmplgGetPluginInstance(
::megamol::core::utility::plugins::ErrorCallback onError) {
MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgGetPluginInstance(plugin_instance, onError)
}
/*
* mmplgReleasePluginInstance
*/
MOLECULARMAPS_API
void mmplgReleasePluginInstance(
::megamol::core::utility::plugins::AbstractPluginInstance* pi) {
MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgReleasePluginInstance(pi)
}
<commit_msg>adaptions to new megamol version<commit_after>/*
* molecularmaps.cpp
* Copyright (C) 2009-2015 by MegaMol Team
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "molecularmaps/molecularmaps.h"
#include "MapGenerator.h"
#include "mmcore/api/MegaMolCore.std.h"
#include "mmcore/utility/plugins/Plugin200Instance.h"
#include "mmcore/versioninfo.h"
#include "vislib/vislibversion.h"
/* anonymous namespace hides this type from any other object files */
namespace {
/** Implementing the instance class of this plugin */
class plugin_instance : public ::megamol::core::utility::plugins::Plugin200Instance {
public:
/** ctor */
plugin_instance(void)
: ::megamol::core::utility::plugins::Plugin200Instance(
/* machine-readable plugin assembly name */
"molecularmaps", // TODO: Change this!
/* human-readable plugin description */
"New version of the molecular maps creator") {
// here we could perform addition initialization
};
/** Dtor */
virtual ~plugin_instance(void) {
// here we could perform addition de-initialization
}
/** Registers modules and calls */
virtual void registerClasses(void) {
// register modules here:
//
// TODO: Register your plugin's modules here
// like:
// this->module_descriptions.RegisterAutoDescription<megamol::molecularmaps::MyModule1>();
// this->module_descriptions.RegisterAutoDescription<megamol::molecularmaps::MyModule2>();
// ...
//
this->module_descriptions.RegisterAutoDescription<megamol::molecularmaps::MapGenerator>();
// register calls here:
//
// TODO: Register your plugin's calls here
// like:
// this->call_descriptions.RegisterAutoDescription<megamol::molecularmaps::MyCall1>();
// this->call_descriptions.RegisterAutoDescription<megamol::molecularmaps::MyCall2>();
// ...
//
}
MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_plugininstance_connectStatics
};
}
/*
* mmplgPluginAPIVersion
*/
MOLECULARMAPS_API int mmplgPluginAPIVersion(void) {
MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgPluginAPIVersion
}
/*
* mmplgGetPluginCompatibilityInfo
*/
MOLECULARMAPS_API
::megamol::core::utility::plugins::PluginCompatibilityInfo *
mmplgGetPluginCompatibilityInfo(
::megamol::core::utility::plugins::ErrorCallback onError) {
// compatibility information with core and vislib
using ::megamol::core::utility::plugins::PluginCompatibilityInfo;
using ::megamol::core::utility::plugins::LibraryVersionInfo;
PluginCompatibilityInfo *ci = new PluginCompatibilityInfo;
ci->libs_cnt = 2;
ci->libs = new LibraryVersionInfo[2];
SetLibraryVersionInfo(ci->libs[0], "MegaMolCore",
MEGAMOL_CORE_MAJOR_VER, MEGAMOL_CORE_MINOR_VER, MEGAMOL_CORE_COMP_REV, 0
#if defined(DEBUG) || defined(_DEBUG)
| MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DEBUG_BUILD
#endif
#if defined(MEGAMOL_CORE_DIRTY) && (MEGAMOL_CORE_DIRTY != 0)
| MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DIRTY_BUILD
#endif
);
SetLibraryVersionInfo(ci->libs[1], "vislib",
vislib::VISLIB_VERSION_MAJOR, vislib::VISLIB_VERSION_MINOR, vislib::VISLIB_VERSION_REVISION, 0
#if defined(DEBUG) || defined(_DEBUG)
| MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DEBUG_BUILD
#endif
#if defined(VISLIB_DIRTY_BUILD) && (VISLIB_DIRTY_BUILD != 0)
| MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DIRTY_BUILD
#endif
);
//
// If you want to test additional compatibilties, add the corresponding versions here
//
return ci;
}
/*
* mmplgReleasePluginCompatibilityInfo
*/
MOLECULARMAPS_API
void mmplgReleasePluginCompatibilityInfo(
::megamol::core::utility::plugins::PluginCompatibilityInfo* ci) {
// release compatiblity data on the correct heap
MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgReleasePluginCompatibilityInfo(ci)
}
/*
* mmplgGetPluginInstance
*/
MOLECULARMAPS_API
::megamol::core::utility::plugins::AbstractPluginInstance*
mmplgGetPluginInstance(
::megamol::core::utility::plugins::ErrorCallback onError) {
MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgGetPluginInstance(plugin_instance, onError)
}
/*
* mmplgReleasePluginInstance
*/
MOLECULARMAPS_API
void mmplgReleasePluginInstance(
::megamol::core::utility::plugins::AbstractPluginInstance* pi) {
MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgReleasePluginInstance(pi)
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 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.
//
// This file defines a class that contains various method related to branding.
// It provides only default implementations of these methods. Usually to add
// specific branding, we will need to extend this class with a custom
// implementation.
#include "chrome/installer/util/browser_distribution.h"
#include "base/atomicops.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/logging.h"
#include "base/win/registry.h"
#include "chrome/common/env_vars.h"
#include "chrome/installer/util/chrome_frame_distribution.h"
#include "chrome/installer/util/chromium_binaries_distribution.h"
#include "chrome/installer/util/google_chrome_distribution.h"
#include "chrome/installer/util/google_chrome_binaries_distribution.h"
#include "chrome/installer/util/google_chrome_sxs_distribution.h"
#include "chrome/installer/util/install_util.h"
#include "chrome/installer/util/l10n_string_util.h"
#include "chrome/installer/util/master_preferences.h"
#include "installer_util_strings.h" // NOLINT
using installer::MasterPreferences;
namespace {
const wchar_t kCommandExecuteImplUuid[] =
L"{A2DF06F9-A21A-44A8-8A99-8B9C84F29160}";
const wchar_t kDelegateExecuteLibUuid[] =
L"{7779FB70-B399-454A-AA1A-BAA850032B10}";
const wchar_t kDelegateExecuteLibVersion[] = L"1.0";
const wchar_t kICommandExecuteImplUuid[] =
L"{0BA0D4E9-2259-4963-B9AE-A839F7CB7544}";
// The BrowserDistribution objects are never freed.
BrowserDistribution* g_browser_distribution = NULL;
BrowserDistribution* g_chrome_frame_distribution = NULL;
BrowserDistribution* g_binaries_distribution = NULL;
// Returns true if currently running in npchrome_frame.dll
bool IsChromeFrameModule() {
FilePath module_path;
PathService::Get(base::FILE_MODULE, &module_path);
return FilePath::CompareEqualIgnoreCase(module_path.BaseName().value(),
installer::kChromeFrameDll);
}
BrowserDistribution::Type GetCurrentDistributionType() {
static BrowserDistribution::Type type =
(MasterPreferences::ForCurrentProcess().install_chrome_frame() ||
IsChromeFrameModule()) ?
BrowserDistribution::CHROME_FRAME :
BrowserDistribution::CHROME_BROWSER;
return type;
}
} // end namespace
// CHROME_BINARIES represents the binaries shared by multi-install products and
// is not a product in and of itself, so it is not present in this collection.
const BrowserDistribution::Type BrowserDistribution::kProductTypes[] = {
BrowserDistribution::CHROME_BROWSER,
BrowserDistribution::CHROME_FRAME,
};
const size_t BrowserDistribution::kNumProductTypes =
arraysize(BrowserDistribution::kProductTypes);
BrowserDistribution::BrowserDistribution()
: type_(CHROME_BROWSER) {
}
BrowserDistribution::BrowserDistribution(Type type)
: type_(type) {
}
template<class DistributionClass>
BrowserDistribution* BrowserDistribution::GetOrCreateBrowserDistribution(
BrowserDistribution** dist) {
if (!*dist) {
DistributionClass* temp = new DistributionClass();
if (base::subtle::NoBarrier_CompareAndSwap(
reinterpret_cast<base::subtle::AtomicWord*>(dist), NULL,
reinterpret_cast<base::subtle::AtomicWord>(temp)) != NULL)
delete temp;
}
return *dist;
}
BrowserDistribution* BrowserDistribution::GetDistribution() {
return GetSpecificDistribution(GetCurrentDistributionType());
}
// static
BrowserDistribution* BrowserDistribution::GetSpecificDistribution(
BrowserDistribution::Type type) {
BrowserDistribution* dist = NULL;
switch (type) {
case CHROME_BROWSER:
#if defined(GOOGLE_CHROME_BUILD)
if (InstallUtil::IsChromeSxSProcess()) {
dist = GetOrCreateBrowserDistribution<GoogleChromeSxSDistribution>(
&g_browser_distribution);
} else {
dist = GetOrCreateBrowserDistribution<GoogleChromeDistribution>(
&g_browser_distribution);
}
#else
dist = GetOrCreateBrowserDistribution<BrowserDistribution>(
&g_browser_distribution);
#endif
break;
case CHROME_FRAME:
dist = GetOrCreateBrowserDistribution<ChromeFrameDistribution>(
&g_chrome_frame_distribution);
break;
default:
DCHECK_EQ(CHROME_BINARIES, type);
#if defined(GOOGLE_CHROME_BUILD)
dist = GetOrCreateBrowserDistribution<GoogleChromeBinariesDistribution>(
&g_binaries_distribution);
#else
dist = GetOrCreateBrowserDistribution<ChromiumBinariesDistribution>(
&g_binaries_distribution);
#endif
}
return dist;
}
void BrowserDistribution::DoPostUninstallOperations(
const Version& version, const FilePath& local_data_path,
const std::wstring& distribution_data) {
}
std::wstring BrowserDistribution::GetAppGuid() {
return L"";
}
std::wstring BrowserDistribution::GetApplicationName() {
return L"Chromium";
}
std::wstring BrowserDistribution::GetAppShortCutName() {
return GetApplicationName();
}
std::wstring BrowserDistribution::GetAlternateApplicationName() {
return L"The Internet";
}
std::wstring BrowserDistribution::GetBrowserAppId() {
return L"Chromium";
}
std::wstring BrowserDistribution::GetInstallSubDir() {
return L"Chromium";
}
std::wstring BrowserDistribution::GetPublisherName() {
return L"Chromium";
}
std::wstring BrowserDistribution::GetAppDescription() {
return L"Browse the web";
}
std::wstring BrowserDistribution::GetLongAppDescription() {
const std::wstring& app_description =
installer::GetLocalizedString(IDS_PRODUCT_DESCRIPTION_BASE);
return app_description;
}
std::string BrowserDistribution::GetSafeBrowsingName() {
return "chromium";
}
std::wstring BrowserDistribution::GetStateKey() {
return L"Software\\Chromium";
}
std::wstring BrowserDistribution::GetStateMediumKey() {
return L"Software\\Chromium";
}
std::wstring BrowserDistribution::GetStatsServerURL() {
return L"";
}
std::string BrowserDistribution::GetNetworkStatsServer() const {
return "";
}
std::string BrowserDistribution::GetHttpPipeliningTestServer() const {
return "";
}
std::wstring BrowserDistribution::GetDistributionData(HKEY root_key) {
return L"";
}
std::wstring BrowserDistribution::GetUninstallLinkName() {
return L"Uninstall Chromium";
}
std::wstring BrowserDistribution::GetUninstallRegPath() {
return L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Chromium";
}
std::wstring BrowserDistribution::GetVersionKey() {
return L"Software\\Chromium";
}
bool BrowserDistribution::CanSetAsDefault() {
return true;
}
bool BrowserDistribution::CanCreateDesktopShortcuts() {
return true;
}
int BrowserDistribution::GetIconIndex() {
return 0;
}
bool BrowserDistribution::GetChromeChannel(std::wstring* channel) {
return false;
}
bool BrowserDistribution::GetDelegateExecuteHandlerData(
string16* handler_class_uuid,
string16* type_lib_uuid,
string16* type_lib_version,
string16* interface_uuid) {
if (handler_class_uuid)
*handler_class_uuid = kCommandExecuteImplUuid;
if (type_lib_uuid)
*type_lib_uuid = kDelegateExecuteLibUuid;
if (type_lib_version)
*type_lib_version = kDelegateExecuteLibVersion;
if (interface_uuid)
*interface_uuid = kICommandExecuteImplUuid;
return true;
}
void BrowserDistribution::UpdateInstallStatus(bool system_install,
installer::ArchiveType archive_type,
installer::InstallStatus install_status) {
}
bool BrowserDistribution::GetExperimentDetails(
UserExperiment* experiment, int flavor) {
return false;
}
void BrowserDistribution::LaunchUserExperiment(
const FilePath& setup_path, installer::InstallStatus status,
const Version& version, const installer::Product& product,
bool system_level) {
}
void BrowserDistribution::InactiveUserToastExperiment(int flavor,
const std::wstring& experiment_group,
const installer::Product& installation,
const FilePath& application_path) {
}
<commit_msg>Revert 133006 - Support the DelegateExecute verb handler for Chromium builds.<commit_after>// Copyright (c) 2012 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.
//
// This file defines a class that contains various method related to branding.
// It provides only default implementations of these methods. Usually to add
// specific branding, we will need to extend this class with a custom
// implementation.
#include "chrome/installer/util/browser_distribution.h"
#include "base/atomicops.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/logging.h"
#include "base/win/registry.h"
#include "chrome/common/env_vars.h"
#include "chrome/installer/util/chrome_frame_distribution.h"
#include "chrome/installer/util/chromium_binaries_distribution.h"
#include "chrome/installer/util/google_chrome_distribution.h"
#include "chrome/installer/util/google_chrome_binaries_distribution.h"
#include "chrome/installer/util/google_chrome_sxs_distribution.h"
#include "chrome/installer/util/install_util.h"
#include "chrome/installer/util/l10n_string_util.h"
#include "chrome/installer/util/master_preferences.h"
#include "installer_util_strings.h" // NOLINT
using installer::MasterPreferences;
namespace {
// The BrowserDistribution objects are never freed.
BrowserDistribution* g_browser_distribution = NULL;
BrowserDistribution* g_chrome_frame_distribution = NULL;
BrowserDistribution* g_binaries_distribution = NULL;
// Returns true if currently running in npchrome_frame.dll
bool IsChromeFrameModule() {
FilePath module_path;
PathService::Get(base::FILE_MODULE, &module_path);
return FilePath::CompareEqualIgnoreCase(module_path.BaseName().value(),
installer::kChromeFrameDll);
}
BrowserDistribution::Type GetCurrentDistributionType() {
static BrowserDistribution::Type type =
(MasterPreferences::ForCurrentProcess().install_chrome_frame() ||
IsChromeFrameModule()) ?
BrowserDistribution::CHROME_FRAME :
BrowserDistribution::CHROME_BROWSER;
return type;
}
} // end namespace
// CHROME_BINARIES represents the binaries shared by multi-install products and
// is not a product in and of itself, so it is not present in this collection.
const BrowserDistribution::Type BrowserDistribution::kProductTypes[] = {
BrowserDistribution::CHROME_BROWSER,
BrowserDistribution::CHROME_FRAME,
};
const size_t BrowserDistribution::kNumProductTypes =
arraysize(BrowserDistribution::kProductTypes);
BrowserDistribution::BrowserDistribution()
: type_(CHROME_BROWSER) {
}
BrowserDistribution::BrowserDistribution(Type type)
: type_(type) {
}
template<class DistributionClass>
BrowserDistribution* BrowserDistribution::GetOrCreateBrowserDistribution(
BrowserDistribution** dist) {
if (!*dist) {
DistributionClass* temp = new DistributionClass();
if (base::subtle::NoBarrier_CompareAndSwap(
reinterpret_cast<base::subtle::AtomicWord*>(dist), NULL,
reinterpret_cast<base::subtle::AtomicWord>(temp)) != NULL)
delete temp;
}
return *dist;
}
BrowserDistribution* BrowserDistribution::GetDistribution() {
return GetSpecificDistribution(GetCurrentDistributionType());
}
// static
BrowserDistribution* BrowserDistribution::GetSpecificDistribution(
BrowserDistribution::Type type) {
BrowserDistribution* dist = NULL;
switch (type) {
case CHROME_BROWSER:
#if defined(GOOGLE_CHROME_BUILD)
if (InstallUtil::IsChromeSxSProcess()) {
dist = GetOrCreateBrowserDistribution<GoogleChromeSxSDistribution>(
&g_browser_distribution);
} else {
dist = GetOrCreateBrowserDistribution<GoogleChromeDistribution>(
&g_browser_distribution);
}
#else
dist = GetOrCreateBrowserDistribution<BrowserDistribution>(
&g_browser_distribution);
#endif
break;
case CHROME_FRAME:
dist = GetOrCreateBrowserDistribution<ChromeFrameDistribution>(
&g_chrome_frame_distribution);
break;
default:
DCHECK_EQ(CHROME_BINARIES, type);
#if defined(GOOGLE_CHROME_BUILD)
dist = GetOrCreateBrowserDistribution<GoogleChromeBinariesDistribution>(
&g_binaries_distribution);
#else
dist = GetOrCreateBrowserDistribution<ChromiumBinariesDistribution>(
&g_binaries_distribution);
#endif
}
return dist;
}
void BrowserDistribution::DoPostUninstallOperations(
const Version& version, const FilePath& local_data_path,
const std::wstring& distribution_data) {
}
std::wstring BrowserDistribution::GetAppGuid() {
return L"";
}
std::wstring BrowserDistribution::GetApplicationName() {
return L"Chromium";
}
std::wstring BrowserDistribution::GetAppShortCutName() {
return GetApplicationName();
}
std::wstring BrowserDistribution::GetAlternateApplicationName() {
return L"The Internet";
}
std::wstring BrowserDistribution::GetBrowserAppId() {
return L"Chromium";
}
std::wstring BrowserDistribution::GetInstallSubDir() {
return L"Chromium";
}
std::wstring BrowserDistribution::GetPublisherName() {
return L"Chromium";
}
std::wstring BrowserDistribution::GetAppDescription() {
return L"Browse the web";
}
std::wstring BrowserDistribution::GetLongAppDescription() {
const std::wstring& app_description =
installer::GetLocalizedString(IDS_PRODUCT_DESCRIPTION_BASE);
return app_description;
}
std::string BrowserDistribution::GetSafeBrowsingName() {
return "chromium";
}
std::wstring BrowserDistribution::GetStateKey() {
return L"Software\\Chromium";
}
std::wstring BrowserDistribution::GetStateMediumKey() {
return L"Software\\Chromium";
}
std::wstring BrowserDistribution::GetStatsServerURL() {
return L"";
}
std::string BrowserDistribution::GetNetworkStatsServer() const {
return "";
}
std::string BrowserDistribution::GetHttpPipeliningTestServer() const {
return "";
}
std::wstring BrowserDistribution::GetDistributionData(HKEY root_key) {
return L"";
}
std::wstring BrowserDistribution::GetUninstallLinkName() {
return L"Uninstall Chromium";
}
std::wstring BrowserDistribution::GetUninstallRegPath() {
return L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Chromium";
}
std::wstring BrowserDistribution::GetVersionKey() {
return L"Software\\Chromium";
}
bool BrowserDistribution::CanSetAsDefault() {
return true;
}
bool BrowserDistribution::CanCreateDesktopShortcuts() {
return true;
}
int BrowserDistribution::GetIconIndex() {
return 0;
}
bool BrowserDistribution::GetChromeChannel(std::wstring* channel) {
return false;
}
bool BrowserDistribution::GetDelegateExecuteHandlerData(
string16* handler_class_uuid,
string16* type_lib_uuid,
string16* type_lib_version,
string16* interface_uuid) {
// TODO(grt): http://crbug.com/123727 Return values for Chromium.
return false;
}
void BrowserDistribution::UpdateInstallStatus(bool system_install,
installer::ArchiveType archive_type,
installer::InstallStatus install_status) {
}
bool BrowserDistribution::GetExperimentDetails(
UserExperiment* experiment, int flavor) {
return false;
}
void BrowserDistribution::LaunchUserExperiment(
const FilePath& setup_path, installer::InstallStatus status,
const Version& version, const installer::Product& product,
bool system_level) {
}
void BrowserDistribution::InactiveUserToastExperiment(int flavor,
const std::wstring& experiment_group,
const installer::Product& installation,
const FilePath& application_path) {
}
<|endoftext|> |
<commit_before>//
// Robit.cpp
// RoboNeko
//
// Created by nsp on 16/3/17.
// Copyright © 2017 nspool. All rights reserved.
//
#include "Robit.hpp"
Robit::Robit(SDL_Renderer* renderer, SDL_Point p)
{
_p = p;
_renderer = renderer;
// Load the robit
SDL_Surface* gRobits = IMG_Load( "robits.png" );
if(gRobits == 0)
{
printf("Failed to load images! SDL_Error: %s\n", SDL_GetError());
}
// Setup Robit animation
_spriteClips[0].x = 0;
_spriteClips[0].y = 0;
_spriteClips[0].w = 21;
_spriteClips[0].h = 31;
_spriteClips[1].x = 21;
_spriteClips[1].y = 0;
_spriteClips[1].w = 21;
_spriteClips[1].h = 31;
_spriteClips[2].x = 42;
_spriteClips[2].y = 0;
_spriteClips[2].w = 21;
_spriteClips[2].h = 31;
_texture = SDL_CreateTextureFromSurface( renderer, gRobits );
}
void Robit::stop()
{
SDL_Rect robitLoc = { _p.x, _p.y, 21, 31 };
SDL_RenderCopy( _renderer, _texture, &_spriteClips[1], &robitLoc );
}
void Robit::doCollision()
{
// "revert" to the previous uncollided position
_p = _prev;
_isCollided = true;
}
void Robit::action(SDL_Point* target, std::vector<SDL_Rect>* obsticles)
{
if(_isCollided == true) {
_isCollided = false;
return;
}
bool willCollide = false;
SDL_Rect P1 = { _p.x, _p.y };
SDL_Rect P2 = { _p.x + 21, _p.y + 31 };
SDL_Rect P3 = { _p.x, _p.y + 31 };
SDL_Rect P4 = { _p.x + 21, _p.y };
for(SDL_Rect o: *obsticles) {
if(o.x == _p.x && o.y == _p.y) { continue; }
// Only avoid when close to the obsticle
if(sqrt(pow(_p.x - o.x, 2) + pow(_p.y - o.y, 2)) > 100) { continue; }
// Modify the angle randomly to attempt to avoid collision.
if(SDL_IntersectRectAndLine(&o, &P1.x, &P1.y, &target->x, &target->y) ||
SDL_IntersectRectAndLine(&o, &P2.x, &P2.y, &target->x, &target->y) ||
SDL_IntersectRectAndLine(&o, &P3.x, &P3.y, &target->x, &target->y) ||
SDL_IntersectRectAndLine(&o, &P4.x, &P4.y, &target->x, &target->y)){
willCollide = true;
break;
}
}
// Save the current position if the update position enters a collision sate
_prev = _p;
// Interpolate the line between the current position and the target
SDL_Rect center = {_p.x + 10, _p.y + 15};
double rad = atan2((target->y - center.y), (target->x - center.x));
// TODO: Use obsticle obtains above to determine a path around
if(willCollide) {
rad += (arc4random_uniform(1) > 1) ? -1.5 : 1.5;
}
// Set the new coordinates
_xDelta += cos(rad);
_yDelta += sin(rad);
if(_xDelta > 1 || _xDelta < -1){
_p.x += (int)_xDelta;
_xDelta = 0;
}
if(_yDelta > 1 || _yDelta < -1){
_p.y += (int)_yDelta;
_yDelta = 0;
}
}
SDL_Rect Robit::getBounds()
{
return { _p.x, _p.y, 21, 31 };
}
void Robit::render()
{
// Animate at some fixed framerate
constexpr int animationRate = 12;
constexpr int animationLen = 3;
int frameToDraw = ((SDL_GetTicks() - _startTime) * animationRate / 1000) % animationLen;
SDL_Rect bounds = getBounds();
SDL_RenderCopy( _renderer, _texture, &_spriteClips[frameToDraw], &bounds );
}
<commit_msg>Put a buffer around the sprite to try and avoid it getting stuck<commit_after>//
// Robit.cpp
// RoboNeko
//
// Created by nsp on 16/3/17.
// Copyright © 2017 nspool. All rights reserved.
//
#include "Robit.hpp"
Robit::Robit(SDL_Renderer* renderer, SDL_Point p)
{
_p = p;
_renderer = renderer;
// Load the robit
SDL_Surface* gRobits = IMG_Load( "robits.png" );
if(gRobits == 0)
{
printf("Failed to load images! SDL_Error: %s\n", SDL_GetError());
}
// Setup Robit animation
_spriteClips[0].x = 0;
_spriteClips[0].y = 0;
_spriteClips[0].w = 21;
_spriteClips[0].h = 31;
_spriteClips[1].x = 21;
_spriteClips[1].y = 0;
_spriteClips[1].w = 21;
_spriteClips[1].h = 31;
_spriteClips[2].x = 42;
_spriteClips[2].y = 0;
_spriteClips[2].w = 21;
_spriteClips[2].h = 31;
_texture = SDL_CreateTextureFromSurface( renderer, gRobits );
}
void Robit::stop()
{
SDL_Rect robitLoc = { _p.x, _p.y, 21, 31 };
SDL_RenderCopy( _renderer, _texture, &_spriteClips[1], &robitLoc );
}
void Robit::doCollision()
{
// "revert" to the previous uncollided position
_p = _prev;
_isCollided = true;
}
void Robit::action(SDL_Point* target, std::vector<SDL_Rect>* obsticles)
{
if(_isCollided == true) {
_isCollided = false;
return;
}
bool willCollide = false;
int buf = 5;
SDL_Rect P1 = { _p.x - buf, _p.y - buf};
SDL_Rect P2 = { _p.x + buf + 21, _p.y + buf + 31 };
SDL_Rect P3 = { _p.x - buf, _p.y + buf + 31 };
SDL_Rect P4 = { _p.x + buf + 21, _p.y + buf };
for(SDL_Rect o: *obsticles) {
if(o.x == _p.x && o.y == _p.y) { continue; }
// Only avoid when close to the obsticle
if(sqrt(pow(_p.x - o.x, 2) + pow(_p.y - o.y, 2)) > 100) { continue; }
// Modify the angle randomly to attempt to avoid collision.
if(SDL_IntersectRectAndLine(&o, &P1.x, &P1.y, &target->x, &target->y) ||
SDL_IntersectRectAndLine(&o, &P2.x, &P2.y, &target->x, &target->y) ||
SDL_IntersectRectAndLine(&o, &P3.x, &P3.y, &target->x, &target->y) ||
SDL_IntersectRectAndLine(&o, &P4.x, &P4.y, &target->x, &target->y)){
willCollide = true;
break;
}
}
// Save the current position if the update position enters a collision sate
_prev = _p;
// Interpolate the line between the current position and the target
SDL_Rect center = {_p.x + 10, _p.y + 15};
double rad = atan2((target->y - center.y), (target->x - center.x));
// TODO: Use obsticle obtains above to determine a path around
if(willCollide) {
rad += (arc4random_uniform(1) > 1) ? -1.5 : 1.5;
}
// Set the new coordinates
_xDelta += cos(rad);
_yDelta += sin(rad);
if(_xDelta > 1 || _xDelta < -1){
_p.x += (int)_xDelta;
_xDelta = 0;
}
if(_yDelta > 1 || _yDelta < -1){
_p.y += (int)_yDelta;
_yDelta = 0;
}
}
SDL_Rect Robit::getBounds()
{
return { _p.x, _p.y, 21, 31 };
}
void Robit::render()
{
// Animate at some fixed framerate
constexpr int animationRate = 12;
constexpr int animationLen = 3;
int frameToDraw = ((SDL_GetTicks() - _startTime) * animationRate / 1000) % animationLen;
SDL_Rect bounds = getBounds();
SDL_RenderCopy( _renderer, _texture, &_spriteClips[frameToDraw], &bounds );
}
<|endoftext|> |
<commit_before>/// @file h5_pool_serialize.cpp
/// @brief h5_pool serialization implementation
/// @author uentity
/// @version
/// @date 24.01.2012
/// @copyright This source code is released under the terms of
/// the BSD License. See LICENSE for more details.
//#include "bs_bos_core_data_storage_stdafx.h"
#include "h5_pool_serialize.h"
#include <boost/serialization/array.hpp>
using namespace blue_sky;
namespace boser = boost::serialization;
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(save, h5_pool)
bool is_open = (t.file_id != 0);
ar << is_open;
ar << t.fname;
ar << t.path;
ar << boser::make_array(&t.pool_dims, 3);
ar << t.n_pool_dims;
// save flag if h5 is open
// flush buffers
const_cast< h5_pool& >(t).flush();
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(load, h5_pool)
bool do_open;
ar >> do_open;
ar >> t.fname;
ar >> t.path;
if(do_open)
t.open_file(t.fname, t.path);
ar >> boser::make_array(&t.pool_dims, 3);
ar >> t.n_pool_dims;
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(serialize, h5_pool)
// register conversion to base interface
boser::bs_void_cast_register< h5_pool, h5_pool_iface >(
static_cast< h5_pool* >(NULL),
static_cast< h5_pool_iface* >(NULL)
);
boser::split_free(ar, t, version);
BLUE_SKY_CLASS_SRZ_FCN_END
BOOST_SERIALIZATION_ASSUME_ABSTRACT(h5_pool_iface)
BLUE_SKY_TYPE_SERIALIZE_IMPL(h5_pool)
<commit_msg>SRZ: fix openning h5 pool when deserializing<commit_after>/// @file h5_pool_serialize.cpp
/// @brief h5_pool serialization implementation
/// @author uentity
/// @version
/// @date 24.01.2012
/// @copyright This source code is released under the terms of
/// the BSD License. See LICENSE for more details.
//#include "bs_bos_core_data_storage_stdafx.h"
#include "h5_pool_serialize.h"
#include <boost/serialization/array.hpp>
using namespace blue_sky;
namespace boser = boost::serialization;
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(save, h5_pool)
bool is_open = (t.file_id != 0);
ar << is_open;
ar << t.fname;
ar << t.path;
ar << boser::make_array(&t.pool_dims, 3);
ar << t.n_pool_dims;
// save flag if h5 is open
// flush buffers
const_cast< h5_pool& >(t).flush();
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(load, h5_pool)
bool do_open;
ar >> do_open;
ar >> t.fname;
ar >> t.path;
if(do_open) {
t.file_id = H5Fopen(t.fname.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
if(t.file_id < 0) // try to create file
t.open_file(t.fname.c_str(), t.path.c_str());
else {
// try to open group
t.group_id = H5Gopen(t.file_id, t.path.c_str());
if(t.group_id < 0) {
// try to create group
t.group_id = H5Gcreate(t.file_id, t.path.c_str (), -1);
if(t.group_id < 0)
bs_throw_exception(
boost::format ("h5_pool_serialize: Can't create group: %s") % t.path
);
}
// init
t.fill_map();
}
}
ar >> boser::make_array(&t.pool_dims, 3);
ar >> t.n_pool_dims;
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(serialize, h5_pool)
// register conversion to base interface
boser::bs_void_cast_register< h5_pool, h5_pool_iface >(
static_cast< h5_pool* >(NULL),
static_cast< h5_pool_iface* >(NULL)
);
boser::split_free(ar, t, version);
BLUE_SKY_CLASS_SRZ_FCN_END
BOOST_SERIALIZATION_ASSUME_ABSTRACT(h5_pool_iface)
BLUE_SKY_TYPE_SERIALIZE_IMPL(h5_pool)
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) 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.
*
* $Id$
*
*/
#include <sensor_msgs/PointCloud2.h>
#include <pcl/io/pcd_io.h>
#include <pcl/features/normal_3d.h>
#include <pcl/features/integral_image_normal.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
using namespace std;
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
int default_k = 0;
double default_radius = 0.0;
void
printHelp (int, char **argv)
{
print_error ("Syntax is: %s input.pcd output.pcd <options> [optional_arguments]\n", argv[0]);
print_info (" where options are:\n");
print_info (" -radius X = use a radius of Xm around each point to determine the neighborhood (default: ");
print_value ("%f", default_radius); print_info (")\n");
print_info (" -k X = use a fixed number of X-nearest neighbors around each point (default: ");
print_value ("%f", default_k); print_info (")\n");
print_info (" For organized datasets, an IntegralImageNormalEstimation approach will be used, with the RADIUS given value as SMOOTHING SIZE.\n");
print_info ("\nOptional arguments are:\n");
print_info (" -input_dir X = batch process all PCD files found in input_dir\n");
print_info (" -output_dir X = save the processed files from input_dir in this directory\n");
}
bool
loadCloud (const string &filename, sensor_msgs::PointCloud2 &cloud,
Eigen::Vector4f &translation, Eigen::Quaternionf &orientation)
{
if (loadPCDFile (filename, cloud, translation, orientation) < 0)
return (false);
return (true);
}
void
compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,
int k, double radius)
{
// Convert data to PointCloud<T>
PointCloud<PointXYZ>::Ptr xyz (new PointCloud<PointXYZ>);
fromROSMsg (*input, *xyz);
TicToc tt;
tt.tic ();
PointCloud<Normal> normals;
// Try our luck with organized integral image based normal estimation
if (xyz->isOrganized ())
{
IntegralImageNormalEstimation<PointXYZ, Normal> ne;
ne.setInputCloud (xyz);
ne.setNormalEstimationMethod (IntegralImageNormalEstimation<PointXYZ, Normal>::COVARIANCE_MATRIX);
ne.setNormalSmoothingSize (float (radius));
ne.setDepthDependentSmoothing (true);
ne.compute (normals);
}
else
{
NormalEstimation<PointXYZ, Normal> ne;
ne.setInputCloud (xyz);
ne.setSearchMethod (search::KdTree<PointXYZ>::Ptr (new search::KdTree<PointXYZ>));
ne.setKSearch (k);
ne.setRadiusSearch (radius);
ne.compute (normals);
}
print_highlight ("Computed normals in "); print_value ("%g", tt.toc ()); print_info (" ms for "); print_value ("%d", normals.width * normals.height); print_info (" points.\n");
// Convert data back
sensor_msgs::PointCloud2 output_normals;
toROSMsg (normals, output_normals);
concatenateFields (output_normals, *input, output);
}
void
saveCloud (const string &filename, const sensor_msgs::PointCloud2 &output,
const Eigen::Vector4f &translation, const Eigen::Quaternionf &orientation)
{
PCDWriter w;
w.writeBinaryCompressed (filename, output, translation, orientation);
}
int
batchProcess (const vector<string> &pcd_files, string &output_dir, int k, double radius)
{
vector<string> st;
#if _OPENMP
#pragma omp parallel for
#endif
for (size_t i = 0; i < pcd_files.size (); ++i)
{
// Load the first file
Eigen::Vector4f translation;
Eigen::Quaternionf rotation;
sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
if (!loadCloud (pcd_files[i], *cloud, translation, rotation))
continue;
// Perform the feature estimation
sensor_msgs::PointCloud2 output;
compute (cloud, output, k, radius);
// Prepare output file name
string filename = pcd_files[i];
boost::trim (filename);
boost::split (st, filename, boost::is_any_of ("/\\"), boost::token_compress_on);
// Save into the second file
stringstream ss;
ss << output_dir << "/" << st.at (st.size () - 1);
saveCloud (ss.str (), output, translation, rotation);
}
return (0);
}
/* ---[ */
int
main (int argc, char** argv)
{
print_info ("Estimate surface normals using NormalEstimation. For more information, use: %s -h\n", argv[0]);
if (argc < 3)
{
printHelp (argc, argv);
return (-1);
}
bool batch_mode = false;
// Command line parsing
int k = default_k;
double radius = default_radius;
parse_argument (argc, argv, "-k", k);
parse_argument (argc, argv, "-radius", radius);
string input_dir, output_dir;
if (parse_argument (argc, argv, "-input_dir", input_dir) != -1)
{
PCL_INFO ("Input directory given as %s. Batch process mode on.\n", input_dir.c_str ());
if (parse_argument (argc, argv, "-output_dir", output_dir) == -1)
{
PCL_ERROR ("Need an output directory! Please use -output_dir to continue.\n");
return (-1);
}
// Both input dir and output dir given, switch into batch processing mode
batch_mode = true;
}
if (!batch_mode)
{
// Parse the command line arguments for .pcd files
vector<int> p_file_indices;
p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
if (p_file_indices.size () != 2)
{
print_error ("Need one input PCD file and one output PCD file to continue.\n");
return (-1);
}
print_info ("Estimating normals with a radius/k/smoothing size of: ");
print_value ("%d / %f / %f\n", k, radius, radius);
// Load the first file
Eigen::Vector4f translation;
Eigen::Quaternionf rotation;
sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
if (!loadCloud (argv[p_file_indices[0]], *cloud, translation, rotation))
return (-1);
// Perform the feature estimation
sensor_msgs::PointCloud2 output;
compute (cloud, output, k, radius);
// Save into the second file
saveCloud (argv[p_file_indices[1]], output, translation, rotation);
}
else
{
if (input_dir != "" && boost::filesystem::exists (input_dir))
{
vector<string> pcd_files;
boost::filesystem::directory_iterator end_itr;
for (boost::filesystem::directory_iterator itr (input_dir); itr != end_itr; ++itr)
{
// Only add PCD files
if (!is_directory (itr->status ()) && boost::algorithm::to_upper_copy (boost::filesystem::extension (itr->path ())) == ".PCD" )
{
pcd_files.push_back (itr->path ().string ());
PCL_INFO ("[Batch processing mode] Added %s for processing.\n", itr->path ().string ().c_str ());
}
}
batchProcess (pcd_files, output_dir, k, radius);
}
else
{
PCL_ERROR ("Batch processing mode enabled, but invalid input directory (%s) given!\n", input_dir.c_str ());
return (-1);
}
}
}
<commit_msg>small error fix<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) 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.
*
* $Id$
*
*/
#include <sensor_msgs/PointCloud2.h>
#include <pcl/io/pcd_io.h>
#include <pcl/features/normal_3d.h>
#include <pcl/features/integral_image_normal.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
using namespace std;
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
int default_k = 0;
double default_radius = 0.0;
void
printHelp (int, char **argv)
{
print_error ("Syntax is: %s input.pcd output.pcd <options> [optional_arguments]\n", argv[0]);
print_info (" where options are:\n");
print_info (" -radius X = use a radius of Xm around each point to determine the neighborhood (default: ");
print_value ("%f", default_radius); print_info (")\n");
print_info (" -k X = use a fixed number of X-nearest neighbors around each point (default: ");
print_value ("%f", default_k); print_info (")\n");
print_info (" For organized datasets, an IntegralImageNormalEstimation approach will be used, with the RADIUS given value as SMOOTHING SIZE.\n");
print_info ("\nOptional arguments are:\n");
print_info (" -input_dir X = batch process all PCD files found in input_dir\n");
print_info (" -output_dir X = save the processed files from input_dir in this directory\n");
}
bool
loadCloud (const string &filename, sensor_msgs::PointCloud2 &cloud,
Eigen::Vector4f &translation, Eigen::Quaternionf &orientation)
{
if (loadPCDFile (filename, cloud, translation, orientation) < 0)
return (false);
return (true);
}
void
compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,
int k, double radius)
{
// Convert data to PointCloud<T>
PointCloud<PointXYZ>::Ptr xyz (new PointCloud<PointXYZ>);
fromROSMsg (*input, *xyz);
TicToc tt;
tt.tic ();
PointCloud<Normal> normals;
// Try our luck with organized integral image based normal estimation
if (xyz->isOrganized ())
{
IntegralImageNormalEstimation<PointXYZ, Normal> ne;
ne.setInputCloud (xyz);
ne.setNormalEstimationMethod (IntegralImageNormalEstimation<PointXYZ, Normal>::COVARIANCE_MATRIX);
ne.setNormalSmoothingSize (float (radius));
ne.setDepthDependentSmoothing (true);
ne.compute (normals);
}
else
{
NormalEstimation<PointXYZ, Normal> ne;
ne.setInputCloud (xyz);
ne.setSearchMethod (search::KdTree<PointXYZ>::Ptr (new search::KdTree<PointXYZ>));
ne.setKSearch (k);
ne.setRadiusSearch (radius);
ne.compute (normals);
}
print_highlight ("Computed normals in "); print_value ("%g", tt.toc ()); print_info (" ms for "); print_value ("%d", normals.width * normals.height); print_info (" points.\n");
// Convert data back
sensor_msgs::PointCloud2 output_normals;
toROSMsg (normals, output_normals);
concatenateFields (output_normals, *input, output);
}
void
saveCloud (const string &filename, const sensor_msgs::PointCloud2 &output,
const Eigen::Vector4f &translation, const Eigen::Quaternionf &orientation)
{
PCDWriter w;
w.writeBinaryCompressed (filename, output, translation, orientation);
}
int
batchProcess (const vector<string> &pcd_files, string &output_dir, int k, double radius)
{
#if _OPENMP
#pragma omp parallel for
#endif
for (size_t i = 0; i < pcd_files.size (); ++i)
{
// Load the first file
Eigen::Vector4f translation;
Eigen::Quaternionf rotation;
sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
if (!loadCloud (pcd_files[i], *cloud, translation, rotation))
continue;
// Perform the feature estimation
sensor_msgs::PointCloud2 output;
compute (cloud, output, k, radius);
// Prepare output file name
string filename = pcd_files[i];
boost::trim (filename);
vector<string> st;
boost::split (st, filename, boost::is_any_of ("/\\"), boost::token_compress_on);
// Save into the second file
stringstream ss;
ss << output_dir << "/" << st.at (st.size () - 1);
saveCloud (ss.str (), output, translation, rotation);
}
return (0);
}
/* ---[ */
int
main (int argc, char** argv)
{
print_info ("Estimate surface normals using NormalEstimation. For more information, use: %s -h\n", argv[0]);
if (argc < 3)
{
printHelp (argc, argv);
return (-1);
}
bool batch_mode = false;
// Command line parsing
int k = default_k;
double radius = default_radius;
parse_argument (argc, argv, "-k", k);
parse_argument (argc, argv, "-radius", radius);
string input_dir, output_dir;
if (parse_argument (argc, argv, "-input_dir", input_dir) != -1)
{
PCL_INFO ("Input directory given as %s. Batch process mode on.\n", input_dir.c_str ());
if (parse_argument (argc, argv, "-output_dir", output_dir) == -1)
{
PCL_ERROR ("Need an output directory! Please use -output_dir to continue.\n");
return (-1);
}
// Both input dir and output dir given, switch into batch processing mode
batch_mode = true;
}
if (!batch_mode)
{
// Parse the command line arguments for .pcd files
vector<int> p_file_indices;
p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
if (p_file_indices.size () != 2)
{
print_error ("Need one input PCD file and one output PCD file to continue.\n");
return (-1);
}
print_info ("Estimating normals with a radius/k/smoothing size of: ");
print_value ("%d / %f / %f\n", k, radius, radius);
// Load the first file
Eigen::Vector4f translation;
Eigen::Quaternionf rotation;
sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
if (!loadCloud (argv[p_file_indices[0]], *cloud, translation, rotation))
return (-1);
// Perform the feature estimation
sensor_msgs::PointCloud2 output;
compute (cloud, output, k, radius);
// Save into the second file
saveCloud (argv[p_file_indices[1]], output, translation, rotation);
}
else
{
if (input_dir != "" && boost::filesystem::exists (input_dir))
{
vector<string> pcd_files;
boost::filesystem::directory_iterator end_itr;
for (boost::filesystem::directory_iterator itr (input_dir); itr != end_itr; ++itr)
{
// Only add PCD files
if (!is_directory (itr->status ()) && boost::algorithm::to_upper_copy (boost::filesystem::extension (itr->path ())) == ".PCD" )
{
pcd_files.push_back (itr->path ().string ());
PCL_INFO ("[Batch processing mode] Added %s for processing.\n", itr->path ().string ().c_str ());
}
}
batchProcess (pcd_files, output_dir, k, radius);
}
else
{
PCL_ERROR ("Batch processing mode enabled, but invalid input directory (%s) given!\n", input_dir.c_str ());
return (-1);
}
}
}
<|endoftext|> |
<commit_before>/*
EMCAL DA for online calibration: for LED studies
Contact: silvermy@ornl.gov
Run Type: PHYSICS or STANDALONE
DA Type: MON
Number of events needed: continously accumulating for all runs, rate ~0.1-1 Hz
Input Files: argument list
Output Files: RESULT_FILE=EMCALLED.root, to be exported to the DAQ FXS
fileId: FILE_ID=EMCALLED
Trigger types used: CALIBRATION_EVENT
*/
/*
This process reads RAW data from the files provided as command line arguments
and save results (class itself) in a file (named from RESULT_FILE define -
see below).
*/
#define RESULT_FILE "EMCALLED.root"
#define FILE_ID "signal"
#define AliDebugLevel() -1
#define FILE_SIGClassName "emcCalibSignal"
const int kNRCU = 4;
/* LOCAL_DEBUG is used to bypass daq* calls that do not work locally */
//#define LOCAL_DEBUG 1 // comment out to run normally
extern "C" {
#include <daqDA.h>
}
#include "event.h" /* in $DATE_COMMON_DEFS/; includes definition of event types */
#include "monitor.h" /* in $DATE_MONITOR_DIR/; monitor* interfaces */
#include "stdio.h"
#include "stdlib.h"
// ROOT includes
#include <TFile.h>
#include <TROOT.h>
#include <TPluginManager.h>
#include <TSystem.h>
//
//AliRoot includes
//
#include "AliRawReader.h"
#include "AliRawReaderDate.h"
#include "AliRawEventHeaderBase.h"
#include "AliCaloRawStreamV3.h"
#include "AliCaloAltroMapping.h"
#include "AliLog.h"
#include "AliDAQ.h"
//
// EMC calibration-helper algorithm includes
//
#include "AliCaloCalibSignal.h"
/*
Main routine, EMC signal detector algorithm
Arguments: list of DATE raw data files
*/
int main(int argc, char **argv) { // Main routine, EMC signal detector algorithm
AliLog::SetClassDebugLevel("AliCaloRawStreamV3",-5);
AliLog::SetClassDebugLevel("AliRawReaderDate",-5);
AliLog::SetModuleDebugLevel("RAW",-5);
if (argc<2) {
printf("Wrong number of arguments\n");
return -1;
}
/* magic line - for TStreamerInfo */
gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
"*",
"TStreamerInfo",
"RIO",
"TStreamerInfo()");
int i, status;
/* log start of process */
printf("EMCAL DA started - %s\n",__FILE__);
Int_t emcID = AliDAQ::DetectorID("EMCAL"); // bit 18..
/* declare monitoring program */
status=monitorDeclareMp( __FILE__ );
if (status!=0) {
printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* define wait event timeout - 1s max */
monitorSetNowait();
monitorSetNoWaitNetworkTimeout(1000);
/* Retrieve mapping files from DAQ DB */
const char* mapFiles[kNRCU] = {"RCU0A.data","RCU1A.data","RCU0C.data","RCU1C.data"};
for(Int_t iFile=0; iFile<kNRCU; iFile++) {
int failed = daqDA_DB_getFile(mapFiles[iFile], mapFiles[iFile]);
if(failed) {
printf("Cannot retrieve file %d : %s from DAQ DB. Exit now..\n",
iFile, mapFiles[iFile]);
#ifdef LOCAL_DEBUG
#else
return -1;
#endif
}
}
/* Open mapping files */
AliCaloAltroMapping *mapping[kNRCU];
TString path = "./";
path += "RCU";
TString path2;
TString side[] = {"A","C"};//+ and - pseudorapidity supermodules
for(Int_t j = 0; j < 2; j++){
for(Int_t i = 0; i < 2; i++) {
path2 = path;
path2 += i;
path2 += side[j];
path2 += ".data";
mapping[j*2 + i] = new AliCaloAltroMapping(path2.Data());
}
}
/* Retrieve cut=parameter file from DAQ DB */
const char* parameterFile = {"EMCALLEDda.dat"};
int failed = daqDA_DB_getFile(parameterFile, parameterFile);
if (failed) {
printf("Cannot retrieve file : %s from DAQ DB. Exit now..\n",
parameterFile);
#ifdef LOCAL_DEBUG
#else
return -1;
#endif
}
/* set up our analysis classes */
AliCaloCalibSignal * calibSignal = new AliCaloCalibSignal(AliCaloCalibSignal::kEmCal);
calibSignal->SetAltroMapping( mapping );
calibSignal->SetParametersFromFile( parameterFile );
AliRawReader *rawReader = NULL;
int nevents=0;
/* loop over RAW data files */
for ( i=1; i<argc; i++ ) {
/* define data source : this is argument i */
printf("Processing file %s\n", argv[i]);
status=monitorSetDataSource( argv[i] );
if (status!=0) {
printf("monitorSetDataSource() failed. Error=%s. Exiting ...\n", monitorDecodeError(status));
return -1;
}
/* read until EOF */
struct eventHeaderStruct *event;
eventTypeType eventT;
for ( ; ; ) { // infinite loop
/* check shutdown condition */
if (daqDA_checkShutdown()) {break;}
/* get next event (blocking call until timeout) */
status=monitorGetEventDynamic((void **)&event);
if (status==MON_ERR_EOF) {
printf ("End of File %d (%s) detected\n", i, argv[i]);
break; /* end of monitoring file has been reached */
}
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
break;
}
/* retry if got no event */
if (event==NULL) {
continue;
}
eventT = event->eventType; /* just convenient shorthand */
/* only look at calibration events */
if ( eventT != calibrationEvent ) {
free(event);
continue;
}
/* only look at events where EMCAL was included */
if (! TEST_DETECTOR_IN_PATTERN(event->eventDetectorPattern, emcID) ) {
free(event);
continue;
}
nevents++; // count how many acceptable events we have
// Signal calibration
rawReader = new AliRawReaderDate((void*)event);
calibSignal->SetRunNumber(event->eventRunNb);
calibSignal->ProcessEvent(rawReader);
delete rawReader;
/* free resources */
free(event);
} //until EOF
} // loop over files
// calculate average values also, for the LED info
calibSignal->SetUseAverage(kTRUE);
calibSignal->Analyze();
// by default, we only save the full info in debug mode
#ifdef LOCAL_DEBUG
#else
// reset the full trees, when we are not in debug mode
calibSignal->GetTreeAmpVsTime()->Reset();
calibSignal->GetTreeLEDAmpVsTime()->Reset();
#endif
//
// write class to rootfile
//
printf ("%d calibration events processed.\n",nevents);
TFile f(RESULT_FILE, "recreate");
if (!f.IsZombie()) {
f.cd();
calibSignal->Write(FILE_SIGClassName);
f.Close();
printf("Objects saved to file \"%s\" as \"%s\".\n",
RESULT_FILE, FILE_SIGClassName);
}
else {
printf("Could not save the object to file \"%s\".\n",
RESULT_FILE);
}
//
// closing down; see if we can delete our analysis helper(s) also
//
delete calibSignal;
for(Int_t iFile=0; iFile<kNRCU; iFile++) {
if (mapping[iFile]) delete mapping[iFile];
}
/* store the result file on FES */
#ifdef LOCAL_DEBUG
#else
status = daqDA_FES_storeFile(RESULT_FILE, FILE_ID);
status = daqDA_DB_storeFile(RESULT_FILE, RESULT_FILE); // also to DAQ DB
#endif
return status;
}
<commit_msg>adding TMinuit to plugin manager for LED DA - thanks Sylvain<commit_after>/*
EMCAL DA for online calibration: for LED studies
Contact: silvermy@ornl.gov
Run Type: PHYSICS or STANDALONE
DA Type: MON
Number of events needed: continously accumulating for all runs, rate ~0.1-1 Hz
Input Files: argument list
Output Files: RESULT_FILE=EMCALLED.root, to be exported to the DAQ FXS
fileId: FILE_ID=EMCALLED
Trigger types used: CALIBRATION_EVENT
*/
/*
This process reads RAW data from the files provided as command line arguments
and save results (class itself) in a file (named from RESULT_FILE define -
see below).
*/
#define RESULT_FILE "EMCALLED.root"
#define FILE_ID "signal"
#define AliDebugLevel() -1
#define FILE_SIGClassName "emcCalibSignal"
const int kNRCU = 4;
/* LOCAL_DEBUG is used to bypass daq* calls that do not work locally */
//#define LOCAL_DEBUG 1 // comment out to run normally
extern "C" {
#include <daqDA.h>
}
#include "event.h" /* in $DATE_COMMON_DEFS/; includes definition of event types */
#include "monitor.h" /* in $DATE_MONITOR_DIR/; monitor* interfaces */
#include "stdio.h"
#include "stdlib.h"
// ROOT includes
#include <TFile.h>
#include <TROOT.h>
#include <TPluginManager.h>
#include <TSystem.h>
//
//AliRoot includes
//
#include "AliRawReader.h"
#include "AliRawReaderDate.h"
#include "AliRawEventHeaderBase.h"
#include "AliCaloRawStreamV3.h"
#include "AliCaloAltroMapping.h"
#include "AliLog.h"
#include "AliDAQ.h"
//
// EMC calibration-helper algorithm includes
//
#include "AliCaloCalibSignal.h"
/*
Main routine, EMC signal detector algorithm
Arguments: list of DATE raw data files
*/
int main(int argc, char **argv) { // Main routine, EMC signal detector algorithm
AliLog::SetClassDebugLevel("AliCaloRawStreamV3",-5);
AliLog::SetClassDebugLevel("AliRawReaderDate",-5);
AliLog::SetModuleDebugLevel("RAW",-5);
if (argc<2) {
printf("Wrong number of arguments\n");
return -1;
}
/* magic line - for TStreamerInfo */
gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
"*",
"TStreamerInfo",
"RIO",
"TStreamerInfo()");
/* another magic line - for TMinuit */
gROOT->GetPluginManager()->AddHandler("ROOT::Math::Minimizer",
"Minuit",
"TMinuitMinimizer",
"Minuit",
"TMinuitMinimizer(const char*)");
int i, status;
/* log start of process */
printf("EMCAL DA started - %s\n",__FILE__);
Int_t emcID = AliDAQ::DetectorID("EMCAL"); // bit 18..
/* declare monitoring program */
status=monitorDeclareMp( __FILE__ );
if (status!=0) {
printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* define wait event timeout - 1s max */
monitorSetNowait();
monitorSetNoWaitNetworkTimeout(1000);
/* Retrieve mapping files from DAQ DB */
const char* mapFiles[kNRCU] = {"RCU0A.data","RCU1A.data","RCU0C.data","RCU1C.data"};
for(Int_t iFile=0; iFile<kNRCU; iFile++) {
int failed = daqDA_DB_getFile(mapFiles[iFile], mapFiles[iFile]);
if(failed) {
printf("Cannot retrieve file %d : %s from DAQ DB. Exit now..\n",
iFile, mapFiles[iFile]);
#ifdef LOCAL_DEBUG
#else
return -1;
#endif
}
}
/* Open mapping files */
AliCaloAltroMapping *mapping[kNRCU];
TString path = "./";
path += "RCU";
TString path2;
TString side[] = {"A","C"};//+ and - pseudorapidity supermodules
for(Int_t j = 0; j < 2; j++){
for(Int_t i = 0; i < 2; i++) {
path2 = path;
path2 += i;
path2 += side[j];
path2 += ".data";
mapping[j*2 + i] = new AliCaloAltroMapping(path2.Data());
}
}
/* Retrieve cut=parameter file from DAQ DB */
const char* parameterFile = {"EMCALLEDda.dat"};
int failed = daqDA_DB_getFile(parameterFile, parameterFile);
if (failed) {
printf("Cannot retrieve file : %s from DAQ DB. Exit now..\n",
parameterFile);
#ifdef LOCAL_DEBUG
#else
return -1;
#endif
}
/* set up our analysis classes */
AliCaloCalibSignal * calibSignal = new AliCaloCalibSignal(AliCaloCalibSignal::kEmCal);
calibSignal->SetAltroMapping( mapping );
calibSignal->SetParametersFromFile( parameterFile );
AliRawReader *rawReader = NULL;
int nevents=0;
/* loop over RAW data files */
for ( i=1; i<argc; i++ ) {
/* define data source : this is argument i */
printf("Processing file %s\n", argv[i]);
status=monitorSetDataSource( argv[i] );
if (status!=0) {
printf("monitorSetDataSource() failed. Error=%s. Exiting ...\n", monitorDecodeError(status));
return -1;
}
/* read until EOF */
struct eventHeaderStruct *event;
eventTypeType eventT;
for ( ; ; ) { // infinite loop
/* check shutdown condition */
if (daqDA_checkShutdown()) {break;}
/* get next event (blocking call until timeout) */
status=monitorGetEventDynamic((void **)&event);
if (status==MON_ERR_EOF) {
printf ("End of File %d (%s) detected\n", i, argv[i]);
break; /* end of monitoring file has been reached */
}
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
break;
}
/* retry if got no event */
if (event==NULL) {
continue;
}
eventT = event->eventType; /* just convenient shorthand */
/* only look at calibration events */
if ( eventT != calibrationEvent ) {
free(event);
continue;
}
/* only look at events where EMCAL was included */
if (! TEST_DETECTOR_IN_PATTERN(event->eventDetectorPattern, emcID) ) {
free(event);
continue;
}
nevents++; // count how many acceptable events we have
// Signal calibration
rawReader = new AliRawReaderDate((void*)event);
calibSignal->SetRunNumber(event->eventRunNb);
calibSignal->ProcessEvent(rawReader);
delete rawReader;
/* free resources */
free(event);
} //until EOF
} // loop over files
// calculate average values also, for the LED info
calibSignal->SetUseAverage(kTRUE);
calibSignal->Analyze();
// by default, we only save the full info in debug mode
#ifdef LOCAL_DEBUG
#else
// reset the full trees, when we are not in debug mode
calibSignal->GetTreeAmpVsTime()->Reset();
calibSignal->GetTreeLEDAmpVsTime()->Reset();
#endif
//
// write class to rootfile
//
printf ("%d calibration events processed.\n",nevents);
TFile f(RESULT_FILE, "recreate");
if (!f.IsZombie()) {
f.cd();
calibSignal->Write(FILE_SIGClassName);
f.Close();
printf("Objects saved to file \"%s\" as \"%s\".\n",
RESULT_FILE, FILE_SIGClassName);
}
else {
printf("Could not save the object to file \"%s\".\n",
RESULT_FILE);
}
//
// closing down; see if we can delete our analysis helper(s) also
//
delete calibSignal;
for(Int_t iFile=0; iFile<kNRCU; iFile++) {
if (mapping[iFile]) delete mapping[iFile];
}
/* store the result file on FES */
#ifdef LOCAL_DEBUG
#else
status = daqDA_FES_storeFile(RESULT_FILE, FILE_ID);
status = daqDA_DB_storeFile(RESULT_FILE, RESULT_FILE); // also to DAQ DB
#endif
return status;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2015 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#include <stdexcept>
#include <map>
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <istream>
#include <ostream>
#include <sstream>
#include <chrono>
#define CLIOPTS_ENABLE_CXX
#define INCLUDE_SUBDOC_NTOHLL
#include "subdoc/subdoc-api.h"
#include "subdoc/path.h"
#include "subdoc/match.h"
#include "subdoc/operations.h"
#include "contrib/cliopts/cliopts.h"
using std::string;
using std::vector;
using std::map;
using namespace cliopts;
using Subdoc::Path;
using Subdoc::Operation;
using Subdoc::Command;
using Subdoc::Error;
using Subdoc::Result;
struct OpEntry {
uint8_t opcode;
const char *description;
OpEntry(uint8_t opcode = 0, const char *description = NULL) :
opcode(opcode),
description(description) {}
operator uint8_t() const { return opcode; }
};
class Options {
public:
Options() :
o_iter('i', "iterations", 1000),
o_path('p', "docpath"),
o_value('v', "value"),
o_jsfile('f', "json"),
o_cmd('c', "command"),
o_mkdirp('M', "create-intermediate"),
parser("subdoc-bench")
{
o_iter.description("Number of iterations to run");
o_path.description("Document path to manipulate");
o_value.description("Document value to insert");
o_jsfile.description("JSON files to operate on. If passing multiple files, each file should be delimited by a comma");
o_cmd.description("Command to use. Use -c help to show all the commands").mandatory();
o_mkdirp.description("Create intermediate paths for mutation operations");
parser.addOption(o_iter);
parser.addOption(o_path);
parser.addOption(o_value);
parser.addOption(o_jsfile);
parser.addOption(o_cmd);
parser.addOption(o_mkdirp);
totalBytes = 0;
// Set the opmap
initOpmap();
}
void initOpmap() {
// generic ops:
opmap["replace"] = OpEntry(Command::REPLACE, "Replace a value");
opmap["delete"] = OpEntry(Command::REMOVE, "Delete a value");
opmap["get"] = OpEntry(Command::GET, "Retrieve a value");
opmap["exists"] = OpEntry(Command::EXISTS, "Check if a value exists");
// dict ops
opmap["add"] = OpEntry(Command::DICT_ADD, "Create a new dictionary value");
opmap["upsert"] = OpEntry(Command::DICT_UPSERT, "Create or replace a dictionary value");
// list ops
opmap["append"] = OpEntry(Command::ARRAY_APPEND, "Insert values to the end of an array");
opmap["prepend"] = OpEntry(Command::ARRAY_PREPEND, "Insert values to the beginning of an array");
opmap["addunique"] = OpEntry(Command::ARRAY_ADD_UNIQUE, "Add a unique value to an array");
opmap["insert"] = OpEntry(Command::ARRAY_INSERT, "Insert value at given array index");
// arithmetic ops
opmap["counter"] = OpEntry(Command::COUNTER);
// Generic ops
opmap["path"] = OpEntry(0xff, "Check the validity of a path");
}
UIntOption o_iter;
StringOption o_path;
StringOption o_value;
StringOption o_jsfile;
StringOption o_cmd;
BoolOption o_mkdirp;
map<string,OpEntry> opmap;
Parser parser;
size_t totalBytes;
};
static void
readJsonFile(string& name, vector<string>& out)
{
std::ifstream input(name.c_str());
if (input.fail()) {
throw name + ": " + strerror(errno);
}
fprintf(stderr, "Reading %s\n", name.c_str());
std::stringstream ss;
ss << input.rdbuf();
out.push_back(ss.str());
input.close();
}
static void
execOperation(Options& o)
{
vector<string> fileNames;
vector<string> inputStrs;
string flist = o.o_jsfile.const_result();
if (flist.find(',') == string::npos) {
fileNames.push_back(flist);
} else {
while (true) {
size_t pos = flist.find_first_of(',');
if (pos == string::npos) {
fileNames.push_back(flist);
break;
} else {
string curName = flist.substr(0, pos);
fileNames.push_back(curName);
flist = flist.substr(pos+1);
}
}
}
if (fileNames.empty()) {
throw string("At least one file must be passed!");
}
for (size_t ii = 0; ii < fileNames.size(); ii++) {
readJsonFile(fileNames[ii], inputStrs);
o.totalBytes += inputStrs.back().length();
}
uint8_t opcode = o.opmap[o.o_cmd.result()];
if (o.o_mkdirp.passed()) {
opcode |= 0x80;
}
string value = o.o_value.const_result();
string path = o.o_path.const_result();
Operation op;
Result res;
size_t itermax = o.o_iter.result();
for (size_t ii = 0; ii < itermax; ii++) {
op.clear();
res.clear();
const string& curInput = inputStrs[ii % inputStrs.size()];
op.set_value(value);
op.set_code(opcode);
op.set_doc(curInput);
op.set_result_buf(&res);
Error rv = op.op_exec(path);
if (!rv.success()) {
throw rv;
}
}
// Print the result.
if (opcode == Command::GET || opcode == Command::EXISTS) {
string match = res.matchloc().to_string();
printf("%s\n", match.c_str());
} else {
string newdoc;
for (auto ii : res.newdoc()) {
newdoc.append(ii.at, ii.length);
}
printf("%s\n", newdoc.c_str());
}
}
static void
execPathParse(Options& o)
{
size_t itermax = o.o_iter.result();
string path = o.o_path.const_result();
Path pth;
for (size_t ii = 0; ii < itermax; ii++) {
pth.clear();
int rv = pth.parse(path);
if (rv != 0) {
throw string("Failed to parse path!");
}
}
}
void runMain(int argc, char **argv)
{
using namespace std::chrono;
Options o;
if (!o.parser.parse(argc, argv)) {
throw string("Bad options!");
}
// Determine the command
string cmdStr = o.o_cmd.const_result();
auto t_begin = steady_clock::now();
if (cmdStr == "help") {
map<string,OpEntry>::const_iterator iter = o.opmap.begin();
for (; iter != o.opmap.end(); ++iter) {
const OpEntry& ent = iter->second;
fprintf(stderr, "%s (0x%x): ", iter->first.c_str(), ent.opcode);
fprintf(stderr, "%s\n", ent.description);
}
exit(EXIT_SUCCESS);
}
if (!o.o_path.passed()) {
fprintf(stderr, "Path (-p) required\n");
exit(EXIT_FAILURE);
}
if (o.opmap.find(cmdStr) != o.opmap.end()) {
if (!o.o_jsfile.passed()) {
throw string("Operation must contain file!");
}
execOperation(o);
} else if (cmdStr == "path") {
execPathParse(o);
} else {
throw string("Unknown command!");
}
auto total = duration_cast<duration<double>>(steady_clock::now() - t_begin);
// Get the number of seconds:
double n_seconds = total.count();
double ops_per_sec = static_cast<double>(o.o_iter.result()) / n_seconds;
double mb_per_sec = (
static_cast<double>(o.totalBytes) *
static_cast<double>(o.o_iter.result())) /
n_seconds;
mb_per_sec /= (1024 * 1024);
fprintf(stderr, "DURATION=%.2fs. OPS=%u\n", n_seconds, o.o_iter.result());
fprintf(stderr, "%.2f OPS/s\n", ops_per_sec);
fprintf(stderr, "%.2f MB/s\n", mb_per_sec);
}
int main(int argc, char **argv)
{
try {
runMain(argc, argv);
return EXIT_SUCCESS;
} catch (string& exc) {
fprintf(stderr, "%s\n", exc.c_str());
return EXIT_FAILURE;
} catch (Error& rc) {
fprintf(stderr, "Command failed: %s\n", rc.description());
} catch (std::exception& ex) {
fprintf(stderr, "Command failed: %s\n", ex.what());
}
}
<commit_msg>bench: allow 'raw' mode.<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2015 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#include <stdexcept>
#include <map>
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <istream>
#include <ostream>
#include <sstream>
#include <chrono>
#define CLIOPTS_ENABLE_CXX
#define INCLUDE_SUBDOC_NTOHLL
#include "subdoc/subdoc-api.h"
#include "subdoc/path.h"
#include "subdoc/match.h"
#include "subdoc/operations.h"
#include "contrib/cliopts/cliopts.h"
using std::string;
using std::vector;
using std::map;
using namespace cliopts;
using Subdoc::Path;
using Subdoc::Operation;
using Subdoc::Command;
using Subdoc::Error;
using Subdoc::Result;
struct OpEntry {
uint8_t opcode;
const char *description;
OpEntry(uint8_t opcode = 0, const char *description = NULL) :
opcode(opcode),
description(description) {}
operator uint8_t() const { return opcode; }
};
class Options {
public:
Options() :
o_iter('i', "iterations", 1000),
o_path('p', "docpath"),
o_value('v', "value"),
o_jsfile('f', "json"),
o_cmd('c', "command"),
o_mkdirp('M', "create-intermediate"),
o_txtscan('T', "text-scan"),
parser("subdoc-bench")
{
o_iter.description("Number of iterations to run");
o_path.description("Document path to manipulate");
o_value.description("Document value to insert");
o_jsfile.description("JSON files to operate on. If passing multiple files, each file should be delimited by a comma");
o_cmd.description("Command to use. Use -c help to show all the commands").mandatory();
o_mkdirp.description("Create intermediate paths for mutation operations");
o_txtscan.description("Simply scan the text using a naive approach. Used to see how much actual overhead jsonsl induces");
parser.addOption(o_iter);
parser.addOption(o_path);
parser.addOption(o_value);
parser.addOption(o_jsfile);
parser.addOption(o_cmd);
parser.addOption(o_mkdirp);
parser.addOption(o_txtscan);
totalBytes = 0;
// Set the opmap
initOpmap();
}
void initOpmap() {
// generic ops:
opmap["replace"] = OpEntry(Command::REPLACE, "Replace a value");
opmap["delete"] = OpEntry(Command::REMOVE, "Delete a value");
opmap["get"] = OpEntry(Command::GET, "Retrieve a value");
opmap["exists"] = OpEntry(Command::EXISTS, "Check if a value exists");
// dict ops
opmap["add"] = OpEntry(Command::DICT_ADD, "Create a new dictionary value");
opmap["upsert"] = OpEntry(Command::DICT_UPSERT, "Create or replace a dictionary value");
// list ops
opmap["append"] = OpEntry(Command::ARRAY_APPEND, "Insert values to the end of an array");
opmap["prepend"] = OpEntry(Command::ARRAY_PREPEND, "Insert values to the beginning of an array");
opmap["addunique"] = OpEntry(Command::ARRAY_ADD_UNIQUE, "Add a unique value to an array");
opmap["insert"] = OpEntry(Command::ARRAY_INSERT, "Insert value at given array index");
// arithmetic ops
opmap["counter"] = OpEntry(Command::COUNTER);
// Generic ops
opmap["path"] = OpEntry(0xff, "Check the validity of a path");
}
UIntOption o_iter;
StringOption o_path;
StringOption o_value;
StringOption o_jsfile;
StringOption o_cmd;
BoolOption o_mkdirp;
BoolOption o_txtscan;
map<string,OpEntry> opmap;
Parser parser;
size_t totalBytes;
};
static void
readJsonFile(string& name, vector<string>& out)
{
std::ifstream input(name.c_str());
if (input.fail()) {
throw name + ": " + strerror(errno);
}
fprintf(stderr, "Reading %s\n", name.c_str());
std::stringstream ss;
ss << input.rdbuf();
out.push_back(ss.str());
input.close();
}
static void
execOperation(Options& o)
{
vector<string> fileNames;
vector<string> inputStrs;
string flist = o.o_jsfile.const_result();
if (flist.find(',') == string::npos) {
fileNames.push_back(flist);
} else {
while (true) {
size_t pos = flist.find_first_of(',');
if (pos == string::npos) {
fileNames.push_back(flist);
break;
} else {
string curName = flist.substr(0, pos);
fileNames.push_back(curName);
flist = flist.substr(pos+1);
}
}
}
if (fileNames.empty()) {
throw string("At least one file must be passed!");
}
for (size_t ii = 0; ii < fileNames.size(); ii++) {
readJsonFile(fileNames[ii], inputStrs);
o.totalBytes += inputStrs.back().length();
}
uint8_t opcode = o.opmap[o.o_cmd.result()];
if (o.o_mkdirp.passed()) {
opcode |= 0x80;
}
string value = o.o_value.const_result();
string path = o.o_path.const_result();
Operation op;
Result res;
size_t nquotes = 0;
bool is_txtscan = o.o_txtscan.result();
size_t itermax = o.o_iter.result();
int char_table[256] = { 0 };
char_table['"'] = 1;
char_table['\\'] = 1;
char_table['!'] = 1;
for (size_t ii = 0; ii < itermax; ii++) {
const string& curInput = inputStrs[ii % inputStrs.size()];
if (is_txtscan) {
const char *buf = curInput.c_str();
size_t nbytes = curInput.size();
for (; nbytes; buf++, nbytes--) {
if (char_table[static_cast<unsigned char>(*buf)]) {
nquotes++;
}
}
continue;
}
op.clear();
res.clear();
op.set_value(value);
op.set_code(opcode);
op.set_doc(curInput);
op.set_result_buf(&res);
Error rv = op.op_exec(path);
if (!rv.success()) {
throw rv;
}
}
if (nquotes) {
printf("Found %lu quotes!\n", nquotes);
}
// Print the result.
if (opcode == Command::GET || opcode == Command::EXISTS) {
string match = res.matchloc().to_string();
printf("%s\n", match.c_str());
} else {
string newdoc;
for (auto ii : res.newdoc()) {
newdoc.append(ii.at, ii.length);
}
printf("%s\n", newdoc.c_str());
}
}
static void
execPathParse(Options& o)
{
size_t itermax = o.o_iter.result();
string path = o.o_path.const_result();
Path pth;
for (size_t ii = 0; ii < itermax; ii++) {
pth.clear();
int rv = pth.parse(path);
if (rv != 0) {
throw string("Failed to parse path!");
}
}
}
void runMain(int argc, char **argv)
{
using namespace std::chrono;
Options o;
if (!o.parser.parse(argc, argv)) {
throw string("Bad options!");
}
// Determine the command
string cmdStr = o.o_cmd.const_result();
auto t_begin = steady_clock::now();
if (cmdStr == "help") {
map<string,OpEntry>::const_iterator iter = o.opmap.begin();
for (; iter != o.opmap.end(); ++iter) {
const OpEntry& ent = iter->second;
fprintf(stderr, "%s (0x%x): ", iter->first.c_str(), ent.opcode);
fprintf(stderr, "%s\n", ent.description);
}
exit(EXIT_SUCCESS);
}
if (!o.o_path.passed()) {
fprintf(stderr, "Path (-p) required\n");
exit(EXIT_FAILURE);
}
if (o.opmap.find(cmdStr) != o.opmap.end()) {
if (!o.o_jsfile.passed()) {
throw string("Operation must contain file!");
}
execOperation(o);
} else if (cmdStr == "path") {
execPathParse(o);
} else {
throw string("Unknown command!");
}
auto total = duration_cast<duration<double>>(steady_clock::now() - t_begin);
// Get the number of seconds:
double n_seconds = total.count();
double ops_per_sec = static_cast<double>(o.o_iter.result()) / n_seconds;
double mb_per_sec = (
static_cast<double>(o.totalBytes) *
static_cast<double>(o.o_iter.result())) /
n_seconds;
mb_per_sec /= (1024 * 1024);
fprintf(stderr, "DURATION=%.2fs. OPS=%u\n", n_seconds, o.o_iter.result());
fprintf(stderr, "%.2f OPS/s\n", ops_per_sec);
fprintf(stderr, "%.2f MB/s\n", mb_per_sec);
}
int main(int argc, char **argv)
{
try {
runMain(argc, argv);
return EXIT_SUCCESS;
} catch (string& exc) {
fprintf(stderr, "%s\n", exc.c_str());
return EXIT_FAILURE;
} catch (Error& rc) {
fprintf(stderr, "Command failed: %s\n", rc.description());
} catch (std::exception& ex) {
fprintf(stderr, "Command failed: %s\n", ex.what());
}
}
<|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. *
**************************************************************************/
// Library class for particle pt and y distributions used for
// LambdaC simulations.
// To be used with AliGenParam.
//
// Author: Annalisa Mastroserio <Annalisa.Mastroserio@cern.ch>
//
#include <TPDGCode.h>
#include <TMath.h>
#include <TRandom.h>
#include <TString.h>
#include "AliGenLcLib.h"
#include "AliLog.h"
ClassImp(AliGenLcLib)
//---------------------------------------------
// LambdaC
//---------------------------------------------
Int_t AliGenLcLib::IpLcPlus(TRandom *)
{
//PDG code
return 4122;
}
Int_t AliGenLcLib::IpLcMinus(TRandom *)
{
//PDG code
return -4122;
}
Double_t AliGenLcLib::PtLcFlat( const Double_t *, const Double_t *)
{
// FLAT pt-distribution
return 1;
}
Double_t AliGenLcLib::PtLcExp( const Double_t *x, const Double_t *)
{
// EXP pt-distribution
return x[0]*TMath::Exp(-x[0]/0.17);
}
Double_t AliGenLcLib::YLcFlat(const Double_t */*x*/,const Double_t *)
{
//LambdaC y-distribution
return 5;
}
typedef Double_t (*GenFunc) (const Double_t*, const Double_t*);
typedef Int_t (*GenFuncIp) (TRandom *);
GenFunc AliGenLcLib::GetPt(Int_t iPID, const char * sForm) const
{
// Return pointer to Pt parameterisation
printf("PID: %i, form: %s \n",iPID,sForm);
TString type(sForm);
GenFunc func;
switch(iPID) {
case kLcPlus:
if (type=="FLAT") {func=PtLcFlat; break;}
else if(type=="EXP") {func=PtLcExp; break;}
else {
AliFatal(Form("Unknown Pt distribution form: %s",sForm)); func=0;
}
case kLcMinus:
if (type=="FLAT") {func=PtLcFlat; break;}
else if(type=="EXP") {func=PtLcExp; break;}
else {
AliFatal(Form("Unknown Pt distribution form: %s",sForm)); func=0;
}
default : AliFatal(Form("Unknown particle type: %i",iPID)); func=0;
}//switch
return func;
}
GenFunc AliGenLcLib::GetY(Int_t iPID, const char *sForm) const
{
AliDebug(1,Form("PID: %i, form: %s",iPID,sForm));
GenFunc func;
switch (iPID) {
case kLcPlus: func=YLcFlat; break;
case kLcMinus: func=YLcFlat; break;
default : AliFatal(Form("Unknown particle type: %i",iPID)); func=0; break;
}//switch
return func;
}
GenFuncIp AliGenLcLib::GetIp(Int_t iPID, const char *sForm) const
{
// Return pointer to particle type parameterisation
AliDebug(1,Form("PID: %i, form: %s",iPID,sForm)); //////////
switch (iPID){
case kLcPlus: return IpLcPlus;
case kLcMinus: return IpLcMinus;
default : AliFatal(Form("Unknown particle type: %i",iPID)); return 0;
}
}
<commit_msg>Change the pt spectrum shape of the Lc<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. *
**************************************************************************/
// Library class for particle pt and y distributions used for
// LambdaC simulations.
// To be used with AliGenParam.
//
// Author: Annalisa Mastroserio <Annalisa.Mastroserio@cern.ch>
//
#include <TPDGCode.h>
#include <TMath.h>
#include <TRandom.h>
#include <TString.h>
#include "AliGenLcLib.h"
#include "AliLog.h"
ClassImp(AliGenLcLib)
//---------------------------------------------
// LambdaC
//---------------------------------------------
Int_t AliGenLcLib::IpLcPlus(TRandom *)
{
//PDG code
return 4122;
}
Int_t AliGenLcLib::IpLcMinus(TRandom *)
{
//PDG code
return -4122;
}
Double_t AliGenLcLib::PtLcFlat( const Double_t *, const Double_t *)
{
// FLAT pt-distribution
return 1;
}
Double_t AliGenLcLib::PtLcExp( const Double_t *x, const Double_t *)
{
// pt-distribution
//return x[0]*TMath::Exp(-x[0]/0.16); // distribution used in LHC11f1 for the anchor runs : 139441, 139510, 139511, 130513, 130514, 130517.
return TMath::GammaDist(x[0],2,0,1.7); //distribution as in LHC11a10a of the prompt Lc whose daughters are in |eta|<0.9. Used for Lb as well.
}
Double_t AliGenLcLib::YLcFlat(const Double_t *,const Double_t *)
{
//LambdaC y-distribution
return 1;
}
typedef Double_t (*GenFunc) (const Double_t*, const Double_t*);
typedef Int_t (*GenFuncIp) (TRandom *);
GenFunc AliGenLcLib::GetPt(Int_t iPID, const char * sForm) const
{
// Return pointer to Pt parameterisation
printf("PID: %i, form: %s \n",iPID,sForm);
TString type(sForm);
GenFunc func;
switch(iPID) {
case kLcPlus:
if (type=="FLAT") {func=PtLcFlat; break;}
else if(type=="EXP") {func=PtLcExp; break;}
else {
AliFatal(Form("Unknown Pt distribution form: %s",sForm)); func=0;
}
case kLcMinus:
if (type=="FLAT") {func=PtLcFlat; break;}
else if(type=="EXP") {func=PtLcExp; break;}
else {
AliFatal(Form("Unknown Pt distribution form: %s",sForm)); func=0;
}
default : AliFatal(Form("Unknown particle type: %i",iPID)); func=0;
}//switch
return func;
}
GenFunc AliGenLcLib::GetY(Int_t iPID, const char *sForm) const
{
AliDebug(1,Form("PID: %i, form: %s",iPID,sForm));
GenFunc func;
switch (iPID) {
case kLcPlus: func=YLcFlat; break;
case kLcMinus: func=YLcFlat; break;
default : AliFatal(Form("Unknown particle type: %i",iPID)); func=0; break;
}//switch
return func;
}
GenFuncIp AliGenLcLib::GetIp(Int_t iPID, const char *sForm) const
{
// Return pointer to particle type parameterisation
AliDebug(1,Form("PID: %i, form: %s",iPID,sForm)); //////////
switch (iPID){
case kLcPlus: return IpLcPlus;
case kLcMinus: return IpLcMinus;
default : AliFatal(Form("Unknown particle type: %i",iPID)); return 0;
}
}
<|endoftext|> |
<commit_before>// This is a personal academic project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/**
* A camera component that generates view and projection matrices.
*
* License: Mozilla Public License Version 2.0 (https://www.mozilla.org/en-US/MPL/2.0/ OR See accompanying file LICENSE)
* Authors:
* - Dan Printzell
*/
#include <hydra/component/cameracomponent.hpp>
#include <imgui/imgui.h>
#include <glm/gtc/type_ptr.hpp>
using namespace Hydra::Component;
CameraComponent::CameraComponent(IEntity* entity) : IComponent(entity), _renderTarget(nullptr) { }
CameraComponent::CameraComponent(IEntity* entity, Hydra::Renderer::IRenderTarget* renderTarget, const glm::vec3& position) : IComponent(entity), _renderTarget(renderTarget), _position(position) {}
CameraComponent::~CameraComponent() {}
void CameraComponent::tick(TickAction action, float delta) {
_position += glm::vec3{0, 0, 0};
int mouseX, mouseY;
if (_mouseControl && SDL_GetRelativeMouseState(&mouseX, &mouseY) == SDL_BUTTON(3)) {
_cameraYaw += mouseX * _sensitivity;
_cameraPitch += mouseY * _sensitivity;
if (_cameraPitch > glm::radians(89.0f)){
_cameraPitch = glm::radians(89.0f);
}
else if(_cameraPitch < glm::radians(-89.0f)){
_cameraPitch = glm::radians(-89.0f);
}
}
glm::quat qPitch = glm::angleAxis(_cameraPitch, glm::vec3(1, 0, 0));
glm::quat qYaw = glm::angleAxis(_cameraYaw, glm::vec3(0, 1, 0));
glm::quat qRoll = glm::angleAxis(glm::radians(180.f), glm::vec3(0, 0, 1));
_orientation = qPitch * qYaw * qRoll;
_orientation = glm::normalize(_orientation);
}
void CameraComponent::translate(const glm::vec3& transform) {
_position += transform * _orientation;
}
void CameraComponent::rotation(float angle, const glm::vec3& axis) {
_orientation *= glm::angleAxis(angle, axis * _orientation);
}
CameraComponent& CameraComponent::yaw(float angle) { rotation(angle, {0, 1, 0}); return *this; }
CameraComponent& CameraComponent::pitch(float angle) { rotation(angle, {1, 0, 0}); return *this; }
CameraComponent& CameraComponent::roll(float angle) { rotation(angle, {0, 0, 1}); return *this; }
void Hydra::Component::CameraComponent::setPosition(const glm::vec3 & position) {
_position = position;
}
void CameraComponent::serialize(nlohmann::json& json) const {
json = {
{"position", {_position.x, _position.y, _position.z}},
{"orientation", {_orientation.x, _orientation.y, _orientation.z, _orientation.w}},
{"fov", _fov},
{"zNear", _zNear},
{"zFar", _zFar}
};
}
void CameraComponent::deserialize(nlohmann::json& json) {
auto& pos = json["position"];
_position = glm::vec3{pos[0].get<float>(), pos[1].get<float>(), pos[2].get<float>()};
auto& orientation = json["orientation"];
_orientation = glm::quat{orientation[0].get<float>(), orientation[1].get<float>(), orientation[2].get<float>(), orientation[3].get<float>()};
_fov = json["fov"].get<float>();
_zNear = json["zNear"].get<float>();
_zFar = json["zFar"].get<float>();
}
void CameraComponent::registerUI() {
//TODO: Change if dirty flag is added!
ImGui::DragFloat3("Position", glm::value_ptr(_position), 0.01f);
ImGui::DragFloat4("Orientation", glm::value_ptr(_orientation), 0.01f);
ImGui::DragFloat("FOV", &_fov);
ImGui::DragFloat("Z Near", &_zNear, 0.001f);
ImGui::DragFloat("Z Far", &_zFar);
float aspect = (_renderTarget->getSize().x*1.0f) / _renderTarget->getSize().y;
ImGui::InputFloat("Aspect", &aspect, 0, 0, -1, ImGuiInputTextFlags_ReadOnly);
ImGui::Checkbox("Mouse Control", &_mouseControl);
}
<commit_msg>Now you can aim and shoot at the same time<commit_after>// This is a personal academic project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/**
* A camera component that generates view and projection matrices.
*
* License: Mozilla Public License Version 2.0 (https://www.mozilla.org/en-US/MPL/2.0/ OR See accompanying file LICENSE)
* Authors:
* - Dan Printzell
*/
#include <hydra/component/cameracomponent.hpp>
#include <imgui/imgui.h>
#include <glm/gtc/type_ptr.hpp>
using namespace Hydra::Component;
CameraComponent::CameraComponent(IEntity* entity) : IComponent(entity), _renderTarget(nullptr) { }
CameraComponent::CameraComponent(IEntity* entity, Hydra::Renderer::IRenderTarget* renderTarget, const glm::vec3& position) : IComponent(entity), _renderTarget(renderTarget), _position(position) {}
CameraComponent::~CameraComponent() {}
void CameraComponent::tick(TickAction action, float delta) {
_position += glm::vec3{0, 0, 0};
int mouseX, mouseY;
if (_mouseControl && SDL_GetRelativeMouseState(&mouseX, &mouseY) & SDL_BUTTON(3)) {
_cameraYaw += mouseX * _sensitivity;
_cameraPitch += mouseY * _sensitivity;
if (_cameraPitch > glm::radians(89.0f)){
_cameraPitch = glm::radians(89.0f);
}
else if(_cameraPitch < glm::radians(-89.0f)){
_cameraPitch = glm::radians(-89.0f);
}
}
glm::quat qPitch = glm::angleAxis(_cameraPitch, glm::vec3(1, 0, 0));
glm::quat qYaw = glm::angleAxis(_cameraYaw, glm::vec3(0, 1, 0));
glm::quat qRoll = glm::angleAxis(glm::radians(180.f), glm::vec3(0, 0, 1));
_orientation = qPitch * qYaw * qRoll;
_orientation = glm::normalize(_orientation);
}
void CameraComponent::translate(const glm::vec3& transform) {
_position += transform * _orientation;
}
void CameraComponent::rotation(float angle, const glm::vec3& axis) {
_orientation *= glm::angleAxis(angle, axis * _orientation);
}
CameraComponent& CameraComponent::yaw(float angle) { rotation(angle, {0, 1, 0}); return *this; }
CameraComponent& CameraComponent::pitch(float angle) { rotation(angle, {1, 0, 0}); return *this; }
CameraComponent& CameraComponent::roll(float angle) { rotation(angle, {0, 0, 1}); return *this; }
void Hydra::Component::CameraComponent::setPosition(const glm::vec3 & position) {
_position = position;
}
void CameraComponent::serialize(nlohmann::json& json) const {
json = {
{"position", {_position.x, _position.y, _position.z}},
{"orientation", {_orientation.x, _orientation.y, _orientation.z, _orientation.w}},
{"fov", _fov},
{"zNear", _zNear},
{"zFar", _zFar}
};
}
void CameraComponent::deserialize(nlohmann::json& json) {
auto& pos = json["position"];
_position = glm::vec3{pos[0].get<float>(), pos[1].get<float>(), pos[2].get<float>()};
auto& orientation = json["orientation"];
_orientation = glm::quat{orientation[0].get<float>(), orientation[1].get<float>(), orientation[2].get<float>(), orientation[3].get<float>()};
_fov = json["fov"].get<float>();
_zNear = json["zNear"].get<float>();
_zFar = json["zFar"].get<float>();
}
void CameraComponent::registerUI() {
//TODO: Change if dirty flag is added!
ImGui::DragFloat3("Position", glm::value_ptr(_position), 0.01f);
ImGui::DragFloat4("Orientation", glm::value_ptr(_orientation), 0.01f);
ImGui::DragFloat("FOV", &_fov);
ImGui::DragFloat("Z Near", &_zNear, 0.001f);
ImGui::DragFloat("Z Far", &_zFar);
float aspect = (_renderTarget->getSize().x*1.0f) / _renderTarget->getSize().y;
ImGui::InputFloat("Aspect", &aspect, 0, 0, -1, ImGuiInputTextFlags_ReadOnly);
ImGui::Checkbox("Mouse Control", &_mouseControl);
}
<|endoftext|> |
<commit_before>// @(#)root/graf:$Id$
// Author: Rene Brun 17/10/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "Riostream.h"
#include "TROOT.h"
#include "TStyle.h"
#include "TPaveLabel.h"
#include "TLatex.h"
#include "TVirtualPad.h"
ClassImp(TPaveLabel)
//______________________________________________________________________________
//* A PaveLabel is a Pave (see TPave) with a text centered in the Pave.
//Begin_Html
/*
<img src="gif/pavelabel.gif">
*/
//End_Html
//
//______________________________________________________________________________
TPaveLabel::TPaveLabel(): TPave(), TAttText()
{
// Pavelabel default constructor.
}
//______________________________________________________________________________
TPaveLabel::TPaveLabel(Double_t x1, Double_t y1,Double_t x2, Double_t y2, const char *label, Option_t *option)
:TPave(x1,y1,x2,y2,3,option), TAttText(22,0,1,gStyle->GetTextFont(),0.99)
{
// Pavelabel normal constructor.
//
// a PaveLabel is a Pave with a label centered in the Pave
// The Pave is by default defined bith bordersize=5 and option ="br".
// The text size is automatically computed as a function of the pave size.
//
// IMPORTANT NOTE:
// Because TPave objects (and objects deriving from TPave) have their
// master coordinate system in NDC, one cannot use the TBox functions
// SetX1,SetY1,SetX2,SetY2 to change the corner coordinates. One should use
// instead SetX1NDC, SetY1NDC, SetX2NDC, SetY2NDC.
fLabel = label;
}
//______________________________________________________________________________
TPaveLabel::~TPaveLabel()
{
// Pavelabel default destructor.
}
//______________________________________________________________________________
TPaveLabel::TPaveLabel(const TPaveLabel &pavelabel) : TPave(pavelabel), TAttText(pavelabel)
{
// Pavelabel copy constructor.
((TPaveLabel&)pavelabel).Copy(*this);
}
//______________________________________________________________________________
void TPaveLabel::Copy(TObject &obj) const
{
// Copy this pavelabel to pavelabel.
TPave::Copy(obj);
TAttText::Copy(((TPaveLabel&)obj));
((TPaveLabel&)obj).fLabel = fLabel;
}
//______________________________________________________________________________
void TPaveLabel::Draw(Option_t *option)
{
// Draw this pavelabel with its current attributes.
Option_t *opt;
if (option && strlen(option)) opt = option;
else opt = GetOption();
AppendPad(opt);
}
//______________________________________________________________________________
void TPaveLabel::DrawPaveLabel(Double_t x1, Double_t y1, Double_t x2, Double_t y2, const char *label, Option_t *option)
{
// Draw this pavelabel with new coordinates.
TPaveLabel *newpavelabel = new TPaveLabel(x1,y1,x2,y2,label,option);
newpavelabel->SetBit(kCanDelete);
newpavelabel->AppendPad();
}
//______________________________________________________________________________
void TPaveLabel::Paint(Option_t *option)
{
// Paint this pavelabel with its current attributes.
// Convert from NDC to pad coordinates
TPave::ConvertNDCtoPad();
PaintPaveLabel(fX1, fY1, fX2, fY2, GetLabel(), strlen(option)?option:GetOption());
}
//______________________________________________________________________________
void TPaveLabel::PaintPaveLabel(Double_t x1, Double_t y1,Double_t x2, Double_t y2,
const char *label ,Option_t *option)
{
// Draw this pavelabel with new coordinates.
Int_t nch = strlen(label);
// Draw the pave
TPave::PaintPave(x1,y1,x2,y2,GetBorderSize(),option);
Float_t nspecials = 0;
for (Int_t i=0;i<nch;i++) {
if (label[i] == '!') nspecials += 1;
if (label[i] == '?') nspecials += 1.5;
if (label[i] == '#') nspecials += 1;
if (label[i] == '`') nspecials += 1;
if (label[i] == '^') nspecials += 1.5;
if (label[i] == '~') nspecials += 1;
if (label[i] == '&') nspecials += 2;
if (label[i] == '\\') nspecials += 3; // octal characters very likely
}
nch -= Int_t(nspecials + 0.5);
if (nch <= 0) return;
// Draw label
Double_t wh = (Double_t)gPad->XtoPixel(gPad->GetX2());
Double_t hh = (Double_t)gPad->YtoPixel(gPad->GetY1());
Double_t labelsize, textsize = GetTextSize();
Int_t automat = 0;
if (GetTextFont()%10 > 2) { // fixed size font specified in pixels
labelsize = GetTextSize();
} else {
if (TMath::Abs(textsize -0.99) < 0.001) automat = 1;
if (textsize == 0) { textsize = 0.99; automat = 1;}
Int_t ypixel = TMath::Abs(gPad->YtoPixel(y1) - gPad->YtoPixel(y2));
labelsize = textsize*ypixel/hh;
if (wh < hh) labelsize *= hh/wh;
}
TLatex latex;
latex.SetTextAngle(GetTextAngle());
latex.SetTextFont(GetTextFont());
latex.SetTextAlign(GetTextAlign());
latex.SetTextColor(GetTextColor());
latex.SetTextSize(labelsize);
if (automat) {
UInt_t w,h,w1;
latex.GetTextExtent(w,h,GetTitle());
labelsize = h/hh;
Double_t wxlabel = TMath::Abs(gPad->XtoPixel(x2) - gPad->XtoPixel(x1));
latex.GetTextExtent(w1,h,GetTitle());
while (w > 0.99*wxlabel) {
labelsize *= 0.99*wxlabel/w;
latex.SetTextSize(labelsize);
latex.GetTextExtent(w,h,GetTitle());
if (w==w1) break;
else w1=w;
}
if (h < 1) h = 1;
if (h==1) {
labelsize = Double_t(h)/hh;
if (wh < hh) labelsize *= hh/wh;
latex.SetTextSize(labelsize);
}
}
Int_t halign = GetTextAlign()/10;
Int_t valign = GetTextAlign()%10;
Double_t x = 0.5*(x1+x2);
if (halign == 1) x = x1 + 0.02*(x2-x1);
if (halign == 3) x = x2 - 0.02*(x2-x1);
Double_t y = 0.5*(y1+y2);
if (valign == 1) y = y1 + 0.02*(y2-y1);
if (valign == 3) y = y2 - 0.02*(y2-y1);
latex.PaintLatex(x, y, GetTextAngle(),labelsize,GetLabel());
}
//______________________________________________________________________________
void TPaveLabel::SavePrimitive(ostream &out, Option_t * /*= ""*/)
{
// Save primitive as a C++ statement(s) on output stream out
char quote = '"';
out<<" "<<endl;
if (gROOT->ClassSaved(TPaveLabel::Class())) {
out<<" ";
} else {
out<<" TPaveLabel *";
}
TString s = fLabel.Data();
s.ReplaceAll("\"","\\\"");
if (fOption.Contains("NDC")) {
out<<"pl = new TPaveLabel("<<fX1NDC<<","<<fY1NDC<<","<<fX2NDC<<","<<fY2NDC
<<","<<quote<<s.Data()<<quote<<","<<quote<<fOption<<quote<<");"<<endl;
} else {
out<<"pl = new TPaveLabel("<<gPad->PadtoX(fX1)<<","<<gPad->PadtoY(fY1)<<","<<gPad->PadtoX(fX2)<<","<<gPad->PadtoY(fY2)
<<","<<quote<<s.Data()<<quote<<","<<quote<<fOption<<quote<<");"<<endl;
}
if (fBorderSize != 3) {
out<<" pl->SetBorderSize("<<fBorderSize<<");"<<endl;
}
SaveFillAttributes(out,"pl",19,1001);
SaveLineAttributes(out,"pl",1,1,1);
SaveTextAttributes(out,"pl",22,0,1,62,0);
out<<" pl->Draw();"<<endl;
}
<commit_msg>Fix coverity reports (UNINIT)<commit_after>// @(#)root/graf:$Id$
// Author: Rene Brun 17/10/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "Riostream.h"
#include "TROOT.h"
#include "TStyle.h"
#include "TPaveLabel.h"
#include "TLatex.h"
#include "TVirtualPad.h"
ClassImp(TPaveLabel)
//______________________________________________________________________________
//* A PaveLabel is a Pave (see TPave) with a text centered in the Pave.
//Begin_Html
/*
<img src="gif/pavelabel.gif">
*/
//End_Html
//
//______________________________________________________________________________
TPaveLabel::TPaveLabel(): TPave(), TAttText()
{
// Pavelabel default constructor.
}
//______________________________________________________________________________
TPaveLabel::TPaveLabel(Double_t x1, Double_t y1,Double_t x2, Double_t y2, const char *label, Option_t *option)
:TPave(x1,y1,x2,y2,3,option), TAttText(22,0,1,gStyle->GetTextFont(),0.99)
{
// Pavelabel normal constructor.
//
// a PaveLabel is a Pave with a label centered in the Pave
// The Pave is by default defined bith bordersize=5 and option ="br".
// The text size is automatically computed as a function of the pave size.
//
// IMPORTANT NOTE:
// Because TPave objects (and objects deriving from TPave) have their
// master coordinate system in NDC, one cannot use the TBox functions
// SetX1,SetY1,SetX2,SetY2 to change the corner coordinates. One should use
// instead SetX1NDC, SetY1NDC, SetX2NDC, SetY2NDC.
fLabel = label;
}
//______________________________________________________________________________
TPaveLabel::~TPaveLabel()
{
// Pavelabel default destructor.
}
//______________________________________________________________________________
TPaveLabel::TPaveLabel(const TPaveLabel &pavelabel) : TPave(pavelabel), TAttText(pavelabel)
{
// Pavelabel copy constructor.
((TPaveLabel&)pavelabel).Copy(*this);
}
//______________________________________________________________________________
void TPaveLabel::Copy(TObject &obj) const
{
// Copy this pavelabel to pavelabel.
TPave::Copy(obj);
TAttText::Copy(((TPaveLabel&)obj));
((TPaveLabel&)obj).fLabel = fLabel;
}
//______________________________________________________________________________
void TPaveLabel::Draw(Option_t *option)
{
// Draw this pavelabel with its current attributes.
Option_t *opt;
if (option && strlen(option)) opt = option;
else opt = GetOption();
AppendPad(opt);
}
//______________________________________________________________________________
void TPaveLabel::DrawPaveLabel(Double_t x1, Double_t y1, Double_t x2, Double_t y2, const char *label, Option_t *option)
{
// Draw this pavelabel with new coordinates.
TPaveLabel *newpavelabel = new TPaveLabel(x1,y1,x2,y2,label,option);
newpavelabel->SetBit(kCanDelete);
newpavelabel->AppendPad();
}
//______________________________________________________________________________
void TPaveLabel::Paint(Option_t *option)
{
// Paint this pavelabel with its current attributes.
// Convert from NDC to pad coordinates
TPave::ConvertNDCtoPad();
PaintPaveLabel(fX1, fY1, fX2, fY2, GetLabel(), strlen(option)?option:GetOption());
}
//______________________________________________________________________________
void TPaveLabel::PaintPaveLabel(Double_t x1, Double_t y1,Double_t x2, Double_t y2,
const char *label ,Option_t *option)
{
// Draw this pavelabel with new coordinates.
Int_t nch = strlen(label);
// Draw the pave
TPave::PaintPave(x1,y1,x2,y2,GetBorderSize(),option);
Float_t nspecials = 0;
for (Int_t i=0;i<nch;i++) {
if (label[i] == '!') nspecials += 1;
if (label[i] == '?') nspecials += 1.5;
if (label[i] == '#') nspecials += 1;
if (label[i] == '`') nspecials += 1;
if (label[i] == '^') nspecials += 1.5;
if (label[i] == '~') nspecials += 1;
if (label[i] == '&') nspecials += 2;
if (label[i] == '\\') nspecials += 3; // octal characters very likely
}
nch -= Int_t(nspecials + 0.5);
if (nch <= 0) return;
// Draw label
Double_t wh = (Double_t)gPad->XtoPixel(gPad->GetX2());
Double_t hh = (Double_t)gPad->YtoPixel(gPad->GetY1());
Double_t labelsize, textsize = GetTextSize();
Int_t automat = 0;
if (GetTextFont()%10 > 2) { // fixed size font specified in pixels
labelsize = GetTextSize();
} else {
if (TMath::Abs(textsize -0.99) < 0.001) automat = 1;
if (textsize == 0) { textsize = 0.99; automat = 1;}
Int_t ypixel = TMath::Abs(gPad->YtoPixel(y1) - gPad->YtoPixel(y2));
labelsize = textsize*ypixel/hh;
if (wh < hh) labelsize *= hh/wh;
}
TLatex latex;
latex.SetTextAngle(GetTextAngle());
latex.SetTextFont(GetTextFont());
latex.SetTextAlign(GetTextAlign());
latex.SetTextColor(GetTextColor());
latex.SetTextSize(labelsize);
if (automat) {
UInt_t w=0,h=0,w1=0;
latex.GetTextExtent(w,h,GetTitle());
labelsize = h/hh;
Double_t wxlabel = TMath::Abs(gPad->XtoPixel(x2) - gPad->XtoPixel(x1));
latex.GetTextExtent(w1,h,GetTitle());
while (w > 0.99*wxlabel) {
labelsize *= 0.99*wxlabel/w;
latex.SetTextSize(labelsize);
latex.GetTextExtent(w,h,GetTitle());
if (w==w1) break;
else w1=w;
}
if (h < 1) h = 1;
if (h==1) {
labelsize = Double_t(h)/hh;
if (wh < hh) labelsize *= hh/wh;
latex.SetTextSize(labelsize);
}
}
Int_t halign = GetTextAlign()/10;
Int_t valign = GetTextAlign()%10;
Double_t x = 0.5*(x1+x2);
if (halign == 1) x = x1 + 0.02*(x2-x1);
if (halign == 3) x = x2 - 0.02*(x2-x1);
Double_t y = 0.5*(y1+y2);
if (valign == 1) y = y1 + 0.02*(y2-y1);
if (valign == 3) y = y2 - 0.02*(y2-y1);
latex.PaintLatex(x, y, GetTextAngle(),labelsize,GetLabel());
}
//______________________________________________________________________________
void TPaveLabel::SavePrimitive(ostream &out, Option_t * /*= ""*/)
{
// Save primitive as a C++ statement(s) on output stream out
char quote = '"';
out<<" "<<endl;
if (gROOT->ClassSaved(TPaveLabel::Class())) {
out<<" ";
} else {
out<<" TPaveLabel *";
}
TString s = fLabel.Data();
s.ReplaceAll("\"","\\\"");
if (fOption.Contains("NDC")) {
out<<"pl = new TPaveLabel("<<fX1NDC<<","<<fY1NDC<<","<<fX2NDC<<","<<fY2NDC
<<","<<quote<<s.Data()<<quote<<","<<quote<<fOption<<quote<<");"<<endl;
} else {
out<<"pl = new TPaveLabel("<<gPad->PadtoX(fX1)<<","<<gPad->PadtoY(fY1)<<","<<gPad->PadtoX(fX2)<<","<<gPad->PadtoY(fY2)
<<","<<quote<<s.Data()<<quote<<","<<quote<<fOption<<quote<<");"<<endl;
}
if (fBorderSize != 3) {
out<<" pl->SetBorderSize("<<fBorderSize<<");"<<endl;
}
SaveFillAttributes(out,"pl",19,1001);
SaveLineAttributes(out,"pl",1,1,1);
SaveTextAttributes(out,"pl",22,0,1,62,0);
out<<" pl->Draw();"<<endl;
}
<|endoftext|> |
<commit_before>// (C) Copyright Gennadiy Rozental 2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : defines the is_forward_iterable collection type trait
// ***************************************************************************
#ifndef BOOST_TEST_IS_FORWARD_ITERABLE_HPP_110612GER
#define BOOST_TEST_IS_FORWARD_ITERABLE_HPP_110612GER
#ifdef BOOST_NO_CXX11_DECLTYPE
// Boost
#include <boost/mpl/bool.hpp>
// STL
#include <list>
#include <vector>
#include <map>
#include <set>
#else
// Boost
#include <boost/utility/declval.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/type_traits/remove_cv.hpp>
// STL
#include <utility>
#include <type_traits>
#endif
//____________________________________________________________________________//
namespace boost {
namespace unit_test {
// ************************************************************************** //
// ************** is_forward_iterable ************** //
// ************************************************************************** //
#if defined(BOOST_NO_CXX11_DECLTYPE) || defined(BOOST_NO_CXX11_NULLPTR) || defined(BOOST_NO_CXX11_TRAILING_RESULT_TYPES)
template<typename T>
struct is_forward_iterable : public mpl::false_ {};
template<typename T>
struct is_forward_iterable<T const> : public is_forward_iterable<T> {};
template<typename T>
struct is_forward_iterable<T&> : public is_forward_iterable<T> {};
template<typename T, typename A>
struct is_forward_iterable< std::vector<T, A> > : public mpl::true_ {};
template<typename T, typename A>
struct is_forward_iterable< std::list<T, A> > : public mpl::true_ {};
template<typename K, typename V, typename C, typename A>
struct is_forward_iterable< std::map<K, V, C, A> > : public mpl::true_ {};
template<typename K, typename C, typename A>
struct is_forward_iterable< std::set<K, C, A> > : public mpl::true_ {};
#else
namespace ut_detail {
template<typename T>
struct is_present : public mpl::true_ {};
// some compiler do not implement properly decltype non expression involving members (eg. VS2013)
// a workaround is to use -> decltype syntax.
template <class T>
struct has_member_size {
private:
struct nil_t;
template<typename U> static auto test(U*) -> decltype( boost::declval<U>().size() );
template<typename> static nil_t test(...);
public:
static bool const value = !std::is_same< decltype(test<T>(nullptr)), nil_t>::value;
};
template <class T>
struct has_member_begin {
private:
struct nil_t;
template<typename U> static auto test(U*) -> decltype( boost::declval<U>().begin() );
template<typename> static nil_t test(...);
public:
static bool const value = !std::is_same< decltype(test<T>(nullptr)), nil_t>::value;
};
template <class T, class enabled = void>
struct is_forward_iterable_impl : std::false_type
{};
template <class T>
struct is_forward_iterable_impl<
T,
typename std::enable_if<
is_present<typename T::const_iterator>::value &&
is_present<typename T::value_type>::value &&
has_member_size<T>::value &&
has_member_begin<T>::value &&
!is_same<typename remove_cv<typename T::value_type>::type,char>::value &&
!is_same<typename remove_cv<typename T::value_type>::type,wchar_t>::value
>::type
> : std::true_type
{};
} // namespace ut_detail
template<typename T>
struct is_forward_iterable {
typedef typename std::remove_reference<T>::type T_ref;
typedef ut_detail::is_forward_iterable_impl<T_ref> is_fwd_it_t;
typedef mpl::bool_<is_fwd_it_t::value> type;
enum { value = is_fwd_it_t::value };
};
#endif
} // namespace unit_test
} // namespace boost
#endif // BOOST_TEST_IS_FORWARD_ITERABLE_HPP_110612GER
<commit_msg>Also the include part<commit_after>// (C) Copyright Gennadiy Rozental 2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : defines the is_forward_iterable collection type trait
// ***************************************************************************
#ifndef BOOST_TEST_IS_FORWARD_ITERABLE_HPP_110612GER
#define BOOST_TEST_IS_FORWARD_ITERABLE_HPP_110612GER
#if defined(BOOST_NO_CXX11_DECLTYPE) || defined(BOOST_NO_CXX11_NULLPTR) || defined(BOOST_NO_CXX11_TRAILING_RESULT_TYPES)
#define BOOST_TEST_FWD_ITERABLE_CXX03
#endif
#if defined(BOOST_TEST_FWD_ITERABLE_CXX03)
// Boost
#include <boost/mpl/bool.hpp>
// STL
#include <list>
#include <vector>
#include <map>
#include <set>
#else
// Boost
#include <boost/utility/declval.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/type_traits/remove_cv.hpp>
// STL
#include <utility>
#include <type_traits>
#endif
//____________________________________________________________________________//
namespace boost {
namespace unit_test {
// ************************************************************************** //
// ************** is_forward_iterable ************** //
// ************************************************************************** //
#if defined(BOOST_TEST_FWD_ITERABLE_CXX03)
template<typename T>
struct is_forward_iterable : public mpl::false_ {};
template<typename T>
struct is_forward_iterable<T const> : public is_forward_iterable<T> {};
template<typename T>
struct is_forward_iterable<T&> : public is_forward_iterable<T> {};
template<typename T, typename A>
struct is_forward_iterable< std::vector<T, A> > : public mpl::true_ {};
template<typename T, typename A>
struct is_forward_iterable< std::list<T, A> > : public mpl::true_ {};
template<typename K, typename V, typename C, typename A>
struct is_forward_iterable< std::map<K, V, C, A> > : public mpl::true_ {};
template<typename K, typename C, typename A>
struct is_forward_iterable< std::set<K, C, A> > : public mpl::true_ {};
#else
namespace ut_detail {
template<typename T>
struct is_present : public mpl::true_ {};
// some compiler do not implement properly decltype non expression involving members (eg. VS2013)
// a workaround is to use -> decltype syntax.
template <class T>
struct has_member_size {
private:
struct nil_t;
template<typename U> static auto test(U*) -> decltype( boost::declval<U>().size() );
template<typename> static nil_t test(...);
public:
static bool const value = !std::is_same< decltype(test<T>(nullptr)), nil_t>::value;
};
template <class T>
struct has_member_begin {
private:
struct nil_t;
template<typename U> static auto test(U*) -> decltype( boost::declval<U>().begin() );
template<typename> static nil_t test(...);
public:
static bool const value = !std::is_same< decltype(test<T>(nullptr)), nil_t>::value;
};
template <class T, class enabled = void>
struct is_forward_iterable_impl : std::false_type
{};
template <class T>
struct is_forward_iterable_impl<
T,
typename std::enable_if<
is_present<typename T::const_iterator>::value &&
is_present<typename T::value_type>::value &&
has_member_size<T>::value &&
has_member_begin<T>::value &&
!is_same<typename remove_cv<typename T::value_type>::type,char>::value &&
!is_same<typename remove_cv<typename T::value_type>::type,wchar_t>::value
>::type
> : std::true_type
{};
} // namespace ut_detail
template<typename T>
struct is_forward_iterable {
typedef typename std::remove_reference<T>::type T_ref;
typedef ut_detail::is_forward_iterable_impl<T_ref> is_fwd_it_t;
typedef mpl::bool_<is_fwd_it_t::value> type;
enum { value = is_fwd_it_t::value };
};
#endif
} // namespace unit_test
} // namespace boost
#endif // BOOST_TEST_IS_FORWARD_ITERABLE_HPP_110612GER
<|endoftext|> |
<commit_before>/*
* This file is part of TelepathyQt4Yell Models
*
* Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4Yell/Models/AccountsModelItem>
#include "TelepathyQt4Yell/Models/_gen/accounts-model-item.moc.hpp"
#include <TelepathyQt4Yell/Models/AccountsModel>
#include <TelepathyQt4Yell/Models/AvatarImageProvider>
#include <TelepathyQt4Yell/Models/ContactModelItem>
#include <TelepathyQt4/Account>
#include <TelepathyQt4/ContactManager>
namespace Tpy
{
struct TELEPATHY_QT4_YELL_MODELS_NO_EXPORT AccountsModelItem::Private
{
Private(const Tp::AccountPtr &account)
: mAccount(account)
{
}
void setStatus(const QString &value);
void setStatusMessage(const QString &value);
Tp::AccountPtr mAccount;
};
void AccountsModelItem::Private::setStatus(const QString &value)
{
Tp::Presence presence = mAccount->currentPresence().barePresence();
presence.setStatus(Tp::ConnectionPresenceTypeUnset, value, QString());
mAccount->setRequestedPresence(presence);
}
void AccountsModelItem::Private::setStatusMessage(const QString &value)
{
Tp::Presence presence = mAccount->currentPresence().barePresence();
presence.setStatus(Tp::ConnectionPresenceTypeUnset, QString(), value);
mAccount->setRequestedPresence(presence);
}
AccountsModelItem::AccountsModelItem(const Tp::AccountPtr &account)
: mPriv(new Private(account))
{
if (!mPriv->mAccount->connection().isNull()) {
Tp::ContactManagerPtr manager = account->connection()->contactManager();
connect(manager.data(),
SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts,
Tp::Channel::GroupMemberChangeDetails)),
SLOT(onContactsChanged(Tp::Contacts,Tp::Contacts)));
}
connect(mPriv->mAccount.data(),
SIGNAL(removed()),
SLOT(onRemoved()));
connect(mPriv->mAccount.data(),
SIGNAL(serviceNameChanged(QString)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(profileChanged(Tp::ProfilePtr)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(iconNameChanged(QString)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(nicknameChanged(QString)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(normalizedNameChanged(QString)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(validityChanged(bool)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(stateChanged(bool)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(capabilitiesChanged(Tp::ConnectionCapabilities)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(connectsAutomaticallyPropertyChanged(bool)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(parametersChanged(QVariantMap)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(changingPresence(bool)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(automaticPresenceChanged(Tp::Presence)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(currentPresenceChanged(Tp::Presence)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(requestedPresenceChanged(Tp::Presence)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(onlinenessChanged(bool)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(avatarChanged(Tp::Avatar)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(onlinenessChanged(bool)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(connectionStatusChanged(Tp::ConnectionStatus)),
SLOT(onStatusChanged(Tp::ConnectionStatus)));
connect(mPriv->mAccount.data(),
SIGNAL(connectionChanged(Tp::ConnectionPtr)),
SLOT(onConnectionChanged(Tp::ConnectionPtr)));
}
AccountsModelItem::~AccountsModelItem()
{
delete mPriv;
}
QVariant AccountsModelItem::data(int role) const
{
switch (role) {
case AccountsModel::ItemRole:
return QVariant::fromValue(
const_cast<QObject *>(
static_cast<const QObject *>(this)));
case AccountsModel::IdRole:
return mPriv->mAccount->uniqueIdentifier();
case AccountsModel::AvatarRole:
return AvatarImageProvider::urlFor(mPriv->mAccount);
case AccountsModel::ValidRole:
return mPriv->mAccount->isValid();
case AccountsModel::EnabledRole:
return mPriv->mAccount->isEnabled();
case AccountsModel::ConnectionManagerNameRole:
return mPriv->mAccount->cmName();
case AccountsModel::ProtocolNameRole:
return mPriv->mAccount->protocolName();
case AccountsModel::DisplayNameRole:
case Qt::DisplayRole:
return mPriv->mAccount->displayName();
case AccountsModel::IconRole:
return mPriv->mAccount->iconName();
case AccountsModel::NicknameRole:
return mPriv->mAccount->nickname();
case AccountsModel::ConnectsAutomaticallyRole:
return mPriv->mAccount->connectsAutomatically();
case AccountsModel::ChangingPresenceRole:
return mPriv->mAccount->isChangingPresence();
case AccountsModel::AutomaticPresenceRole:
return mPriv->mAccount->automaticPresence().status();
case AccountsModel::AutomaticPresenceTypeRole:
return mPriv->mAccount->automaticPresence().type();
case AccountsModel::AutomaticPresenceStatusMessageRole:
return mPriv->mAccount->automaticPresence().statusMessage();
case AccountsModel::CurrentPresenceRole:
return mPriv->mAccount->currentPresence().status();
case AccountsModel::CurrentPresenceTypeRole:
return mPriv->mAccount->currentPresence().type();
case AccountsModel::CurrentPresenceStatusMessageRole:
return mPriv->mAccount->currentPresence().statusMessage();
case AccountsModel::RequestedPresenceRole:
return mPriv->mAccount->requestedPresence().status();
case AccountsModel::RequestedPresenceTypeRole:
return mPriv->mAccount->requestedPresence().type();
case AccountsModel::RequestedPresenceStatusMessageRole:
return mPriv->mAccount->requestedPresence().statusMessage();
case AccountsModel::ConnectionStatusRole:
return mPriv->mAccount->connectionStatus();
case AccountsModel::ConnectionStatusReasonRole:
return mPriv->mAccount->connectionStatusReason();
default:
return QVariant();
}
}
bool AccountsModelItem::setData(int role, const QVariant &value)
{
switch (role) {
case AccountsModel::EnabledRole:
setEnabled(value.toBool());
return true;
case AccountsModel::RequestedPresenceRole:
mPriv->setStatus(value.toString());
return true;
case AccountsModel::RequestedPresenceStatusMessageRole:
mPriv->setStatusMessage(value.toString());
return true;
case AccountsModel::NicknameRole:
setNickname(value.toString());
return true;
default:
return false;
}
}
Tp::AccountPtr AccountsModelItem::account() const
{
return mPriv->mAccount;
}
void AccountsModelItem::setEnabled(bool value)
{
mPriv->mAccount->setEnabled(value);
}
void AccountsModelItem::setNickname(const QString &value)
{
mPriv->mAccount->setNickname(value);
}
void AccountsModelItem::setAutomaticPresence(int type, const QString &status, const QString &statusMessage)
{
Tp::Presence presence;
presence.setStatus((Tp::ConnectionPresenceType) type, status, statusMessage);
mPriv->mAccount->setAutomaticPresence(presence);
}
void AccountsModelItem::setRequestedPresence(int type, const QString &status, const QString &statusMessage)
{
Tp::Presence presence;
presence.setStatus((Tp::ConnectionPresenceType) type, status, statusMessage);
mPriv->mAccount->setRequestedPresence(presence);
}
void AccountsModelItem::onRemoved()
{
int index = parent()->indexOf(this);
emit childrenRemoved(parent(), index, index);
}
void AccountsModelItem::onChanged()
{
emit changed(this);
}
void AccountsModelItem::onContactsChanged(const Tp::Contacts &addedContacts,
const Tp::Contacts &removedContacts)
{
foreach (const Tp::ContactPtr &contact, removedContacts) {
for (int i = 0; i < size(); ++i) {
ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i));
if (item->contact() == contact) {
emit childrenRemoved(this, i, i);
break;
}
}
}
// get the list of contact ids in the children
QStringList idList;
int numElems = size();
for (int i = 0; i < numElems; ++i) {
ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i));
if (item) {
idList.append(item->contact()->id());
}
}
QList<TreeNode *> newNodes;
foreach (const Tp::ContactPtr &contact, addedContacts) {
if (!idList.contains(contact->id())) {
newNodes.append(new ContactModelItem(contact));
}
}
emit childrenAdded(this, newNodes);
}
void AccountsModelItem::onStatusChanged(Tp::ConnectionStatus status)
{
emit connectionStatusChanged(mPriv->mAccount->uniqueIdentifier(), status);
}
void AccountsModelItem::onConnectionChanged(const Tp::ConnectionPtr &connection)
{
onChanged();
// if the connection is invalid or disconnected, clear the contacts list
if (connection.isNull()
|| !connection->isValid()
|| connection->status() == Tp::ConnectionStatusDisconnected) {
emit childrenRemoved(this, 0, size() - 1);
return;
}
Tp::ContactManagerPtr manager = connection->contactManager();
connect(manager.data(),
SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts,
Tp::Channel::GroupMemberChangeDetails)),
SLOT(onContactsChanged(Tp::Contacts,Tp::Contacts)));
clearContacts();
addKnownContacts();
}
void AccountsModelItem::clearContacts()
{
if (!mPriv->mAccount->connection().isNull() &&
mPriv->mAccount->connection()->isValid()) {
Tp::ContactManagerPtr manager = mPriv->mAccount->connection()->contactManager();
Tp::Contacts contacts = manager->allKnownContacts();
// remove the items no longer present
for (int i = 0; i < size(); ++i) {
bool exists = false;
ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i));
if (item) {
Tp::ContactPtr itemContact = item->contact();
if (contacts.contains(itemContact)) {
exists = true;
}
}
if (!exists) {
emit childrenRemoved(this, i, i);
}
}
}
}
void AccountsModelItem::addKnownContacts()
{
// reload the known contacts if it has a connection
QList<TreeNode *> newNodes;
if (!mPriv->mAccount->connection().isNull() &&
mPriv->mAccount->connection()->isValid()) {
Tp::ContactManagerPtr manager = mPriv->mAccount->connection()->contactManager();
Tp::Contacts contacts = manager->allKnownContacts();
// get the list of contact ids in the children
QStringList idList;
int numElems = size();
for (int i = 0; i < numElems; ++i) {
ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i));
if (item) {
idList.append(item->contact()->id());
}
}
// only add the contact item if it is new
foreach (const Tp::ContactPtr &contact, contacts) {
if (!idList.contains(contact->id())) {
newNodes.append(new ContactModelItem(contact));
}
}
}
if (newNodes.count() > 0) {
emit childrenAdded(this, newNodes);
}
}
}
<commit_msg>Only notify new contacts if there is any<commit_after>/*
* This file is part of TelepathyQt4Yell Models
*
* Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4Yell/Models/AccountsModelItem>
#include "TelepathyQt4Yell/Models/_gen/accounts-model-item.moc.hpp"
#include <TelepathyQt4Yell/Models/AccountsModel>
#include <TelepathyQt4Yell/Models/AvatarImageProvider>
#include <TelepathyQt4Yell/Models/ContactModelItem>
#include <TelepathyQt4/Account>
#include <TelepathyQt4/ContactManager>
namespace Tpy
{
struct TELEPATHY_QT4_YELL_MODELS_NO_EXPORT AccountsModelItem::Private
{
Private(const Tp::AccountPtr &account)
: mAccount(account)
{
}
void setStatus(const QString &value);
void setStatusMessage(const QString &value);
Tp::AccountPtr mAccount;
};
void AccountsModelItem::Private::setStatus(const QString &value)
{
Tp::Presence presence = mAccount->currentPresence().barePresence();
presence.setStatus(Tp::ConnectionPresenceTypeUnset, value, QString());
mAccount->setRequestedPresence(presence);
}
void AccountsModelItem::Private::setStatusMessage(const QString &value)
{
Tp::Presence presence = mAccount->currentPresence().barePresence();
presence.setStatus(Tp::ConnectionPresenceTypeUnset, QString(), value);
mAccount->setRequestedPresence(presence);
}
AccountsModelItem::AccountsModelItem(const Tp::AccountPtr &account)
: mPriv(new Private(account))
{
if (!mPriv->mAccount->connection().isNull()) {
Tp::ContactManagerPtr manager = account->connection()->contactManager();
connect(manager.data(),
SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts,
Tp::Channel::GroupMemberChangeDetails)),
SLOT(onContactsChanged(Tp::Contacts,Tp::Contacts)));
}
connect(mPriv->mAccount.data(),
SIGNAL(removed()),
SLOT(onRemoved()));
connect(mPriv->mAccount.data(),
SIGNAL(serviceNameChanged(QString)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(profileChanged(Tp::ProfilePtr)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(iconNameChanged(QString)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(nicknameChanged(QString)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(normalizedNameChanged(QString)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(validityChanged(bool)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(stateChanged(bool)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(capabilitiesChanged(Tp::ConnectionCapabilities)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(connectsAutomaticallyPropertyChanged(bool)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(parametersChanged(QVariantMap)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(changingPresence(bool)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(automaticPresenceChanged(Tp::Presence)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(currentPresenceChanged(Tp::Presence)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(requestedPresenceChanged(Tp::Presence)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(onlinenessChanged(bool)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(avatarChanged(Tp::Avatar)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(onlinenessChanged(bool)),
SLOT(onChanged()));
connect(mPriv->mAccount.data(),
SIGNAL(connectionStatusChanged(Tp::ConnectionStatus)),
SLOT(onStatusChanged(Tp::ConnectionStatus)));
connect(mPriv->mAccount.data(),
SIGNAL(connectionChanged(Tp::ConnectionPtr)),
SLOT(onConnectionChanged(Tp::ConnectionPtr)));
}
AccountsModelItem::~AccountsModelItem()
{
delete mPriv;
}
QVariant AccountsModelItem::data(int role) const
{
switch (role) {
case AccountsModel::ItemRole:
return QVariant::fromValue(
const_cast<QObject *>(
static_cast<const QObject *>(this)));
case AccountsModel::IdRole:
return mPriv->mAccount->uniqueIdentifier();
case AccountsModel::AvatarRole:
return AvatarImageProvider::urlFor(mPriv->mAccount);
case AccountsModel::ValidRole:
return mPriv->mAccount->isValid();
case AccountsModel::EnabledRole:
return mPriv->mAccount->isEnabled();
case AccountsModel::ConnectionManagerNameRole:
return mPriv->mAccount->cmName();
case AccountsModel::ProtocolNameRole:
return mPriv->mAccount->protocolName();
case AccountsModel::DisplayNameRole:
case Qt::DisplayRole:
return mPriv->mAccount->displayName();
case AccountsModel::IconRole:
return mPriv->mAccount->iconName();
case AccountsModel::NicknameRole:
return mPriv->mAccount->nickname();
case AccountsModel::ConnectsAutomaticallyRole:
return mPriv->mAccount->connectsAutomatically();
case AccountsModel::ChangingPresenceRole:
return mPriv->mAccount->isChangingPresence();
case AccountsModel::AutomaticPresenceRole:
return mPriv->mAccount->automaticPresence().status();
case AccountsModel::AutomaticPresenceTypeRole:
return mPriv->mAccount->automaticPresence().type();
case AccountsModel::AutomaticPresenceStatusMessageRole:
return mPriv->mAccount->automaticPresence().statusMessage();
case AccountsModel::CurrentPresenceRole:
return mPriv->mAccount->currentPresence().status();
case AccountsModel::CurrentPresenceTypeRole:
return mPriv->mAccount->currentPresence().type();
case AccountsModel::CurrentPresenceStatusMessageRole:
return mPriv->mAccount->currentPresence().statusMessage();
case AccountsModel::RequestedPresenceRole:
return mPriv->mAccount->requestedPresence().status();
case AccountsModel::RequestedPresenceTypeRole:
return mPriv->mAccount->requestedPresence().type();
case AccountsModel::RequestedPresenceStatusMessageRole:
return mPriv->mAccount->requestedPresence().statusMessage();
case AccountsModel::ConnectionStatusRole:
return mPriv->mAccount->connectionStatus();
case AccountsModel::ConnectionStatusReasonRole:
return mPriv->mAccount->connectionStatusReason();
default:
return QVariant();
}
}
bool AccountsModelItem::setData(int role, const QVariant &value)
{
switch (role) {
case AccountsModel::EnabledRole:
setEnabled(value.toBool());
return true;
case AccountsModel::RequestedPresenceRole:
mPriv->setStatus(value.toString());
return true;
case AccountsModel::RequestedPresenceStatusMessageRole:
mPriv->setStatusMessage(value.toString());
return true;
case AccountsModel::NicknameRole:
setNickname(value.toString());
return true;
default:
return false;
}
}
Tp::AccountPtr AccountsModelItem::account() const
{
return mPriv->mAccount;
}
void AccountsModelItem::setEnabled(bool value)
{
mPriv->mAccount->setEnabled(value);
}
void AccountsModelItem::setNickname(const QString &value)
{
mPriv->mAccount->setNickname(value);
}
void AccountsModelItem::setAutomaticPresence(int type, const QString &status, const QString &statusMessage)
{
Tp::Presence presence;
presence.setStatus((Tp::ConnectionPresenceType) type, status, statusMessage);
mPriv->mAccount->setAutomaticPresence(presence);
}
void AccountsModelItem::setRequestedPresence(int type, const QString &status, const QString &statusMessage)
{
Tp::Presence presence;
presence.setStatus((Tp::ConnectionPresenceType) type, status, statusMessage);
mPriv->mAccount->setRequestedPresence(presence);
}
void AccountsModelItem::onRemoved()
{
int index = parent()->indexOf(this);
emit childrenRemoved(parent(), index, index);
}
void AccountsModelItem::onChanged()
{
emit changed(this);
}
void AccountsModelItem::onContactsChanged(const Tp::Contacts &addedContacts,
const Tp::Contacts &removedContacts)
{
foreach (const Tp::ContactPtr &contact, removedContacts) {
for (int i = 0; i < size(); ++i) {
ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i));
if (item->contact() == contact) {
emit childrenRemoved(this, i, i);
break;
}
}
}
// get the list of contact ids in the children
QStringList idList;
int numElems = size();
for (int i = 0; i < numElems; ++i) {
ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i));
if (item) {
idList.append(item->contact()->id());
}
}
QList<TreeNode *> newNodes;
foreach (const Tp::ContactPtr &contact, addedContacts) {
if (!idList.contains(contact->id())) {
newNodes.append(new ContactModelItem(contact));
}
}
if (newNodes.count()) {
emit childrenAdded(this, newNodes);
}
}
void AccountsModelItem::onStatusChanged(Tp::ConnectionStatus status)
{
emit connectionStatusChanged(mPriv->mAccount->uniqueIdentifier(), status);
}
void AccountsModelItem::onConnectionChanged(const Tp::ConnectionPtr &connection)
{
onChanged();
// if the connection is invalid or disconnected, clear the contacts list
if (connection.isNull()
|| !connection->isValid()
|| connection->status() == Tp::ConnectionStatusDisconnected) {
emit childrenRemoved(this, 0, size() - 1);
return;
}
Tp::ContactManagerPtr manager = connection->contactManager();
connect(manager.data(),
SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts,
Tp::Channel::GroupMemberChangeDetails)),
SLOT(onContactsChanged(Tp::Contacts,Tp::Contacts)));
clearContacts();
addKnownContacts();
}
void AccountsModelItem::clearContacts()
{
if (!mPriv->mAccount->connection().isNull() &&
mPriv->mAccount->connection()->isValid()) {
Tp::ContactManagerPtr manager = mPriv->mAccount->connection()->contactManager();
Tp::Contacts contacts = manager->allKnownContacts();
// remove the items no longer present
for (int i = 0; i < size(); ++i) {
bool exists = false;
ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i));
if (item) {
Tp::ContactPtr itemContact = item->contact();
if (contacts.contains(itemContact)) {
exists = true;
}
}
if (!exists) {
emit childrenRemoved(this, i, i);
}
}
}
}
void AccountsModelItem::addKnownContacts()
{
// reload the known contacts if it has a connection
QList<TreeNode *> newNodes;
if (!mPriv->mAccount->connection().isNull() &&
mPriv->mAccount->connection()->isValid()) {
Tp::ContactManagerPtr manager = mPriv->mAccount->connection()->contactManager();
Tp::Contacts contacts = manager->allKnownContacts();
// get the list of contact ids in the children
QStringList idList;
int numElems = size();
for (int i = 0; i < numElems; ++i) {
ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i));
if (item) {
idList.append(item->contact()->id());
}
}
// only add the contact item if it is new
foreach (const Tp::ContactPtr &contact, contacts) {
if (!idList.contains(contact->id())) {
newNodes.append(new ContactModelItem(contact));
}
}
}
if (newNodes.count() > 0) {
emit childrenAdded(this, newNodes);
}
}
}
<|endoftext|> |
<commit_before>#include "core.h"
#include "llvm-c/Target.h"
#include "llvm/Support/Host.h"
#include "llvm-c/TargetMachine.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/IR/Type.h"
#include <cstdio>
#include <cstring>
namespace llvm {
inline LLVMTargetLibraryInfoRef wrap(TargetLibraryInfo *TLI) {
return reinterpret_cast<LLVMTargetLibraryInfoRef>(TLI);
}
inline TargetLibraryInfo *unwrap(LLVMTargetLibraryInfoRef TLI) {
return reinterpret_cast<TargetLibraryInfo*>(TLI);
}
inline Target *unwrap(LLVMTargetRef T) {
return reinterpret_cast<Target*>(T);
}
inline LLVMTargetMachineRef wrap(TargetMachine *TM) {
return reinterpret_cast<LLVMTargetMachineRef>(TM);
}
}
extern "C" {
API_EXPORT(void)
LLVMPY_GetDefaultTargetTriple(const char **Out) {
// Should we use getProcessTriple() instead?
*Out = LLVMPY_CreateString(llvm::sys::getDefaultTargetTriple().c_str());
}
API_EXPORT(void)
LLVMPY_GetHostCPUName(const char **Out) {
*Out = LLVMPY_CreateString(llvm::sys::getHostCPUName().data());
}
API_EXPORT(int)
LLVMPY_GetTripleObjectFormat(const char *tripleStr)
{
return llvm::Triple(tripleStr).getObjectFormat();
}
API_EXPORT(LLVMTargetDataRef)
LLVMPY_CreateTargetData(const char *StringRep)
{
return LLVMCreateTargetData(StringRep);
}
API_EXPORT(void)
LLVMPY_AddTargetData(LLVMTargetDataRef TD,
LLVMPassManagerRef PM)
{
LLVMAddTargetData(TD, PM);
}
//// Nothing is creating a TargetLibraryInfo
// void
// LLVMPY_AddTargetLibraryInfo(LLVMTargetLibraryInfoRef TLI,
// LLVMPassManagerRef PM)
// {
// LLVMAddTargetLibraryInfo(TLI, PM);
// }
API_EXPORT(void)
LLVMPY_CopyStringRepOfTargetData(LLVMTargetDataRef TD, char** Out)
{
*Out = LLVMCopyStringRepOfTargetData(TD);
}
API_EXPORT(void)
LLVMPY_DisposeTargetData(LLVMTargetDataRef TD)
{
LLVMDisposeTargetData(TD);
}
API_EXPORT(long long)
LLVMPY_ABISizeOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty)
{
return (long long) LLVMABISizeOfType(TD, Ty);
}
API_EXPORT(long long)
LLVMPY_ABISizeOfElementType(LLVMTargetDataRef TD, LLVMTypeRef Ty)
{
llvm::Type *tp = llvm::unwrap(Ty);
if (!tp->isPointerTy())
return -1;
tp = tp->getSequentialElementType();
return (long long) LLVMABISizeOfType(TD, llvm::wrap(tp));
}
API_EXPORT(long long)
LLVMPY_ABIAlignmentOfElementType(LLVMTargetDataRef TD, LLVMTypeRef Ty)
{
llvm::Type *tp = llvm::unwrap(Ty);
if (!tp->isPointerTy())
return -1;
tp = tp->getSequentialElementType();
return (long long) LLVMABIAlignmentOfType(TD, llvm::wrap(tp));
}
API_EXPORT(LLVMTargetRef)
LLVMPY_GetTargetFromTriple(const char *Triple, const char **ErrOut)
{
char *ErrorMessage;
LLVMTargetRef T;
if (LLVMGetTargetFromTriple(Triple, &T, &ErrorMessage)) {
*ErrOut = LLVMPY_CreateString(ErrorMessage);
LLVMDisposeMessage(ErrorMessage);
return NULL;
}
return T;
}
API_EXPORT(const char *)
LLVMPY_GetTargetName(LLVMTargetRef T)
{
return LLVMGetTargetName(T);
}
API_EXPORT(const char *)
LLVMPY_GetTargetDescription(LLVMTargetRef T)
{
return LLVMGetTargetDescription(T);
}
API_EXPORT(LLVMTargetMachineRef)
LLVMPY_CreateTargetMachine(LLVMTargetRef T,
const char *Triple,
const char *CPU,
const char *Features,
int OptLevel,
const char *RelocModel,
const char *CodeModel,
int EmitJITDebug,
int PrintMC)
{
using namespace llvm;
CodeGenOpt::Level cgol;
switch(OptLevel) {
case 0:
cgol = CodeGenOpt::None;
break;
case 1:
cgol = CodeGenOpt::Less;
break;
case 3:
cgol = CodeGenOpt::Aggressive;
break;
case 2:
default:
cgol = CodeGenOpt::Default;
}
CodeModel::Model cm;
std::string cms(CodeModel);
if (cms == "jitdefault")
cm = CodeModel::JITDefault;
else if (cms == "small")
cm = CodeModel::Small;
else if (cms == "kernel")
cm = CodeModel::Kernel;
else if (cms == "medium")
cm = CodeModel::Medium;
else if (cms == "large")
cm = CodeModel::Large;
else
cm = CodeModel::Default;
Reloc::Model rm;
std::string rms(RelocModel);
if (rms == "static")
rm = Reloc::Static;
else if (rms == "pic")
rm = Reloc::PIC_;
else if (rms == "dynamicnopic")
rm = Reloc::DynamicNoPIC;
else
rm = Reloc::Default;
TargetOptions opt;
// opt.JITEmitDebugInfo = EmitJITDebug;
opt.PrintMachineCode = PrintMC;
return wrap(unwrap(T)->createTargetMachine(Triple, CPU, Features, opt,
rm, cm, cgol));
}
API_EXPORT(void)
LLVMPY_DisposeTargetMachine(LLVMTargetMachineRef TM)
{
return LLVMDisposeTargetMachine(TM);
}
API_EXPORT(void)
LLVMPY_GetTargetMachineTriple(LLVMTargetMachineRef TM, const char **Out)
{
// result is already strdup()ed by LLVMGetTargetMachineTriple
*Out = LLVMGetTargetMachineTriple(TM);
}
API_EXPORT(LLVMMemoryBufferRef)
LLVMPY_TargetMachineEmitToMemory (
LLVMTargetMachineRef TM,
LLVMModuleRef M,
int use_object,
const char ** ErrOut
)
{
LLVMCodeGenFileType filetype = LLVMAssemblyFile;
if (use_object) filetype = LLVMObjectFile;
char *ErrorMessage;
LLVMMemoryBufferRef BufOut;
int err = LLVMTargetMachineEmitToMemoryBuffer(TM, M, filetype,
&ErrorMessage,
&BufOut);
if (err) {
*ErrOut = LLVMPY_CreateString(ErrorMessage);
LLVMDisposeMessage(ErrorMessage);
return NULL;
}
return BufOut;
}
API_EXPORT(LLVMTargetDataRef)
LLVMPY_GetTargetMachineData(LLVMTargetMachineRef TM)
{
return LLVMGetTargetMachineData(TM);
}
API_EXPORT(void)
LLVMPY_AddAnalysisPasses(
LLVMTargetMachineRef TM,
LLVMPassManagerRef PM
)
{
LLVMAddAnalysisPasses(TM, PM);
}
API_EXPORT(const void*)
LLVMPY_GetBufferStart(LLVMMemoryBufferRef MB)
{
return LLVMGetBufferStart(MB);
}
API_EXPORT(size_t)
LLVMPY_GetBufferSize(LLVMMemoryBufferRef MB)
{
return LLVMGetBufferSize(MB);
}
API_EXPORT(void)
LLVMPY_DisposeMemoryBuffer(LLVMMemoryBufferRef MB)
{
return LLVMDisposeMemoryBuffer(MB);
}
/*
If needed:
explicit TargetLibraryInfoWrapperPass(const Triple &T);
void LLVMAddTargetLibraryInfo(LLVMTargetLibraryInfoRef TLI,
LLVMPassManagerRef PM) {
unwrap(PM)->add(new TargetLibraryInfoWrapperPass(*unwrap(TLI)));
}
*/
#if 0
API_EXPORT(LLVMTargetLibraryInfoRef)
LLVMPY_CreateTargetLibraryInfo(const char *Triple)
{
return llvm::wrap(new llvm::TargetLibraryInfo(llvm::Triple(Triple)));
}
API_EXPORT(void)
LLVMPY_DisposeTargetLibraryInfo(LLVMTargetLibraryInfoRef TLI)
{
delete llvm::unwrap(TLI);
}
API_EXPORT(void)
LLVMPY_AddTargetLibraryInfo(
LLVMTargetLibraryInfoRef TLI,
LLVMPassManagerRef PM
)
{
LLVMAddTargetLibraryInfo(TLI, PM);
}
API_EXPORT(void)
LLVMPY_DisableAllBuiltins(LLVMTargetLibraryInfoRef TLI)
{
llvm::unwrap(TLI)->disableAllFunctions();
}
API_EXPORT(int)
LLVMPY_GetLibFunc(LLVMTargetLibraryInfoRef TLI, const char *Name, int *OutF)
{
llvm::LibFunc::Func F;
if (llvm::unwrap(TLI)->getLibFunc(Name, F)) {
/* Ok */
*OutF = F;
return 1;
} else {
/* Failed */
return 0;
}
}
API_EXPORT(void)
LLVMPY_SetUnavailableLibFunc(LLVMTargetLibraryInfoRef TLI, int F)
{
llvm::unwrap(TLI)->setUnavailable((llvm::LibFunc::Func)F);
}
#endif
} // end extern "C"
<commit_msg>Remove dead code<commit_after>#include "core.h"
#include "llvm-c/Target.h"
#include "llvm/Support/Host.h"
#include "llvm-c/TargetMachine.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/IR/Type.h"
#include <cstdio>
#include <cstring>
namespace llvm {
inline LLVMTargetLibraryInfoRef wrap(TargetLibraryInfo *TLI) {
return reinterpret_cast<LLVMTargetLibraryInfoRef>(TLI);
}
inline TargetLibraryInfo *unwrap(LLVMTargetLibraryInfoRef TLI) {
return reinterpret_cast<TargetLibraryInfo*>(TLI);
}
inline Target *unwrap(LLVMTargetRef T) {
return reinterpret_cast<Target*>(T);
}
inline LLVMTargetMachineRef wrap(TargetMachine *TM) {
return reinterpret_cast<LLVMTargetMachineRef>(TM);
}
}
extern "C" {
API_EXPORT(void)
LLVMPY_GetDefaultTargetTriple(const char **Out) {
// Should we use getProcessTriple() instead?
*Out = LLVMPY_CreateString(llvm::sys::getDefaultTargetTriple().c_str());
}
API_EXPORT(void)
LLVMPY_GetHostCPUName(const char **Out) {
*Out = LLVMPY_CreateString(llvm::sys::getHostCPUName().data());
}
API_EXPORT(int)
LLVMPY_GetTripleObjectFormat(const char *tripleStr)
{
return llvm::Triple(tripleStr).getObjectFormat();
}
API_EXPORT(LLVMTargetDataRef)
LLVMPY_CreateTargetData(const char *StringRep)
{
return LLVMCreateTargetData(StringRep);
}
API_EXPORT(void)
LLVMPY_AddTargetData(LLVMTargetDataRef TD,
LLVMPassManagerRef PM)
{
LLVMAddTargetData(TD, PM);
}
//// Nothing is creating a TargetLibraryInfo
// void
// LLVMPY_AddTargetLibraryInfo(LLVMTargetLibraryInfoRef TLI,
// LLVMPassManagerRef PM)
// {
// LLVMAddTargetLibraryInfo(TLI, PM);
// }
API_EXPORT(void)
LLVMPY_CopyStringRepOfTargetData(LLVMTargetDataRef TD, char** Out)
{
*Out = LLVMCopyStringRepOfTargetData(TD);
}
API_EXPORT(void)
LLVMPY_DisposeTargetData(LLVMTargetDataRef TD)
{
LLVMDisposeTargetData(TD);
}
API_EXPORT(long long)
LLVMPY_ABISizeOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty)
{
return (long long) LLVMABISizeOfType(TD, Ty);
}
API_EXPORT(long long)
LLVMPY_ABISizeOfElementType(LLVMTargetDataRef TD, LLVMTypeRef Ty)
{
llvm::Type *tp = llvm::unwrap(Ty);
if (!tp->isPointerTy())
return -1;
tp = tp->getSequentialElementType();
return (long long) LLVMABISizeOfType(TD, llvm::wrap(tp));
}
API_EXPORT(long long)
LLVMPY_ABIAlignmentOfElementType(LLVMTargetDataRef TD, LLVMTypeRef Ty)
{
llvm::Type *tp = llvm::unwrap(Ty);
if (!tp->isPointerTy())
return -1;
tp = tp->getSequentialElementType();
return (long long) LLVMABIAlignmentOfType(TD, llvm::wrap(tp));
}
API_EXPORT(LLVMTargetRef)
LLVMPY_GetTargetFromTriple(const char *Triple, const char **ErrOut)
{
char *ErrorMessage;
LLVMTargetRef T;
if (LLVMGetTargetFromTriple(Triple, &T, &ErrorMessage)) {
*ErrOut = LLVMPY_CreateString(ErrorMessage);
LLVMDisposeMessage(ErrorMessage);
return NULL;
}
return T;
}
API_EXPORT(const char *)
LLVMPY_GetTargetName(LLVMTargetRef T)
{
return LLVMGetTargetName(T);
}
API_EXPORT(const char *)
LLVMPY_GetTargetDescription(LLVMTargetRef T)
{
return LLVMGetTargetDescription(T);
}
API_EXPORT(LLVMTargetMachineRef)
LLVMPY_CreateTargetMachine(LLVMTargetRef T,
const char *Triple,
const char *CPU,
const char *Features,
int OptLevel,
const char *RelocModel,
const char *CodeModel,
int EmitJITDebug,
int PrintMC)
{
using namespace llvm;
CodeGenOpt::Level cgol;
switch(OptLevel) {
case 0:
cgol = CodeGenOpt::None;
break;
case 1:
cgol = CodeGenOpt::Less;
break;
case 3:
cgol = CodeGenOpt::Aggressive;
break;
case 2:
default:
cgol = CodeGenOpt::Default;
}
CodeModel::Model cm;
std::string cms(CodeModel);
if (cms == "jitdefault")
cm = CodeModel::JITDefault;
else if (cms == "small")
cm = CodeModel::Small;
else if (cms == "kernel")
cm = CodeModel::Kernel;
else if (cms == "medium")
cm = CodeModel::Medium;
else if (cms == "large")
cm = CodeModel::Large;
else
cm = CodeModel::Default;
Reloc::Model rm;
std::string rms(RelocModel);
if (rms == "static")
rm = Reloc::Static;
else if (rms == "pic")
rm = Reloc::PIC_;
else if (rms == "dynamicnopic")
rm = Reloc::DynamicNoPIC;
else
rm = Reloc::Default;
TargetOptions opt;
// opt.JITEmitDebugInfo = EmitJITDebug;
opt.PrintMachineCode = PrintMC;
return wrap(unwrap(T)->createTargetMachine(Triple, CPU, Features, opt,
rm, cm, cgol));
}
API_EXPORT(void)
LLVMPY_DisposeTargetMachine(LLVMTargetMachineRef TM)
{
return LLVMDisposeTargetMachine(TM);
}
API_EXPORT(void)
LLVMPY_GetTargetMachineTriple(LLVMTargetMachineRef TM, const char **Out)
{
// result is already strdup()ed by LLVMGetTargetMachineTriple
*Out = LLVMGetTargetMachineTriple(TM);
}
API_EXPORT(LLVMMemoryBufferRef)
LLVMPY_TargetMachineEmitToMemory (
LLVMTargetMachineRef TM,
LLVMModuleRef M,
int use_object,
const char ** ErrOut
)
{
LLVMCodeGenFileType filetype = LLVMAssemblyFile;
if (use_object) filetype = LLVMObjectFile;
char *ErrorMessage;
LLVMMemoryBufferRef BufOut;
int err = LLVMTargetMachineEmitToMemoryBuffer(TM, M, filetype,
&ErrorMessage,
&BufOut);
if (err) {
*ErrOut = LLVMPY_CreateString(ErrorMessage);
LLVMDisposeMessage(ErrorMessage);
return NULL;
}
return BufOut;
}
API_EXPORT(LLVMTargetDataRef)
LLVMPY_GetTargetMachineData(LLVMTargetMachineRef TM)
{
return LLVMGetTargetMachineData(TM);
}
API_EXPORT(void)
LLVMPY_AddAnalysisPasses(
LLVMTargetMachineRef TM,
LLVMPassManagerRef PM
)
{
LLVMAddAnalysisPasses(TM, PM);
}
API_EXPORT(const void*)
LLVMPY_GetBufferStart(LLVMMemoryBufferRef MB)
{
return LLVMGetBufferStart(MB);
}
API_EXPORT(size_t)
LLVMPY_GetBufferSize(LLVMMemoryBufferRef MB)
{
return LLVMGetBufferSize(MB);
}
API_EXPORT(void)
LLVMPY_DisposeMemoryBuffer(LLVMMemoryBufferRef MB)
{
return LLVMDisposeMemoryBuffer(MB);
}
/*
If needed:
explicit TargetLibraryInfoWrapperPass(const Triple &T);
void LLVMAddTargetLibraryInfo(LLVMTargetLibraryInfoRef TLI,
LLVMPassManagerRef PM) {
unwrap(PM)->add(new TargetLibraryInfoWrapperPass(*unwrap(TLI)));
}
*/
} // end extern "C"
<|endoftext|> |
<commit_before>/* Siconos-Kernel, Copyright INRIA 2005-2010.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* Siconos is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY ory 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 Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr
*/
#include "GenericMechanical.hpp"
#include "FrictionContactXML.hpp"
#include "Topology.hpp"
#include "Simulation.hpp"
#include "Model.hpp"
#include "NonSmoothDynamicalSystem.hpp"
#include "NewtonImpactFrictionNSL.hpp"
using namespace std;
using namespace RELATION;
//#define GMP_DEBUG
GenericMechanical::GenericMechanical(int FC3D_Solver_Id):
LinearOSNS()
{
_MStorageType = SICONOS_SPARSE;
_pnumerics_GMP = buildEmptyGenericMechanicalProblem();
genericMechnicalProblem_setDefaultSolverOptions(&*_numerics_solver_options, FC3D_Solver_Id);
}
void GenericMechanical::initialize(SP::Simulation sim)
{
// - Checks memory allocation for main variables (M,q,w,z)
// - Formalizes the problem if the topology is time-invariant
// This function performs all steps that are time-invariant
// General initialize for OneStepNSProblem
LinearOSNS::initialize(sim);
}
void GenericMechanical::computeDiagonalUnitaryBlock(const UnitaryRelationsGraph::VDescriptor& vd)
{
SP::UnitaryRelationsGraph indexSet = simulation()->indexSet(levelMin());
//bool isTimeInvariant = simulation()->model()->nonSmoothDynamicalSystem()->topology()->isTimeInvariant();
/*Build the corresponding numerics problems*/
SP::DynamicalSystem DS1 = indexSet->properties(vd).source;
SP::DynamicalSystem DS2 = indexSet->properties(vd).target;
SP::UnitaryRelation UR = indexSet->bundle(vd);
#ifdef GMP_DEBUG
printf("GenericMechanical::computeUnitaryBlock: add problem of type ");
#endif
if (!_hasBeUpdated)
{
int size = UR->getNonSmoothLawSize();
if (Type::value(*(UR->interaction()->nonSmoothLaw()))
== Type::EqualityConditionNSL)
{
addProblem(_pnumerics_GMP, SICONOS_NUMERICS_PROBLEM_EQUALITY, size);
#ifdef GMP_DEBUG
printf(" Type::EqualityConditionNSL\n");
#endif
//pAux->size= UR->getNonSmoothLawSize();
}
else if (Type::value(*(UR->interaction()->nonSmoothLaw()))
== Type::NewtonImpactNSL)
{
addProblem(_pnumerics_GMP, SICONOS_NUMERICS_PROBLEM_LCP, size);
#ifdef GMP_DEBUG
printf(" Type::NewtonImpactNSL\n");
#endif
}
else if (Type::value(*(UR->interaction()->nonSmoothLaw()))
== Type::NewtonImpactFrictionNSL)
{
FrictionContactProblem * pAux =
(FrictionContactProblem *)addProblem(_pnumerics_GMP, SICONOS_NUMERICS_PROBLEM_FC3D, size);
SP::NewtonImpactFrictionNSL nsLaw =
boost::static_pointer_cast<NewtonImpactFrictionNSL> (UR->interaction()->nonSmoothLaw());
pAux->dimension = 3;
pAux->numberOfContacts = 1;
*(pAux->mu) = nsLaw->mu();
#ifdef GMP_DEBUG
printf(" Type::NewtonImpactFrictionNSL\n");
#endif
}
else
{
RuntimeException::selfThrow("GenericMechanical::computeDiagonalUnitaryBlock- not yet implemented for that NSLAW type");
}
}
LinearOSNS::computeDiagonalUnitaryBlock(vd);
}
void GenericMechanical::computeUnitaryBlock(const UnitaryRelationsGraph::EDescriptor& ed)
{
LinearOSNS::computeUnitaryBlock(ed);
}
int GenericMechanical::compute(double time)
{
int info = 0;
// --- Prepare data for GenericMechanical computing ---
preCompute(time);
_hasBeUpdated = true;
/*
La matrice _M est construite. Ici, il faut construire les
sous-problemes, c'est a dire completer les champs des
NumericsProblem (_mu, _e, _en, les dimentions...). Il faut aussi
remplir la sous matrice M du sous-probleme. Pour cela, on peut
boucler sur les interactions et completer le membres
_numerics_problem.problems[i] and
_numerics_problem.problemsType[i].
*/
//......
// --- Call Numerics driver ---
// Inputs:
// - the problem (M,q ...)
// - the unknowns (z,w)
// - the options for the solver (name, max iteration number ...)
// - the global options for Numerics (verbose mode ...)
if (_sizeOutput != 0)
{
// The GenericMechanical Problem in Numerics format
_pnumerics_GMP->M = &*_M->getNumericsMatrix();
_pnumerics_GMP->q = &*_q->getArray();
// Call Numerics Driver for GenericMechanical
// display();
info = genericMechanical_driver(_pnumerics_GMP,
&*_z->getArray() ,
&*_w->getArray() ,
&*_numerics_solver_options);
//printf("GenericMechanical::compute : R:\n");
//_z->display();
postCompute();
}
else
{
#ifdef GMP_DEBUG
printf("GenericMechanical::compute : sizeoutput is null\n");
#endif
}
return info;
}
void GenericMechanical::display() const
{
cout << "===== " << "Generic mechanical Problem " << endl;
LinearOSNS::display();
}
void GenericMechanical::updateUnitaryBlocks()
{
if (!_hasBeUpdated)
{
// printf("GenericMechanical::updateUnitaryBlocks : must be updated\n");
freeGenericMechanicalProblem(_pnumerics_GMP, NUMERICS_GMP_FREE_GMP);
_pnumerics_GMP = buildEmptyGenericMechanicalProblem();
}
LinearOSNS::updateUnitaryBlocks();
}
void GenericMechanical::computeAllUnitaryBlocks()
{
assert(0);
//printf("GenericMechanical::updateUnitaryBlocks : free and build a new GMP\n");
freeGenericMechanicalProblem(_pnumerics_GMP, NUMERICS_GMP_FREE_GMP);
_pnumerics_GMP = buildEmptyGenericMechanicalProblem();
LinearOSNS::computeAllUnitaryBlocks();
}
GenericMechanical::~GenericMechanical()
{
freeGenericMechanicalProblem(_pnumerics_GMP, NUMERICS_GMP_FREE_GMP);
_pnumerics_GMP = 0;
deleteSolverOptions(&*_numerics_solver_options);
}
<commit_msg>mechnical -> mechanical<commit_after>/* Siconos-Kernel, Copyright INRIA 2005-2010.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* Siconos is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY ory 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 Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr
*/
#include "GenericMechanical.hpp"
#include "FrictionContactXML.hpp"
#include "Topology.hpp"
#include "Simulation.hpp"
#include "Model.hpp"
#include "NonSmoothDynamicalSystem.hpp"
#include "NewtonImpactFrictionNSL.hpp"
using namespace std;
using namespace RELATION;
//#define GMP_DEBUG
GenericMechanical::GenericMechanical(int FC3D_Solver_Id):
LinearOSNS()
{
_MStorageType = SICONOS_SPARSE;
_pnumerics_GMP = buildEmptyGenericMechanicalProblem();
genericMechanicalProblem_setDefaultSolverOptions(&*_numerics_solver_options, FC3D_Solver_Id);
}
void GenericMechanical::initialize(SP::Simulation sim)
{
// - Checks memory allocation for main variables (M,q,w,z)
// - Formalizes the problem if the topology is time-invariant
// This function performs all steps that are time-invariant
// General initialize for OneStepNSProblem
LinearOSNS::initialize(sim);
}
void GenericMechanical::computeDiagonalUnitaryBlock(const UnitaryRelationsGraph::VDescriptor& vd)
{
SP::UnitaryRelationsGraph indexSet = simulation()->indexSet(levelMin());
//bool isTimeInvariant = simulation()->model()->nonSmoothDynamicalSystem()->topology()->isTimeInvariant();
/*Build the corresponding numerics problems*/
SP::DynamicalSystem DS1 = indexSet->properties(vd).source;
SP::DynamicalSystem DS2 = indexSet->properties(vd).target;
SP::UnitaryRelation UR = indexSet->bundle(vd);
#ifdef GMP_DEBUG
printf("GenericMechanical::computeUnitaryBlock: add problem of type ");
#endif
if (!_hasBeUpdated)
{
int size = UR->getNonSmoothLawSize();
if (Type::value(*(UR->interaction()->nonSmoothLaw()))
== Type::EqualityConditionNSL)
{
addProblem(_pnumerics_GMP, SICONOS_NUMERICS_PROBLEM_EQUALITY, size);
#ifdef GMP_DEBUG
printf(" Type::EqualityConditionNSL\n");
#endif
//pAux->size= UR->getNonSmoothLawSize();
}
else if (Type::value(*(UR->interaction()->nonSmoothLaw()))
== Type::NewtonImpactNSL)
{
addProblem(_pnumerics_GMP, SICONOS_NUMERICS_PROBLEM_LCP, size);
#ifdef GMP_DEBUG
printf(" Type::NewtonImpactNSL\n");
#endif
}
else if (Type::value(*(UR->interaction()->nonSmoothLaw()))
== Type::NewtonImpactFrictionNSL)
{
FrictionContactProblem * pAux =
(FrictionContactProblem *)addProblem(_pnumerics_GMP, SICONOS_NUMERICS_PROBLEM_FC3D, size);
SP::NewtonImpactFrictionNSL nsLaw =
boost::static_pointer_cast<NewtonImpactFrictionNSL> (UR->interaction()->nonSmoothLaw());
pAux->dimension = 3;
pAux->numberOfContacts = 1;
*(pAux->mu) = nsLaw->mu();
#ifdef GMP_DEBUG
printf(" Type::NewtonImpactFrictionNSL\n");
#endif
}
else
{
RuntimeException::selfThrow("GenericMechanical::computeDiagonalUnitaryBlock- not yet implemented for that NSLAW type");
}
}
LinearOSNS::computeDiagonalUnitaryBlock(vd);
}
void GenericMechanical::computeUnitaryBlock(const UnitaryRelationsGraph::EDescriptor& ed)
{
LinearOSNS::computeUnitaryBlock(ed);
}
int GenericMechanical::compute(double time)
{
int info = 0;
// --- Prepare data for GenericMechanical computing ---
preCompute(time);
_hasBeUpdated = true;
/*
La matrice _M est construite. Ici, il faut construire les
sous-problemes, c'est a dire completer les champs des
NumericsProblem (_mu, _e, _en, les dimentions...). Il faut aussi
remplir la sous matrice M du sous-probleme. Pour cela, on peut
boucler sur les interactions et completer le membres
_numerics_problem.problems[i] and
_numerics_problem.problemsType[i].
*/
//......
// --- Call Numerics driver ---
// Inputs:
// - the problem (M,q ...)
// - the unknowns (z,w)
// - the options for the solver (name, max iteration number ...)
// - the global options for Numerics (verbose mode ...)
if (_sizeOutput != 0)
{
// The GenericMechanical Problem in Numerics format
_pnumerics_GMP->M = &*_M->getNumericsMatrix();
_pnumerics_GMP->q = &*_q->getArray();
// Call Numerics Driver for GenericMechanical
// display();
info = genericMechanical_driver(_pnumerics_GMP,
&*_z->getArray() ,
&*_w->getArray() ,
&*_numerics_solver_options);
//printf("GenericMechanical::compute : R:\n");
//_z->display();
postCompute();
}
else
{
#ifdef GMP_DEBUG
printf("GenericMechanical::compute : sizeoutput is null\n");
#endif
}
return info;
}
void GenericMechanical::display() const
{
cout << "===== " << "Generic mechanical Problem " << endl;
LinearOSNS::display();
}
void GenericMechanical::updateUnitaryBlocks()
{
if (!_hasBeUpdated)
{
// printf("GenericMechanical::updateUnitaryBlocks : must be updated\n");
freeGenericMechanicalProblem(_pnumerics_GMP, NUMERICS_GMP_FREE_GMP);
_pnumerics_GMP = buildEmptyGenericMechanicalProblem();
}
LinearOSNS::updateUnitaryBlocks();
}
void GenericMechanical::computeAllUnitaryBlocks()
{
assert(0);
//printf("GenericMechanical::updateUnitaryBlocks : free and build a new GMP\n");
freeGenericMechanicalProblem(_pnumerics_GMP, NUMERICS_GMP_FREE_GMP);
_pnumerics_GMP = buildEmptyGenericMechanicalProblem();
LinearOSNS::computeAllUnitaryBlocks();
}
GenericMechanical::~GenericMechanical()
{
freeGenericMechanicalProblem(_pnumerics_GMP, NUMERICS_GMP_FREE_GMP);
_pnumerics_GMP = 0;
deleteSolverOptions(&*_numerics_solver_options);
}
<|endoftext|> |
<commit_before>#pragma once
#include <vector>
#include "acmacs-base/fmt.hh"
#include "acmacs-base/range-v3.hh"
// ----------------------------------------------------------------------
namespace acmacs
{
namespace detail
{
template <typename Key, typename Value> class map_base_t
{
public:
using entry_type = std::pair<Key, Value>;
using const_iterator = typename std::vector<entry_type>::const_iterator;
// map_base_t() = default;
virtual ~map_base_t() = default;
bool empty() const noexcept { return data_.empty(); }
constexpr const auto& data() const noexcept { return data_; }
template <typename Range> void collect(Range&& rng, bool check_result = true)
{
data_ = rng | ranges::to<std::vector>;
sorted_ = false;
if (check_result && data_.size() > 1)
check();
}
template <typename EKey, typename EValue> auto& emplace(EKey&& key, EValue&& value)
{
sorted_ = false;
return data_.emplace_back(std::forward<EKey>(key), std::forward<EValue>(value));
}
protected:
constexpr auto& data() noexcept { return data_; }
// constexpr bool sorted() const noexcept { return sorted_; }
template <typename FindKey> const_iterator find_first(const FindKey& key) const noexcept
{
sort();
return std::lower_bound(std::begin(data_), std::end(data_), key, [](const auto& e1, const auto& k2) { return e1.first < k2; });
}
virtual void check() const {}
void sort() const noexcept
{
if (!sorted_) {
ranges::sort(data_, [](const auto& e1, const auto& e2) { return e1.first < e2.first; });
sorted_ = true;
}
}
private:
mutable std::vector<entry_type> data_;
mutable bool sorted_{false};
};
} // namespace detail
// ----------------------------------------------------------------------
// see seqdb.cc Seqdb::hash_index() for sample usage
template <typename Key, typename Value> class map_with_duplicating_keys_t : public detail::map_base_t<Key, Value>
{
public:
using const_iterator = typename detail::map_base_t<Key, Value>::const_iterator;
template <typename FindKey> std::pair<const_iterator, const_iterator> find(const FindKey& key) const noexcept
{
const auto first = this->find_first(key);
// first may point to the wrong key, if key is not in the map
return {first, std::find_if(first, std::end(this->data()), [&key](const auto& en) { return en.first != key; })};
}
};
// ----------------------------------------------------------------------
class map_with_unique_keys_error : public std::runtime_error
{
public:
using std::runtime_error::runtime_error;
};
// see seqdb.cc Seqdb::seq_id_index() for sample usage
template <typename Key, typename Value> class map_with_unique_keys_t : public detail::map_base_t<Key, Value>
{
public:
using const_iterator = typename detail::map_base_t<Key, Value>::const_iterator;
template <typename FindKey> const Value* find(const FindKey& key) const noexcept
{
if (const auto first = this->find_first(key); first->first == key)
return &first->second;
else
return nullptr;
}
protected:
void check() const override
{
this->sort();
for (auto cur = std::next(std::begin(this->data())); cur != std::end(this->data()); ++cur) {
if (cur->first == std::prev(cur)->first)
throw map_with_unique_keys_error{"duplicating keys within map_with_unique_keys_t"};
}
}
};
// ----------------------------------------------------------------------
template <typename Key, typename Value> class small_map_with_unique_keys_t
{
public:
using entry_type = std::pair<Key, Value>;
using const_iterator = typename std::vector<entry_type>::const_iterator;
small_map_with_unique_keys_t() = default;
// template <typename Iter> small_map_with_unique_keys_t(Iter first, Iter last) : data_(first, last) {}
small_map_with_unique_keys_t(std::initializer_list<entry_type> init) : data_{init} {}
constexpr const auto& data() const noexcept { return data_; }
auto begin() const noexcept { return data_.begin(); }
auto end() const noexcept { return data_.end(); }
auto empty() const noexcept { return data_.empty(); }
auto size() const noexcept { return data_.size(); }
template <typename K> auto find(const K& key) const noexcept
{
return std::find_if(std::begin(data_), std::end(data_), [&key](const auto& en) { return en.first == key; });
}
template <typename K> auto find(const K& key) noexcept
{
return std::find_if(std::begin(data_), std::end(data_), [&key](const auto& en) { return en.first == key; });
}
template <typename K, typename Callback> void find_then(const K& key, Callback callback) const noexcept
{
if (const auto& en = find(key); en != std::end(data_))
callback(en->second);
}
template <typename K> Value& get(const K& key)
{
if (const auto found = find(key); found != std::end(data_))
return found->second;
throw std::out_of_range{fmt::format("acmacs::small_map_with_unique_keys_t::at(): no key: {}", key)};
}
template <typename K> const Value& get(const K& key) const
{
if (const auto found = find(key); found != std::end(data_))
return found->second;
throw std::out_of_range{fmt::format("acmacs::small_map_with_unique_keys_t::at(): no key: {}", key)};
}
template <typename K, typename V> const Value& get_or(const K& key, const V& dflt) const
{
if (const auto found = find(key); found != std::end(data_))
return found->second;
else
return dflt;
}
template <typename K, typename V> auto& emplace_or_replace(const K& key, const V& value)
{
if (auto found = find(key); found != end()) {
found->second = Value{value};
return *found;
}
else
return data_.emplace_back(Key{key}, Value{value});
}
template <typename K, typename V = Value> auto& emplace_not_replace(const K& key, const V& value = V{})
{
if (auto found = find(key); found != end())
return *found;
else
return data_.emplace_back(Key{key}, Value{value});
}
private:
std::vector<entry_type> data_;
}; // small_map_with_unique_keys_t<Key, Value>
} // namespace acmacs
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>map_base_t::sort() made public to allow forcing sorting in the mutli-threaded app (seqdb3 -> acmacs-api)<commit_after>#pragma once
#include <vector>
#include "acmacs-base/fmt.hh"
#include "acmacs-base/range-v3.hh"
// ----------------------------------------------------------------------
namespace acmacs
{
namespace detail
{
template <typename Key, typename Value> class map_base_t
{
public:
using entry_type = std::pair<Key, Value>;
using const_iterator = typename std::vector<entry_type>::const_iterator;
// map_base_t() = default;
virtual ~map_base_t() = default;
bool empty() const noexcept { return data_.empty(); }
constexpr const auto& data() const noexcept { return data_; }
template <typename Range> void collect(Range&& rng, bool check_result = true)
{
data_ = rng | ranges::to<std::vector>;
sorted_ = false;
if (check_result && data_.size() > 1)
check();
}
template <typename EKey, typename EValue> auto& emplace(EKey&& key, EValue&& value)
{
sorted_ = false;
return data_.emplace_back(std::forward<EKey>(key), std::forward<EValue>(value));
}
// public to allow forcing sorting in the mutli-threaded app (seqdb3 -> acmacs-api)
void sort() const noexcept
{
if (!sorted_) {
ranges::sort(data_, [](const auto& e1, const auto& e2) { return e1.first < e2.first; });
sorted_ = true;
}
}
protected:
constexpr auto& data() noexcept { return data_; }
// constexpr bool sorted() const noexcept { return sorted_; }
template <typename FindKey> const_iterator find_first(const FindKey& key) const noexcept
{
sort();
return std::lower_bound(std::begin(data_), std::end(data_), key, [](const auto& e1, const auto& k2) { return e1.first < k2; });
}
virtual void check() const {}
private:
mutable std::vector<entry_type> data_;
mutable bool sorted_{false};
};
} // namespace detail
// ----------------------------------------------------------------------
// see seqdb.cc Seqdb::hash_index() for sample usage
template <typename Key, typename Value> class map_with_duplicating_keys_t : public detail::map_base_t<Key, Value>
{
public:
using const_iterator = typename detail::map_base_t<Key, Value>::const_iterator;
template <typename FindKey> std::pair<const_iterator, const_iterator> find(const FindKey& key) const noexcept
{
const auto first = this->find_first(key);
// first may point to the wrong key, if key is not in the map
return {first, std::find_if(first, std::end(this->data()), [&key](const auto& en) { return en.first != key; })};
}
};
// ----------------------------------------------------------------------
class map_with_unique_keys_error : public std::runtime_error
{
public:
using std::runtime_error::runtime_error;
};
// see seqdb.cc Seqdb::seq_id_index() for sample usage
template <typename Key, typename Value> class map_with_unique_keys_t : public detail::map_base_t<Key, Value>
{
public:
using const_iterator = typename detail::map_base_t<Key, Value>::const_iterator;
template <typename FindKey> const Value* find(const FindKey& key) const noexcept
{
if (const auto first = this->find_first(key); first->first == key)
return &first->second;
else
return nullptr;
}
protected:
void check() const override
{
this->sort();
for (auto cur = std::next(std::begin(this->data())); cur != std::end(this->data()); ++cur) {
if (cur->first == std::prev(cur)->first)
throw map_with_unique_keys_error{"duplicating keys within map_with_unique_keys_t"};
}
}
};
// ----------------------------------------------------------------------
template <typename Key, typename Value> class small_map_with_unique_keys_t
{
public:
using entry_type = std::pair<Key, Value>;
using const_iterator = typename std::vector<entry_type>::const_iterator;
small_map_with_unique_keys_t() = default;
// template <typename Iter> small_map_with_unique_keys_t(Iter first, Iter last) : data_(first, last) {}
small_map_with_unique_keys_t(std::initializer_list<entry_type> init) : data_{init} {}
constexpr const auto& data() const noexcept { return data_; }
auto begin() const noexcept { return data_.begin(); }
auto end() const noexcept { return data_.end(); }
auto empty() const noexcept { return data_.empty(); }
auto size() const noexcept { return data_.size(); }
template <typename K> auto find(const K& key) const noexcept
{
return std::find_if(std::begin(data_), std::end(data_), [&key](const auto& en) { return en.first == key; });
}
template <typename K> auto find(const K& key) noexcept
{
return std::find_if(std::begin(data_), std::end(data_), [&key](const auto& en) { return en.first == key; });
}
template <typename K, typename Callback> void find_then(const K& key, Callback callback) const noexcept
{
if (const auto& en = find(key); en != std::end(data_))
callback(en->second);
}
template <typename K> Value& get(const K& key)
{
if (const auto found = find(key); found != std::end(data_))
return found->second;
throw std::out_of_range{fmt::format("acmacs::small_map_with_unique_keys_t::at(): no key: {}", key)};
}
template <typename K> const Value& get(const K& key) const
{
if (const auto found = find(key); found != std::end(data_))
return found->second;
throw std::out_of_range{fmt::format("acmacs::small_map_with_unique_keys_t::at(): no key: {}", key)};
}
template <typename K, typename V> const Value& get_or(const K& key, const V& dflt) const
{
if (const auto found = find(key); found != std::end(data_))
return found->second;
else
return dflt;
}
template <typename K, typename V> auto& emplace_or_replace(const K& key, const V& value)
{
if (auto found = find(key); found != end()) {
found->second = Value{value};
return *found;
}
else
return data_.emplace_back(Key{key}, Value{value});
}
template <typename K, typename V = Value> auto& emplace_not_replace(const K& key, const V& value = V{})
{
if (auto found = find(key); found != end())
return *found;
else
return data_.emplace_back(Key{key}, Value{value});
}
private:
std::vector<entry_type> data_;
}; // small_map_with_unique_keys_t<Key, Value>
} // namespace acmacs
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>#include "itkNarrowBand.h"
#include <vector.h>
int itkNarrowBandTest (int, char*[])
{
unsigned int i;
typedef unsigned int IndexType;
typedef float DataType;
typedef itk::BandNode<IndexType,DataType> BandNodeType;
typedef itk::NarrowBand<BandNodeType> BandType;
typedef BandType::RegionType RegionType;
BandType::Pointer band = BandType::New();
band->Reserve(100);
//Create nodes
BandNodeType node;
band->SetTotalRadius(10);
band->SetInnerRadius(5);
for(i=0 ; i<20 ; i++)
{
node.m_Data = i*5.0;
node.m_Index = i;
node.m_NodeState = 0;
//Fill the band
band->PushBack(node);
}
std::cout<<"Band size: "<<band->Size()<<std::endl;
//Iterate over the band
typedef BandType::ConstIterator itType;
itType it = band->Begin();
itType itend = band->End();
i= 0;
BandNodeType *tmp;
for( ; it != itend ; it++)
{
std::cout <<"Node "<<i<<std::endl<<"Index: "<<it->m_Index<<" Data: "<<it->m_Data<<std::endl;
i++;
}
//Split the band
std::vector<RegionType> regions;
regions = band->SplitBand(10);
RegionType region;
typedef std::vector<RegionType>::const_iterator regionitType;
regionitType regionsit = regions.begin();
regionitType regionsitend = regions.end();
std::cout<<"Number of regions: "<<regions.size()<<std::endl;
i = 0;
for(; regionsit != regionsitend ; regionsit++)
{
std::cout<<"Region "<<i<<std::endl;
for( ; regions[i].Begin != regions[i].End; regions[i].Begin++)
std::cout<<"Index: "<<regions[i].Begin->m_Index<<" Data: "<<regions[i].Begin->m_Data<<std::endl;
i++;
}
std::cout << "Test Passed. " << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>ERR: vector.h should be vector.<commit_after>#include "itkNarrowBand.h"
#include <vector>
int itkNarrowBandTest (int, char*[])
{
unsigned int i;
typedef unsigned int IndexType;
typedef float DataType;
typedef itk::BandNode<IndexType,DataType> BandNodeType;
typedef itk::NarrowBand<BandNodeType> BandType;
typedef BandType::RegionType RegionType;
BandType::Pointer band = BandType::New();
band->Reserve(100);
//Create nodes
BandNodeType node;
band->SetTotalRadius(10);
band->SetInnerRadius(5);
for(i=0 ; i<20 ; i++)
{
node.m_Data = i*5.0;
node.m_Index = i;
node.m_NodeState = 0;
//Fill the band
band->PushBack(node);
}
std::cout<<"Band size: "<<band->Size()<<std::endl;
//Iterate over the band
typedef BandType::ConstIterator itType;
itType it = band->Begin();
itType itend = band->End();
i= 0;
BandNodeType *tmp;
for( ; it != itend ; it++)
{
std::cout <<"Node "<<i<<std::endl<<"Index: "<<it->m_Index<<" Data: "<<it->m_Data<<std::endl;
i++;
}
//Split the band
std::vector<RegionType> regions;
regions = band->SplitBand(10);
RegionType region;
typedef std::vector<RegionType>::const_iterator regionitType;
regionitType regionsit = regions.begin();
regionitType regionsitend = regions.end();
std::cout<<"Number of regions: "<<regions.size()<<std::endl;
i = 0;
for(; regionsit != regionsitend ; regionsit++)
{
std::cout<<"Region "<<i<<std::endl;
for( ; regions[i].Begin != regions[i].End; regions[i].Begin++)
std::cout<<"Index: "<<regions[i].Begin->m_Index<<" Data: "<<regions[i].Begin->m_Data<<std::endl;
i++;
}
std::cout << "Test Passed. " << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef __itkSpectra1DSupportWindowImageFilter_hxx
#define __itkSpectra1DSupportWindowImageFilter_hxx
#include "itkSpectra1DSupportWindowImageFilter.h"
#include "itkImageRegionIterator.h"
#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkMetaDataObject.h"
namespace itk
{
template< typename TInputImage >
Spectra1DSupportWindowImageFilter< TInputImage >
::Spectra1DSupportWindowImageFilter():
m_FFT1DSize( 32 )
{
}
template< typename TInputImage >
void
Spectra1DSupportWindowImageFilter< TInputImage >
::ThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, ThreadIdType itkNotUsed( threadId ) )
{
OutputImageType * output = this->GetOutput();
const InputImageType * input = this->GetInput();
const OutputImageRegionType outputLargestRegion = output->GetLargestPossibleRegion();
typedef typename OutputImageType::IndexType IndexType;
const IndexType largestIndexStart = outputLargestRegion.GetIndex();
const IndexType largestIndexStop = largestIndexStart + outputLargestRegion.GetSize();
typedef ImageRegionConstIteratorWithIndex< InputImageType > InputIteratorType;
InputIteratorType inputIt( input, outputRegionForThread );
typedef ImageRegionIterator< OutputImageType > OutputIteratorType;
OutputIteratorType outputIt( output, outputRegionForThread );
const FFT1DSizeType fftSize = this->GetFFT1DSize();
if( outputLargestRegion.GetSize()[0] < fftSize )
{
itkExceptionMacro( "Insufficient size in the FFT direction." );
}
for( inputIt.GoToBegin(), outputIt.GoToBegin(); !outputIt.IsAtEnd(); ++inputIt, ++outputIt )
{
OutputPixelType & supportWindow = outputIt.Value();
supportWindow.clear();
const IndexType inputIndex = inputIt.GetIndex();
IndexType lineIndex;
lineIndex[0] = inputIndex[0] - fftSize;
if( lineIndex[0] < largestIndexStart[0] )
{
lineIndex[0] = largestIndexStart[0];
}
if( lineIndex[0] + fftSize > largestIndexStop[0] )
{
lineIndex[0] = largestIndexStop[0] - fftSize;
}
const IndexValueType sideLines = static_cast< IndexValueType >( inputIt.Get() );
for( IndexValueType line = inputIndex[1] - sideLines;
line < inputIndex[1] + sideLines;
++line )
{
if( line < largestIndexStart[1] || line > largestIndexStop[1] )
{
continue;
}
lineIndex[1] = line;
supportWindow.push_back( lineIndex );
}
}
}
template< typename TInputImage >
void
Spectra1DSupportWindowImageFilter< TInputImage >
::AfterThreadedGenerateData()
{
OutputImageType * output = this->GetOutput();
MetaDataDictionary & dict = output->GetMetaDataDictionary();
EncapsulateMetaData< FFT1DSizeType >( dict, "FFT1DSize", this->GetFFT1DSize() );
}
} // end namespace itk
#endif
<commit_msg>BUG: Fix largestIndexStop in Spectra1DSupportWindowImageFilter.<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef __itkSpectra1DSupportWindowImageFilter_hxx
#define __itkSpectra1DSupportWindowImageFilter_hxx
#include "itkSpectra1DSupportWindowImageFilter.h"
#include "itkImageRegionIterator.h"
#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkMetaDataObject.h"
namespace itk
{
template< typename TInputImage >
Spectra1DSupportWindowImageFilter< TInputImage >
::Spectra1DSupportWindowImageFilter():
m_FFT1DSize( 32 )
{
}
template< typename TInputImage >
void
Spectra1DSupportWindowImageFilter< TInputImage >
::ThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, ThreadIdType itkNotUsed( threadId ) )
{
OutputImageType * output = this->GetOutput();
const InputImageType * input = this->GetInput();
const OutputImageRegionType outputLargestRegion = output->GetLargestPossibleRegion();
typedef typename OutputImageType::IndexType IndexType;
const IndexType largestIndexStart = outputLargestRegion.GetIndex();
IndexType largestIndexStop = largestIndexStart + outputLargestRegion.GetSize();
for( unsigned int dim = 0; dim < ImageDimension; ++dim )
{
largestIndexStop[dim] -= 1;
}
typedef ImageRegionConstIteratorWithIndex< InputImageType > InputIteratorType;
InputIteratorType inputIt( input, outputRegionForThread );
typedef ImageRegionIterator< OutputImageType > OutputIteratorType;
OutputIteratorType outputIt( output, outputRegionForThread );
const FFT1DSizeType fftSize = this->GetFFT1DSize();
if( outputLargestRegion.GetSize()[0] < fftSize )
{
itkExceptionMacro( "Insufficient size in the FFT direction." );
}
for( inputIt.GoToBegin(), outputIt.GoToBegin(); !outputIt.IsAtEnd(); ++inputIt, ++outputIt )
{
OutputPixelType & supportWindow = outputIt.Value();
supportWindow.clear();
const IndexType inputIndex = inputIt.GetIndex();
IndexType lineIndex;
lineIndex[0] = inputIndex[0] - fftSize;
if( lineIndex[0] < largestIndexStart[0] )
{
lineIndex[0] = largestIndexStart[0];
}
if( lineIndex[0] + fftSize > largestIndexStop[0] )
{
lineIndex[0] = largestIndexStop[0] - fftSize;
}
const IndexValueType sideLines = static_cast< IndexValueType >( inputIt.Get() );
for( IndexValueType line = inputIndex[1] - sideLines;
line < inputIndex[1] + sideLines;
++line )
{
if( line < largestIndexStart[1] || line > largestIndexStop[1] )
{
continue;
}
lineIndex[1] = line;
supportWindow.push_back( lineIndex );
}
}
}
template< typename TInputImage >
void
Spectra1DSupportWindowImageFilter< TInputImage >
::AfterThreadedGenerateData()
{
OutputImageType * output = this->GetOutput();
MetaDataDictionary & dict = output->GetMetaDataDictionary();
EncapsulateMetaData< FFT1DSizeType >( dict, "FFT1DSize", this->GetFFT1DSize() );
}
} // end namespace itk
#endif
<|endoftext|> |
<commit_before>//=====================================================================//
/*! @file
@brief ファースト・サンプル(LED 点滅) @n
RX64M, RX71M: @n
12MHz のベースクロックを使用する @n
P07 ピンにLEDを接続する @n
RX65N (Renesas Envision kit RX65N): @n
12MHz のベースクロックを使用する @n
P70 に接続された LED を利用する @n
RX24T: @n
10MHz のベースクロックを使用する @n
P00 ピンにLEDを接続する
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
namespace {
/// ベースクリスタルの定義
/// LED 接続ポートの定義
#if defined(SIG_RX71M)
typedef device::system_io<12000000> SYSTEM_IO;
typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
#elif defined(SIG_RX64M)
typedef device::system_io<12000000> SYSTEM_IO;
typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
#elif defined(SIG_RX65N)
typedef device::system_io<12000000> SYSTEM_IO;
typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
#elif defined(SIG_RX24T)
typedef device::system_io<10000000> SYSTEM_IO;
typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
#endif
}
int main(int argc, char** argv);
int main(int argc, char** argv)
{
SYSTEM_IO::setup_system_clock();
LED::DIR = 1; // LED ポートを出力に設定
while(1) {
utils::delay::milli_second(250);
LED::P = 0;
utils::delay::milli_second(250);
LED::P = 1;
}
}
<commit_msg>update: RX63T<commit_after>//=====================================================================//
/*! @file
@brief ファースト・サンプル(LED 点滅) @n
RX64M, RX71M: @n
12MHz のベースクロックを使用する @n
P07 ピンにLEDを接続する @n
RX65N (Renesas Envision kit RX65N): @n
12MHz のベースクロックを使用する @n
P70 に接続された LED を利用する @n
RX63T @n
12MHz のベースクロックを使用する @n
PB7 に接続された LED を利用する @n
RX24T: @n
10MHz のベースクロックを使用する @n
P00 ピンにLEDを接続する
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
namespace {
/// ベースクリスタルの定義
/// LED 接続ポートの定義
#if defined(SIG_RX71M)
typedef device::system_io<12000000> SYSTEM_IO;
typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
#elif defined(SIG_RX64M)
typedef device::system_io<12000000> SYSTEM_IO;
typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
#elif defined(SIG_RX65N)
typedef device::system_io<12000000> SYSTEM_IO;
typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
#elif defined(SIG_RX63T)
typedef device::system_io<12000000> SYSTEM_IO;
typedef device::PORT<device::PORTB, device::bitpos::B7> LED;
#elif defined(SIG_RX24T)
typedef device::system_io<10000000> SYSTEM_IO;
typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
#endif
}
int main(int argc, char** argv);
int main(int argc, char** argv)
{
SYSTEM_IO::setup_system_clock();
LED::DIR = 1; // LED ポートを出力に設定
while(1) {
utils::delay::milli_second(250);
LED::P = 0;
utils::delay::milli_second(250);
LED::P = 1;
}
}
<|endoftext|> |
<commit_before>/*
* qisplit.cpp
*
* Copyright (c) 2015 Tobias Wood.
*
* 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 <getopt.h>
#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>
#include "Util.h"
#include "Types.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkOtsuThresholdImageFilter.h"
#include "itkConnectedComponentImageFilter.h"
#include "itkLabelShapeKeepNObjectsImageFilter.h"
#include "itkRelabelComponentImageFilter.h"
#include "itkLabelStatisticsImageFilter.h"
#include "itkExtractImageFilter.h"
#include "itkImageMomentsCalculator.h"
#include "itkAffineTransform.h"
#include "itkTransformFileWriter.h"
#include "itkResampleImageFilter.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
using namespace std;
int main(int argc, char **argv) {
bool verbose = false;
int indexptr = 0, c;
int keep = 4, inwards = false, output_images = false;
QI::ImageF::Pointer reference = ITK_NULLPTR;
const string usage {
"Usage is: qisplit input_file.nii [options]\n\
\n\
Options:\n\
--help, -h : Print this message\n\
--verbose, -v : Print more information\n\
--keep, -k : Keep N largest objects (default 4)\n\
--ref, -r : Specify a reference image for CoG\n\
--oimgs : Output images\n\
--inwards : Subjects were scanned facing 'inwards'\n"
};
const struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"keep", required_argument, 0, 'k'},
{"ref", required_argument, 0, 'r'},
{"oimgs", no_argument, &output_images, true},
{"inwards", no_argument, &inwards, true},
{0, 0, 0, 0}
};
const char* short_options = "hvr:k:";
while ((c = getopt_long(argc, argv, short_options, long_options, &indexptr)) != -1) {
switch (c) {
case 'v': verbose = true; break;
case 'h':
cout << usage << endl;
return EXIT_SUCCESS;
case 'r': {
auto refFile = QI::ReadImageF::New();
refFile->SetFileName(optarg);
refFile->Update();
reference = refFile->GetOutput();
reference->DisconnectPipeline();
} break;
case 'k':
keep = atoi(optarg);
break;
case 0: // longopts flag
break;
case '?': // getopt will print an error message
return EXIT_FAILURE;
default:
cout << "Unhandled option " << string(1, c) << endl;
return EXIT_FAILURE;
}
}
if ((argc - optind) != 1) {
cout << usage << endl;
throw(runtime_error("Wrong number of input arguments."));
}
auto input = QI::ReadImageF::New();
string fname(argv[optind++]);
input->SetFileName(fname);
string prefix = QI::StripExt(fname);
typedef unsigned int TLabel;
typedef itk::Image<TLabel, 3> TLabelImage;
/*typedef itk::BinaryThresholdImageFilter<QI::ImageF, TLabelImage> TThreshFilter;
auto threshold = TThreshFilter::New();
threshold->SetInput(input->GetOutput());
threshold->SetLowerThreshold(atof(argv[optind++]));
threshold->SetUpperThreshold(numeric_limits<float>::infinity());
threshold->SetInsideValue(1);
threshold->SetOutsideValue(0);*/
// Use an Otsu Threshold filter to generate the mask
if (verbose) cout << "Generating Otsu mask" << endl;
auto otsuFilter = itk::OtsuThresholdImageFilter<QI::ImageF, TLabelImage>::New();
otsuFilter->SetInput(input->GetOutput());
otsuFilter->SetOutsideValue(1);
otsuFilter->SetInsideValue(0);
otsuFilter->Update();
auto CC = itk::ConnectedComponentImageFilter<TLabelImage, TLabelImage>::New();
CC->SetInput(otsuFilter->GetOutput());
CC->Update();
if (verbose) cout << "Found " << CC->GetObjectCount() << " objects in total, will keep " << keep << " largest." << endl;
typedef itk::LabelShapeKeepNObjectsImageFilter<TLabelImage> TKeepN;
auto keepN = TKeepN::New();
keepN->SetInput(CC->GetOutput());
keepN->SetBackgroundValue(0);
keepN->SetNumberOfObjects(keep);
keepN->SetAttribute(TKeepN::LabelObjectType::NUMBER_OF_PIXELS);
auto relabel = itk::RelabelComponentImageFilter<TLabelImage, TLabelImage>::New();
relabel->SetInput(keepN->GetOutput());
if (verbose) cout << "Writing label image." << endl;
auto output = itk::ImageFileWriter<TLabelImage>::New();
output->SetInput(relabel->GetOutput());
output->SetFileName(prefix + "_labels.nii");
output->Update();
typedef itk::LabelStatisticsImageFilter<QI::ImageF, TLabelImage> TLabelStats;
auto labelStats = TLabelStats::New();
labelStats->SetInput(input->GetOutput());
labelStats->SetLabelInput(relabel->GetOutput());
labelStats->Update();
typedef itk::ImageMomentsCalculator<QI::ImageF> TMoments;
TMoments::VectorType refCoG; refCoG.Fill(0);
if (reference) {
auto refMoments = TMoments::New();
refMoments->SetImage(reference);
refMoments->Compute();
refCoG = refMoments->GetCenterOfGravity();
if (verbose) cout << "Reference CoG is: " << refCoG << endl;
}
// Set these up to use in the loop
typedef itk::ResampleImageFilter<TLabelImage, TLabelImage, double> TLabelResampler;
typedef itk::NearestNeighborInterpolateImageFunction<TLabelImage, double> TLabelInterp;
auto ilabels = TLabelInterp::New();
ilabels->SetInputImage(relabel->GetOutput());
auto rlabels = TLabelResampler::New();
rlabels->SetInput(relabel->GetOutput());
rlabels->SetInterpolator(ilabels);
rlabels->SetDefaultPixelValue(0.);
rlabels->SetOutputParametersFromImage(relabel->GetOutput());
typedef itk::ResampleImageFilter<QI::ImageF, QI::ImageF, double> TResampleF;
typedef itk::LinearInterpolateImageFunction<QI::ImageF, double> TLinearInterpF;
auto interp = TLinearInterpF::New();
interp->SetInputImage(input->GetOutput());
auto rimage = TResampleF::New();
rimage->SetInput(input->GetOutput());
rimage->SetInterpolator(interp);
rimage->SetDefaultPixelValue(0.);
rimage->SetOutputParametersFromImage(input->GetOutput());
itk::Vector<double, 3> zAxis; zAxis.Fill(0); zAxis[2] = 1.0;
for (auto i = 1; i <= 4; i++) {
TLabelImage::RegionType region = labelStats->GetRegion(i);
typedef itk::ExtractImageFilter<QI::ImageF, QI::ImageF> TExtractF;
auto extract = TExtractF::New();
extract->SetInput(input->GetOutput());
extract->SetExtractionRegion(region);
extract->SetDirectionCollapseToSubmatrix();
extract->Update();
auto moments = TMoments::New();
moments->SetImage(extract->GetOutput());
moments->Compute();
TMoments::VectorType CoG = moments->GetCenterOfGravity();
if (verbose) cout << "Writing object " << i << " CoG is " << CoG << endl;
float rotateAngle = atan2(CoG[1], CoG[0]);
if (inwards)
rotateAngle = (M_PI / 2.) - rotateAngle;
else
rotateAngle = (M_PI * 3./2.) - rotateAngle;
if (verbose) cout << "Rotation angle is " << (rotateAngle*180./M_PI) << " degrees" << endl;
typedef itk::AffineTransform<double, 3> TAffine;
auto tfm = TAffine::New();
tfm->SetIdentity();
tfm->SetOffset(CoG - refCoG);
//tfm->SetCenter(CoG); // Want to leave this at 0 due to how ITK transforms work
tfm->Rotate3D(zAxis, -rotateAngle, 1);
stringstream suffix; suffix << "_" << setfill('0') << setw(2) << i;
if (output_images) {
rlabels->SetTransform(tfm.GetPointer());
rimage->SetTransform(tfm.GetPointer());
auto rstats = TLabelStats::New();
rstats->SetInput(rimage->GetOutput());
rstats->SetLabelInput(rlabels->GetOutput());
rstats->Update();
auto rextract = itk::ExtractImageFilter<QI::ImageF, QI::ImageF>::New();
rextract->SetInput(rimage->GetOutput());
rextract->SetExtractionRegion(rstats->GetRegion(i));
rextract->SetDirectionCollapseToSubmatrix();
rextract->Update();
fname = prefix + suffix.str() + ".nii";
if (verbose) cout << "Writing output file " << fname << endl;
auto routput = itk::ImageFileWriter<QI::ImageF>::New();
routput->SetInput(rextract->GetOutput());
routput->SetFileName(fname);
routput->Update();
}
fname = prefix + suffix.str() + ".tfm";
if (verbose) cout << "Writing transform file " << fname << endl;
auto tfmWriter = itk::TransformFileWriterTemplate<double>::New();
tfmWriter->SetInput(tfm);
tfmWriter->SetFileName(fname);
tfmWriter->Update();
}
return EXIT_SUCCESS;
}
<commit_msg>Changed from generic affine to a rigid (Euler3D) transform for pedantry's sake.<commit_after>/*
* qisplit.cpp
*
* Copyright (c) 2015 Tobias Wood.
*
* 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 <getopt.h>
#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>
#include "Util.h"
#include "Types.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkOtsuThresholdImageFilter.h"
#include "itkConnectedComponentImageFilter.h"
#include "itkLabelShapeKeepNObjectsImageFilter.h"
#include "itkRelabelComponentImageFilter.h"
#include "itkLabelStatisticsImageFilter.h"
#include "itkExtractImageFilter.h"
#include "itkImageMomentsCalculator.h"
#include "itkEuler3DTransform.h"
#include "itkTransformFileWriter.h"
#include "itkResampleImageFilter.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
using namespace std;
int main(int argc, char **argv) {
bool verbose = false;
int indexptr = 0, c;
int keep = 4, inwards = false, output_images = false;
QI::ImageF::Pointer reference = ITK_NULLPTR;
const string usage {
"Usage is: qisplit input_file.nii [options]\n\
\n\
Options:\n\
--help, -h : Print this message\n\
--verbose, -v : Print more information\n\
--keep, -k : Keep N largest objects (default 4)\n\
--ref, -r : Specify a reference image for CoG\n\
--oimgs : Output images\n\
--inwards : Subjects were scanned facing 'inwards'\n"
};
const struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"keep", required_argument, 0, 'k'},
{"ref", required_argument, 0, 'r'},
{"oimgs", no_argument, &output_images, true},
{"inwards", no_argument, &inwards, true},
{0, 0, 0, 0}
};
const char* short_options = "hvr:k:";
while ((c = getopt_long(argc, argv, short_options, long_options, &indexptr)) != -1) {
switch (c) {
case 'v': verbose = true; break;
case 'h':
cout << usage << endl;
return EXIT_SUCCESS;
case 'r': {
auto refFile = QI::ReadImageF::New();
refFile->SetFileName(optarg);
refFile->Update();
reference = refFile->GetOutput();
reference->DisconnectPipeline();
} break;
case 'k':
keep = atoi(optarg);
break;
case 0: // longopts flag
break;
case '?': // getopt will print an error message
return EXIT_FAILURE;
default:
cout << "Unhandled option " << string(1, c) << endl;
return EXIT_FAILURE;
}
}
if ((argc - optind) != 1) {
cout << usage << endl;
throw(runtime_error("Wrong number of input arguments."));
}
auto input = QI::ReadImageF::New();
string fname(argv[optind++]);
input->SetFileName(fname);
string prefix = QI::StripExt(fname);
typedef unsigned int TLabel;
typedef itk::Image<TLabel, 3> TLabelImage;
/*typedef itk::BinaryThresholdImageFilter<QI::ImageF, TLabelImage> TThreshFilter;
auto threshold = TThreshFilter::New();
threshold->SetInput(input->GetOutput());
threshold->SetLowerThreshold(atof(argv[optind++]));
threshold->SetUpperThreshold(numeric_limits<float>::infinity());
threshold->SetInsideValue(1);
threshold->SetOutsideValue(0);*/
// Use an Otsu Threshold filter to generate the mask
if (verbose) cout << "Generating Otsu mask" << endl;
auto otsuFilter = itk::OtsuThresholdImageFilter<QI::ImageF, TLabelImage>::New();
otsuFilter->SetInput(input->GetOutput());
otsuFilter->SetOutsideValue(1);
otsuFilter->SetInsideValue(0);
otsuFilter->Update();
auto CC = itk::ConnectedComponentImageFilter<TLabelImage, TLabelImage>::New();
CC->SetInput(otsuFilter->GetOutput());
CC->Update();
if (verbose) cout << "Found " << CC->GetObjectCount() << " objects in total, will keep " << keep << " largest." << endl;
typedef itk::LabelShapeKeepNObjectsImageFilter<TLabelImage> TKeepN;
auto keepN = TKeepN::New();
keepN->SetInput(CC->GetOutput());
keepN->SetBackgroundValue(0);
keepN->SetNumberOfObjects(keep);
keepN->SetAttribute(TKeepN::LabelObjectType::NUMBER_OF_PIXELS);
auto relabel = itk::RelabelComponentImageFilter<TLabelImage, TLabelImage>::New();
relabel->SetInput(keepN->GetOutput());
if (verbose) cout << "Writing label image." << endl;
auto output = itk::ImageFileWriter<TLabelImage>::New();
output->SetInput(relabel->GetOutput());
output->SetFileName(prefix + "_labels.nii");
output->Update();
typedef itk::LabelStatisticsImageFilter<QI::ImageF, TLabelImage> TLabelStats;
auto labelStats = TLabelStats::New();
labelStats->SetInput(input->GetOutput());
labelStats->SetLabelInput(relabel->GetOutput());
labelStats->Update();
typedef itk::ImageMomentsCalculator<QI::ImageF> TMoments;
TMoments::VectorType refCoG; refCoG.Fill(0);
if (reference) {
auto refMoments = TMoments::New();
refMoments->SetImage(reference);
refMoments->Compute();
refCoG = refMoments->GetCenterOfGravity();
if (verbose) cout << "Reference CoG is: " << refCoG << endl;
}
// Set these up to use in the loop
typedef itk::ResampleImageFilter<TLabelImage, TLabelImage, double> TLabelResampler;
typedef itk::NearestNeighborInterpolateImageFunction<TLabelImage, double> TLabelInterp;
auto ilabels = TLabelInterp::New();
ilabels->SetInputImage(relabel->GetOutput());
auto rlabels = TLabelResampler::New();
rlabels->SetInput(relabel->GetOutput());
rlabels->SetInterpolator(ilabels);
rlabels->SetDefaultPixelValue(0.);
rlabels->SetOutputParametersFromImage(relabel->GetOutput());
typedef itk::ResampleImageFilter<QI::ImageF, QI::ImageF, double> TResampleF;
typedef itk::LinearInterpolateImageFunction<QI::ImageF, double> TLinearInterpF;
auto interp = TLinearInterpF::New();
interp->SetInputImage(input->GetOutput());
auto rimage = TResampleF::New();
rimage->SetInput(input->GetOutput());
rimage->SetInterpolator(interp);
rimage->SetDefaultPixelValue(0.);
rimage->SetOutputParametersFromImage(input->GetOutput());
for (auto i = 1; i <= 4; i++) {
TLabelImage::RegionType region = labelStats->GetRegion(i);
typedef itk::ExtractImageFilter<QI::ImageF, QI::ImageF> TExtractF;
auto extract = TExtractF::New();
extract->SetInput(input->GetOutput());
extract->SetExtractionRegion(region);
extract->SetDirectionCollapseToSubmatrix();
extract->Update();
auto moments = TMoments::New();
moments->SetImage(extract->GetOutput());
moments->Compute();
TMoments::VectorType CoG = moments->GetCenterOfGravity();
if (verbose) cout << "Writing object " << i << " CoG is " << CoG << endl;
float rotateAngle = atan2(CoG[1], CoG[0]);
if (inwards)
rotateAngle = (M_PI / 2.) - rotateAngle;
else
rotateAngle = (M_PI * 3./2.) - rotateAngle;
if (verbose) cout << "Rotation angle is " << (rotateAngle*180./M_PI) << " degrees" << endl;
typedef itk::Euler3DTransform<double> TRigid;
auto tfm = TRigid::New();
tfm->SetIdentity();
tfm->SetOffset(CoG - refCoG);
//tfm->SetCenter(CoG); // Want to leave this at 0 due to how ITK transforms work
tfm->SetRotation(0, 0, -rotateAngle);
stringstream suffix; suffix << "_" << setfill('0') << setw(2) << i;
if (output_images) {
rlabels->SetTransform(tfm.GetPointer());
rimage->SetTransform(tfm.GetPointer());
auto rstats = TLabelStats::New();
rstats->SetInput(rimage->GetOutput());
rstats->SetLabelInput(rlabels->GetOutput());
rstats->Update();
auto rextract = itk::ExtractImageFilter<QI::ImageF, QI::ImageF>::New();
rextract->SetInput(rimage->GetOutput());
rextract->SetExtractionRegion(rstats->GetRegion(i));
rextract->SetDirectionCollapseToSubmatrix();
rextract->Update();
fname = prefix + suffix.str() + ".nii";
if (verbose) cout << "Writing output file " << fname << endl;
auto routput = itk::ImageFileWriter<QI::ImageF>::New();
routput->SetInput(rextract->GetOutput());
routput->SetFileName(fname);
routput->Update();
}
fname = prefix + suffix.str() + ".tfm";
if (verbose) cout << "Writing transform file " << fname << endl;
auto tfmWriter = itk::TransformFileWriterTemplate<double>::New();
tfmWriter->SetInput(tfm);
tfmWriter->SetFileName(fname);
tfmWriter->Update();
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Copyright 2015 Florian Muecke. All rights reserved.
#include <iostream>
#include <vector>
#include <string>
#include <system_error>
#include <filesystem>
#include <memory>
#include "../../WinUtil/System.hpp"
#include "../../WinUtil/Security.hpp"
using namespace std;
using namespace std::tr2;
using namespace WinUtil;
static wchar_t const * const uninstallStr = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
struct UninstallData
{
wstring userProfile;
wstring key;
wstring displayName;
wstring displayVersion;
wstring publisher;
wstring ToText() const
{
return userProfile + L": DisplayName=" + displayName + L", Publisher=" + publisher + L", DisplayVersion=" + displayVersion + L", Key=" + key;
}
};
static UninstallData GetUninstallData(HKEY const& hKey, wstring const& key)
{
UninstallData data;
data.key = key;
Registry::TryReadString(hKey, key, L"DisplayName", data.displayName);
Registry::TryReadString(hKey, key, L"DisplayVersion", data.displayVersion);
Registry::TryReadString(hKey, key, L"Publisher", data.publisher);
return data;
}
static bool SetProcRegAccessPrivs(bool bSet)
{
HANDLE hToken;
if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
cerr << "Error opening process token: " << ::GetLastError() << endl;
return false;
}
LUID restorePriv, backupPriv;
if (!::LookupPrivilegeValue(nullptr, SE_RESTORE_NAME, &restorePriv) ||
!::LookupPrivilegeValue(nullptr, SE_BACKUP_NAME, &backupPriv))
{
cerr << "Error getting privilege values" << endl;
return false;
}
// create buffer with enough space for token privileges and an additional LUID with attributes
auto buffer = std::vector<byte>(sizeof(TOKEN_PRIVILEGES) + sizeof(LUID_AND_ATTRIBUTES), 0);
TOKEN_PRIVILEGES* pTokenPrivileges = (TOKEN_PRIVILEGES*)buffer.data();
pTokenPrivileges->PrivilegeCount = 2;
pTokenPrivileges->Privileges[0].Luid = restorePriv;
pTokenPrivileges->Privileges[0].Attributes = bSet? SE_PRIVILEGE_ENABLED : 0;
pTokenPrivileges->Privileges[1].Luid = backupPriv;
pTokenPrivileges->Privileges[1].Attributes = bSet? SE_PRIVILEGE_ENABLED : 0;
if (!::AdjustTokenPrivileges(hToken, FALSE, pTokenPrivileges, 0, nullptr, nullptr))
{
auto err = ::GetLastError();
cerr << "Error setting privilege values: " << err << endl;
return false;
}
return true;
}
static vector<UninstallData> ScanUserKey(HKEY appKey, wstring const& subKey, WinUtil::UserProfile const& profile)
{
vector<UninstallData> result;
Registry reg;
auto openResult = reg.Open(appKey, subKey, Registry::Mode::Read);
if (openResult == ERROR_FILE_NOT_FOUND)
{
// no software subkey for this user
return result;
}
if (openResult == ERROR_SUCCESS)
{
vector<wstring> subKeys;
reg.EnumKeys(subKeys);
for (auto const& key : subKeys)
{
auto data = GetUninstallData(reg.Key(), key);
data.userProfile = profile.GetFullAccountName();
result.push_back(std::move(data));
}
}
else
{
auto err = error_code(openResult, system_category());
cerr << "error: " << err.message();
}
return result;
}
int main()
{
SetProcRegAccessPrivs(true);
bool verbose = false;
vector<UserProfile> profiles;
System::GetLocalProfiles(profiles);
vector<UninstallData> uninstallData;
using RegLoadAppKeyFun = LONG(WINAPI*)(LPCTSTR, PHKEY, REGSAM, DWORD, DWORD);
auto hModule = GetModuleHandleW(L"Advapi32.dll");
if (!hModule) exit(1);
RegLoadAppKeyFun fnRegLoadAppKey = (RegLoadAppKeyFun)::GetProcAddress(hModule, "RegLoadAppKeyW");
if (fnRegLoadAppKey)
{
for (auto const& profile : profiles)
{
if (profile.path.empty()) continue;
auto path = profile.path;
path.append(path.back() == L'\\' ? L"NTUSER.DAT" : L"\\NTUSER.DAT");
if (!sys::exists(sys::path(path))) continue;
HKEY appKey;
DWORD loadResult = fnRegLoadAppKey(path.c_str(), &appKey, KEY_ALL_ACCESS, REG_PROCESS_APPKEY, 0);
if (ERROR_SUCCESS == loadResult || ERROR_SHARING_VIOLATION == loadResult)
{
auto subKey = ERROR_SUCCESS == loadResult ? wstring(uninstallStr) : profile.sid + L"\\" + uninstallStr;
if (ERROR_SHARING_VIOLATION == loadResult) appKey = HKEY_USERS;
auto userData = ScanUserKey(appKey, subKey, profile);
if (verbose) wcout << profile.GetFullAccountName() << L": " << userData.size() << L" found" << endl;
uninstallData.insert(cend(uninstallData), cbegin(userData), cend(userData));
::RegCloseKey(appKey);
}
else
{
if (ERROR_BADDB == loadResult) //ERROR_PRIVILEGE_NOT_HELD
{
// really load the hive
loadResult = ::RegLoadKeyW(HKEY_USERS, profile.name.c_str(), path.c_str());
if (loadResult == ERROR_SUCCESS)
{
auto subKey = "";
auto userData = ScanUserKey(HKEY_USERS, profile.name + L"\\" + uninstallStr, profile);
if (verbose) wcout << profile.GetFullAccountName() << L": " << userData.size() << L" found" << endl;
uninstallData.insert(cend(uninstallData), cbegin(userData), cend(userData));
::RegUnLoadKeyW(HKEY_USERS, profile.name.c_str());
continue;
}
}
wcerr << profile.name << L": ";
auto err = error_code(loadResult, system_category());
cerr << "error " << err.value() << ": " << err.message();
}
}
}
else
{
cerr << "platform not supported" << endl;
exit(ERROR_INVALID_FUNCTION);
}
wcout << uninstallData.size() << L" found\n";
for (auto const& data : uninstallData)
{
wcout << data.ToText() << endl;
}
return 0;
}
<commit_msg>fixed unicode handling for wcout<commit_after>// Copyright 2015 Florian Muecke. All rights reserved.
#include <iostream>
#include <vector>
#include <string>
#include <system_error>
#include <filesystem>
#include <memory>
#include <io.h>
#include <fcntl.h>
#include "../../WinUtil/System.hpp"
#include "../../WinUtil/Security.hpp"
using namespace std;
using namespace std::tr2;
using namespace WinUtil;
static wchar_t const * const uninstallStr = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
struct UninstallData
{
wstring userProfile;
wstring key;
wstring displayName;
wstring displayVersion;
wstring publisher;
wstring ToText() const
{
return userProfile + L": DisplayName=" + displayName + L", Publisher=" + publisher + L", DisplayVersion=" + displayVersion + L", Key=" + key;
}
};
static UninstallData GetUninstallData(HKEY const& hKey, wstring const& key)
{
UninstallData data;
data.key = key;
Registry::TryReadString(hKey, key, L"DisplayName", data.displayName);
Registry::TryReadString(hKey, key, L"DisplayVersion", data.displayVersion);
Registry::TryReadString(hKey, key, L"Publisher", data.publisher);
return data;
}
static bool SetProcRegAccessPrivs(bool bSet)
{
HANDLE hToken;
if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
cerr << "Error opening process token: " << ::GetLastError() << endl;
return false;
}
LUID restorePriv, backupPriv;
if (!::LookupPrivilegeValue(nullptr, SE_RESTORE_NAME, &restorePriv) ||
!::LookupPrivilegeValue(nullptr, SE_BACKUP_NAME, &backupPriv))
{
cerr << "Error getting privilege values" << endl;
return false;
}
// create buffer with enough space for token privileges and an additional LUID with attributes
auto buffer = std::vector<byte>(sizeof(TOKEN_PRIVILEGES) + sizeof(LUID_AND_ATTRIBUTES), 0);
TOKEN_PRIVILEGES* pTokenPrivileges = (TOKEN_PRIVILEGES*)buffer.data();
pTokenPrivileges->PrivilegeCount = 2;
pTokenPrivileges->Privileges[0].Luid = restorePriv;
pTokenPrivileges->Privileges[0].Attributes = bSet? SE_PRIVILEGE_ENABLED : 0;
pTokenPrivileges->Privileges[1].Luid = backupPriv;
pTokenPrivileges->Privileges[1].Attributes = bSet? SE_PRIVILEGE_ENABLED : 0;
if (!::AdjustTokenPrivileges(hToken, FALSE, pTokenPrivileges, 0, nullptr, nullptr))
{
auto err = ::GetLastError();
cerr << "Error setting privilege values: " << err << endl;
return false;
}
return true;
}
static vector<UninstallData> ScanUserKey(HKEY appKey, wstring const& subKey, WinUtil::UserProfile const& profile)
{
vector<UninstallData> result;
Registry reg;
auto openResult = reg.Open(appKey, subKey, Registry::Mode::Read);
if (openResult == ERROR_FILE_NOT_FOUND)
{
// no software subkey for this user
return result;
}
if (openResult == ERROR_SUCCESS)
{
vector<wstring> subKeys;
reg.EnumKeys(subKeys);
for (auto const& key : subKeys)
{
auto data = GetUninstallData(reg.Key(), key);
data.userProfile = profile.GetFullAccountName();
result.push_back(std::move(data));
}
}
else
{
auto err = error_code(openResult, system_category());
cerr << "error: " << err.message();
}
return result;
}
int main()
{
_setmode(_fileno(stdout), _O_U16TEXT);
SetProcRegAccessPrivs(true);
bool verbose = false;
vector<UserProfile> profiles;
System::GetLocalProfiles(profiles);
vector<UninstallData> uninstallData;
using RegLoadAppKeyFun = LONG(WINAPI*)(LPCTSTR, PHKEY, REGSAM, DWORD, DWORD);
auto hModule = GetModuleHandleW(L"Advapi32.dll");
if (!hModule) exit(1);
RegLoadAppKeyFun fnRegLoadAppKey = (RegLoadAppKeyFun)::GetProcAddress(hModule, "RegLoadAppKeyW");
if (fnRegLoadAppKey)
{
for (auto const& profile : profiles)
{
if (profile.path.empty()) continue;
auto path = profile.path;
path.append(path.back() == L'\\' ? L"NTUSER.DAT" : L"\\NTUSER.DAT");
if (!sys::exists(sys::path(path))) continue;
HKEY appKey;
DWORD loadResult = fnRegLoadAppKey(path.c_str(), &appKey, KEY_ALL_ACCESS, REG_PROCESS_APPKEY, 0);
if (ERROR_SUCCESS == loadResult || ERROR_SHARING_VIOLATION == loadResult)
{
auto subKey = ERROR_SUCCESS == loadResult ? wstring(uninstallStr) : profile.sid + L"\\" + uninstallStr;
if (ERROR_SHARING_VIOLATION == loadResult) appKey = HKEY_USERS;
auto userData = ScanUserKey(appKey, subKey, profile);
if (verbose) wcout << profile.GetFullAccountName() << L": " << userData.size() << L" found" << endl;
uninstallData.insert(cend(uninstallData), cbegin(userData), cend(userData));
::RegCloseKey(appKey);
}
else
{
if (ERROR_BADDB == loadResult) //ERROR_PRIVILEGE_NOT_HELD
{
// really load the hive
loadResult = ::RegLoadKeyW(HKEY_USERS, profile.name.c_str(), path.c_str());
if (loadResult == ERROR_SUCCESS)
{
auto subKey = "";
auto userData = ScanUserKey(HKEY_USERS, profile.name + L"\\" + uninstallStr, profile);
if (verbose) wcout << profile.GetFullAccountName() << L": " << userData.size() << L" found" << endl;
uninstallData.insert(cend(uninstallData), cbegin(userData), cend(userData));
::RegUnLoadKeyW(HKEY_USERS, profile.name.c_str());
continue;
}
}
wcerr << profile.name << L": ";
auto err = error_code(loadResult, system_category());
cerr << "error " << err.value() << ": " << err.message();
}
}
}
else
{
cerr << "platform not supported" << endl;
exit(ERROR_INVALID_FUNCTION);
}
wcout << uninstallData.size() << L" found\n";
for (auto const& data : uninstallData)
{
auto result = data.ToText();
wcout << result << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>//
// BundleActivator.cpp
//
// $Id$
//
// Copyright (c) 2015, Applied Informatics Software Engineering GmbH.
// All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
#include "Poco/WebTunnel/RemotePortForwarder.h"
#include "Poco/Net/HTTPSessionFactory.h"
#include "Poco/Net/HTTPSessionInstantiator.h"
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/HTTPBasicCredentials.h"
#include "Poco/Net/DNS.h"
#include "Poco/OSP/BundleActivator.h"
#include "Poco/OSP/BundleContext.h"
#include "Poco/OSP/Bundle.h"
#include "Poco/OSP/PreferencesService.h"
#include "Poco/OSP/ServiceRegistry.h"
#include "Poco/OSP/ServiceRef.h"
#include "Poco/OSP/ServiceFinder.h"
#include "Poco/Util/Timer.h"
#include "Poco/Util/TimerTaskAdapter.h"
#include "Poco/URI.h"
#include "Poco/NumberParser.h"
#include "Poco/StringTokenizer.h"
#include "Poco/SharedPtr.h"
#include "Poco/Delegate.h"
#include "Poco/Buffer.h"
#include "Poco/Event.h"
#include "Poco/Environment.h"
#include "Poco/ClassLibrary.h"
using Poco::OSP::BundleContext;
using Poco::OSP::ServiceRegistry;
using Poco::OSP::ServiceRef;
using Poco::OSP::ServiceFinder;
using Poco::OSP::Properties;
using Poco::OSP::PreferencesService;
using Poco::OSP::Preferences;
namespace IoT {
namespace WebTunnel {
class BundleActivator: public Poco::OSP::BundleActivator
{
public:
BundleActivator():
_httpPort(80),
_useProxy(false),
_proxyPort(0),
_threads(0),
_retryDelay(1000)
{
}
~BundleActivator()
{
}
void start(BundleContext::Ptr pContext)
{
_pContext = pContext;
_pPrefsService = ServiceFinder::find<PreferencesService>(pContext);
_pPrefs = _pPrefsService->preferences(pContext->thisBundle()->symbolicName());
if (getBoolConfig("webtunnel.enable", false))
{
try
{
_reflectorURI = getStringConfig("webtunnel.reflectorURI");
_deviceName = getStringConfig("webtunnel.deviceName", "");
_username = getStringConfig("webtunnel.username", "");
_password = getStringConfig("webtunnel.password", "");
std::string host = getStringConfig("webtunnel.host", "127.0.0.1");
if (!Poco::Net::IPAddress::tryParse(host, _host))
{
_host = Poco::Net::DNS::resolveOne(host);
}
std::string ports = getStringConfig("webtunnel.ports", "");
Poco::StringTokenizer tok(ports, ";,", Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY);
for (Poco::StringTokenizer::Iterator it = tok.begin(); it != tok.end(); ++it)
{
int port = Poco::NumberParser::parse(*it);
if (port > 0 && port < 65536)
{
_ports.insert(static_cast<Poco::UInt16>(port));
}
else
{
_pContext->logger().warning(Poco::format("Ignored out-of-range port number specified in configuration: %d", port));
}
}
_httpPort = static_cast<Poco::UInt16>(_pPrefsService->configuration()->getInt("osp.web.server.port", 22080));
_ports.insert(_httpPort);
_localTimeout = Poco::Timespan(getIntConfig("webtunnel.localTimeout", 7200), 0);
_connectTimeout = Poco::Timespan(getIntConfig("webtunnel.connectTimeout", 10), 0);
_remoteTimeout = Poco::Timespan(getIntConfig("webtunnel.remoteTimeout", 300), 0);
_threads = getIntConfig("webtunnel.threads", 4);
_userAgent = getStringConfig("webtunnel.userAgent", "");
_httpTimeout = Poco::Timespan(getIntConfig("webtunnel.http.timeout", 30), 0);
_useProxy = getBoolConfig("webtunnel.http.proxy.enable", false);
_proxyHost = getStringConfig("webtunnel.http.proxy.host", "");
_proxyPort = static_cast<Poco::UInt16>(getIntConfig("webtunnel.http.proxy.port", 80));
_proxyUsername = getStringConfig("webtunnel.http.proxy.username", "");
_proxyPassword = getStringConfig("webtunnel.http.proxy.password", "");
if (_userAgent.empty())
{
_userAgent = pContext->thisBundle()->symbolicName();
_userAgent += "/";
_userAgent += pContext->thisBundle()->version().toString();
_userAgent += " (";
_userAgent += Poco::Environment::osName();
_userAgent += "/";
_userAgent += Poco::Environment::osVersion();
_userAgent += "; ";
_userAgent += Poco::Environment::osArchitecture();
_userAgent += ") POCO/";
_userAgent += Poco::format("%d.%d.%d",
static_cast<int>(Poco::Environment::libraryVersion() >> 24),
static_cast<int>((Poco::Environment::libraryVersion() >> 16) & 0xFF),
static_cast<int>((Poco::Environment::libraryVersion() >> 8) & 0xFF));
}
_pTimer = new Poco::Util::Timer;
_pTimer->schedule(new Poco::Util::TimerTaskAdapter<BundleActivator>(*this, &BundleActivator::reconnect), Poco::Timestamp());
}
catch (Poco::Exception& exc)
{
_pContext->logger().log(exc);
}
}
else
{
_pContext->logger().information("WebTunnel disabled.");
}
}
void stop(BundleContext::Ptr pContext)
{
if (_pTimer)
{
_stopped.set();
disconnect();
_pTimer->cancel(true);
_pTimer = 0;
}
_pPrefs = 0;
_pPrefsService = 0;
_pContext = 0;
}
protected:
bool getBoolConfig(const std::string& key)
{
return _pPrefs->getBool(key, _pPrefsService->configuration()->getBool(key));
}
bool getBoolConfig(const std::string& key, bool deflt)
{
return _pPrefs->getBool(key, _pPrefsService->configuration()->getBool(key, deflt));
}
int getIntConfig(const std::string& key)
{
return _pPrefs->getInt(key, _pPrefsService->configuration()->getInt(key));
}
int getIntConfig(const std::string& key, int deflt)
{
return _pPrefs->getInt(key, _pPrefsService->configuration()->getInt(key, deflt));
}
std::string getStringConfig(const std::string& key)
{
return _pPrefs->getString(key, _pPrefsService->configuration()->getString(key));
}
std::string getStringConfig(const std::string& key, const std::string& deflt)
{
return _pPrefs->getString(key, _pPrefsService->configuration()->getString(key, deflt));
}
void connect()
{
_pContext->logger().information("Connecting to " + _reflectorURI.toString() + "...");
_pHTTPClientSession = Poco::Net::HTTPSessionFactory::defaultFactory().createClientSession(_reflectorURI);
_pHTTPClientSession->setTimeout(_httpTimeout);
if (_useProxy && !_proxyHost.empty())
{
_pHTTPClientSession->setProxy(_proxyHost, _proxyPort);
if (!_proxyUsername.empty())
{
_pHTTPClientSession->setProxyCredentials(_proxyUsername, _proxyPassword);
}
}
std::string path(_reflectorURI.getPathEtc());
if (path.empty()) path = "/";
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, path, Poco::Net::HTTPRequest::HTTP_1_1);
request.set(SEC_WEBSOCKET_PROTOCOL, WEBTUNNEL_PROTOCOL);
if (!_username.empty())
{
Poco::Net::HTTPBasicCredentials creds(_username, _password);
creds.authenticate(request);
}
if (_httpPort != 0)
{
request.add("X-PTTH-Set-Property", Poco::format("device;httpPort=%hu", _httpPort));
}
if (!_deviceName.empty())
{
request.add("X-PTTH-Set-Property", Poco::format("device;name=\"%s\"", _deviceName));
}
request.set("User-Agent", _userAgent);
Poco::Net::HTTPResponse response;
bool reconnect = true;
while (reconnect)
{
_pContext->logger().debug("Entering reconnect loop...");
try
{
Poco::Net::DNS::reload();
_pContext->logger().debug("Creating WebSocket...");
Poco::SharedPtr<Poco::Net::WebSocket> pWebSocket = new Poco::Net::WebSocket(*_pHTTPClientSession, request, response);
if (response.get(SEC_WEBSOCKET_PROTOCOL, "") == WEBTUNNEL_PROTOCOL)
{
_pContext->logger().debug("WebSocket established. Creating RemotePortForwarder...");
_pDispatcher = new Poco::WebTunnel::SocketDispatcher(_threads);
_pForwarder = new Poco::WebTunnel::RemotePortForwarder(*_pDispatcher, pWebSocket, _host, _ports, _remoteTimeout);
_pForwarder->setConnectTimeout(_connectTimeout);
_pForwarder->setLocalTimeout(_localTimeout);
_pForwarder->webSocketClosed += Poco::delegate(this, &BundleActivator::onClose);
_retryDelay = 1000;
_pContext->logger().information("WebTunnel connection established.");
return;
}
else
{
_pContext->logger().error(Poco::format("The host at %s does not support the WebTunnel protocol.", _reflectorURI.toString()));
pWebSocket->shutdown(Poco::Net::WebSocket::WS_PROTOCOL_ERROR);
// receive final frame from peer; ignore if none is sent.
if (pWebSocket->poll(Poco::Timespan(2, 0), Poco::Net::Socket::SELECT_READ))
{
Poco::Buffer<char> buffer(1024);
int flags;
try
{
pWebSocket->receiveFrame(buffer.begin(), static_cast<int>(buffer.size()), flags);
}
catch (Poco::Exception&)
{
}
}
pWebSocket->close();
reconnect = false;
}
}
catch (Poco::Exception& exc)
{
_pContext->logger().error(Poco::format("Cannot connect to reflector at %s: %s", _reflectorURI.toString(), exc.displayText()));
if (_retryDelay < 30000)
{
_retryDelay *= 2;
}
reconnect = !_stopped.tryWait(_retryDelay);
}
}
}
void disconnect()
{
if (_pForwarder)
{
_pContext->logger().information("Disconnecting from reflector server");
_pForwarder->webSocketClosed -= Poco::delegate(this, &BundleActivator::onClose);
_pForwarder->stop();
_pForwarder = 0;
_pDispatcher = 0;
}
if (_pHTTPClientSession)
{
try
{
_pHTTPClientSession->abort();
}
catch (Poco::Exception&)
{
}
}
}
void onClose(const int& reason)
{
_pContext->logger().information("WebTunnel connection closed.");
if (!_stopped.tryWait(_retryDelay))
{
_pTimer->schedule(new Poco::Util::TimerTaskAdapter<BundleActivator>(*this, &BundleActivator::reconnect), Poco::Timestamp());
}
}
void reconnect(Poco::Util::TimerTask&)
{
try
{
disconnect();
connect();
}
catch (Poco::Exception& exc)
{
_pContext->logger().fatal(exc.displayText());
}
}
static const std::string SEC_WEBSOCKET_PROTOCOL;
static const std::string WEBTUNNEL_PROTOCOL;
private:
BundleContext::Ptr _pContext;
PreferencesService::Ptr _pPrefsService;
Preferences::Ptr _pPrefs;
Poco::Net::IPAddress _host;
std::set<Poco::UInt16> _ports;
Poco::URI _reflectorURI;
std::string _deviceName;
std::string _username;
std::string _password;
std::string _userAgent;
Poco::UInt16 _httpPort;
bool _useProxy;
std::string _proxyHost;
Poco::UInt16 _proxyPort;
std::string _proxyUsername;
std::string _proxyPassword;
Poco::Timespan _localTimeout;
Poco::Timespan _connectTimeout;
Poco::Timespan _remoteTimeout;
Poco::Timespan _httpTimeout;
int _threads;
Poco::SharedPtr<Poco::WebTunnel::SocketDispatcher> _pDispatcher;
Poco::SharedPtr<Poco::WebTunnel::RemotePortForwarder> _pForwarder;
Poco::SharedPtr<Poco::Net::HTTPClientSession> _pHTTPClientSession;
Poco::Event _stopped;
int _retryDelay;
Poco::SharedPtr<Poco::Util::Timer> _pTimer;
};
const std::string BundleActivator::SEC_WEBSOCKET_PROTOCOL("Sec-WebSocket-Protocol");
const std::string BundleActivator::WEBTUNNEL_PROTOCOL("com.appinf.webtunnel.server/1.0");
} } // namespace IoT::WebTunnel
POCO_BEGIN_MANIFEST(Poco::OSP::BundleActivator)
POCO_EXPORT_CLASS(IoT::WebTunnel::BundleActivator)
POCO_END_MANIFEST
<commit_msg>support for specifying VNC port<commit_after>//
// BundleActivator.cpp
//
// $Id$
//
// Copyright (c) 2015, Applied Informatics Software Engineering GmbH.
// All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
#include "Poco/WebTunnel/RemotePortForwarder.h"
#include "Poco/Net/HTTPSessionFactory.h"
#include "Poco/Net/HTTPSessionInstantiator.h"
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/HTTPBasicCredentials.h"
#include "Poco/Net/DNS.h"
#include "Poco/OSP/BundleActivator.h"
#include "Poco/OSP/BundleContext.h"
#include "Poco/OSP/Bundle.h"
#include "Poco/OSP/PreferencesService.h"
#include "Poco/OSP/ServiceRegistry.h"
#include "Poco/OSP/ServiceRef.h"
#include "Poco/OSP/ServiceFinder.h"
#include "Poco/Util/Timer.h"
#include "Poco/Util/TimerTaskAdapter.h"
#include "Poco/URI.h"
#include "Poco/NumberParser.h"
#include "Poco/StringTokenizer.h"
#include "Poco/SharedPtr.h"
#include "Poco/Delegate.h"
#include "Poco/Buffer.h"
#include "Poco/Event.h"
#include "Poco/Environment.h"
#include "Poco/ClassLibrary.h"
using Poco::OSP::BundleContext;
using Poco::OSP::ServiceRegistry;
using Poco::OSP::ServiceRef;
using Poco::OSP::ServiceFinder;
using Poco::OSP::Properties;
using Poco::OSP::PreferencesService;
using Poco::OSP::Preferences;
namespace IoT {
namespace WebTunnel {
class BundleActivator: public Poco::OSP::BundleActivator
{
public:
BundleActivator():
_httpPort(80),
_vncPort(0),
_useProxy(false),
_proxyPort(0),
_threads(0),
_retryDelay(1000)
{
}
~BundleActivator()
{
}
void start(BundleContext::Ptr pContext)
{
_pContext = pContext;
_pPrefsService = ServiceFinder::find<PreferencesService>(pContext);
_pPrefs = _pPrefsService->preferences(pContext->thisBundle()->symbolicName());
if (getBoolConfig("webtunnel.enable", false))
{
try
{
_reflectorURI = getStringConfig("webtunnel.reflectorURI");
_deviceName = getStringConfig("webtunnel.deviceName", "");
_username = getStringConfig("webtunnel.username", "");
_password = getStringConfig("webtunnel.password", "");
std::string host = getStringConfig("webtunnel.host", "127.0.0.1");
if (!Poco::Net::IPAddress::tryParse(host, _host))
{
_host = Poco::Net::DNS::resolveOne(host);
}
std::string ports = getStringConfig("webtunnel.ports", "");
Poco::StringTokenizer tok(ports, ";,", Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY);
for (Poco::StringTokenizer::Iterator it = tok.begin(); it != tok.end(); ++it)
{
int port = Poco::NumberParser::parse(*it);
if (port > 0 && port < 65536)
{
_ports.insert(static_cast<Poco::UInt16>(port));
}
else
{
_pContext->logger().warning(Poco::format("Ignored out-of-range port number specified in configuration: %d", port));
}
}
_httpPort = static_cast<Poco::UInt16>(_pPrefsService->configuration()->getInt("osp.web.server.port", 22080));
_ports.insert(_httpPort);
_vncPort = static_cast<Poco::UInt16>(getIntConfig("webtunnel.vncPort", 0));
if (_vncPort != 0 && _ports.find(_vncPort) == _ports.end())
{
_pContext->logger().warning(Poco::format("Specified vncPort %hu not in list of forwarded ports (webtunnel.ports) - ignored.", _vncPort));
_vncPort = 0;
}
_localTimeout = Poco::Timespan(getIntConfig("webtunnel.localTimeout", 7200), 0);
_connectTimeout = Poco::Timespan(getIntConfig("webtunnel.connectTimeout", 10), 0);
_remoteTimeout = Poco::Timespan(getIntConfig("webtunnel.remoteTimeout", 300), 0);
_threads = getIntConfig("webtunnel.threads", 4);
_userAgent = getStringConfig("webtunnel.userAgent", "");
_httpTimeout = Poco::Timespan(getIntConfig("webtunnel.http.timeout", 30), 0);
_useProxy = getBoolConfig("webtunnel.http.proxy.enable", false);
_proxyHost = getStringConfig("webtunnel.http.proxy.host", "");
_proxyPort = static_cast<Poco::UInt16>(getIntConfig("webtunnel.http.proxy.port", 80));
_proxyUsername = getStringConfig("webtunnel.http.proxy.username", "");
_proxyPassword = getStringConfig("webtunnel.http.proxy.password", "");
if (_userAgent.empty())
{
_userAgent = pContext->thisBundle()->symbolicName();
_userAgent += "/";
_userAgent += pContext->thisBundle()->version().toString();
_userAgent += " (";
_userAgent += Poco::Environment::osName();
_userAgent += "/";
_userAgent += Poco::Environment::osVersion();
_userAgent += "; ";
_userAgent += Poco::Environment::osArchitecture();
_userAgent += ") POCO/";
_userAgent += Poco::format("%d.%d.%d",
static_cast<int>(Poco::Environment::libraryVersion() >> 24),
static_cast<int>((Poco::Environment::libraryVersion() >> 16) & 0xFF),
static_cast<int>((Poco::Environment::libraryVersion() >> 8) & 0xFF));
}
_pTimer = new Poco::Util::Timer;
_pTimer->schedule(new Poco::Util::TimerTaskAdapter<BundleActivator>(*this, &BundleActivator::reconnect), Poco::Timestamp());
}
catch (Poco::Exception& exc)
{
_pContext->logger().log(exc);
}
}
else
{
_pContext->logger().information("WebTunnel disabled.");
}
}
void stop(BundleContext::Ptr pContext)
{
if (_pTimer)
{
_stopped.set();
disconnect();
_pTimer->cancel(true);
_pTimer = 0;
}
_pPrefs = 0;
_pPrefsService = 0;
_pContext = 0;
}
protected:
bool getBoolConfig(const std::string& key)
{
return _pPrefs->getBool(key, _pPrefsService->configuration()->getBool(key));
}
bool getBoolConfig(const std::string& key, bool deflt)
{
return _pPrefs->getBool(key, _pPrefsService->configuration()->getBool(key, deflt));
}
int getIntConfig(const std::string& key)
{
return _pPrefs->getInt(key, _pPrefsService->configuration()->getInt(key));
}
int getIntConfig(const std::string& key, int deflt)
{
return _pPrefs->getInt(key, _pPrefsService->configuration()->getInt(key, deflt));
}
std::string getStringConfig(const std::string& key)
{
return _pPrefs->getString(key, _pPrefsService->configuration()->getString(key));
}
std::string getStringConfig(const std::string& key, const std::string& deflt)
{
return _pPrefs->getString(key, _pPrefsService->configuration()->getString(key, deflt));
}
void connect()
{
_pContext->logger().information("Connecting to " + _reflectorURI.toString() + "...");
_pHTTPClientSession = Poco::Net::HTTPSessionFactory::defaultFactory().createClientSession(_reflectorURI);
_pHTTPClientSession->setTimeout(_httpTimeout);
if (_useProxy && !_proxyHost.empty())
{
_pHTTPClientSession->setProxy(_proxyHost, _proxyPort);
if (!_proxyUsername.empty())
{
_pHTTPClientSession->setProxyCredentials(_proxyUsername, _proxyPassword);
}
}
std::string path(_reflectorURI.getPathEtc());
if (path.empty()) path = "/";
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, path, Poco::Net::HTTPRequest::HTTP_1_1);
request.set(SEC_WEBSOCKET_PROTOCOL, WEBTUNNEL_PROTOCOL);
if (!_username.empty())
{
Poco::Net::HTTPBasicCredentials creds(_username, _password);
creds.authenticate(request);
}
if (_httpPort != 0)
{
request.add("X-PTTH-Set-Property", Poco::format("device;httpPort=%hu", _httpPort));
}
if (_vncPort != 0)
{
request.add("X-PTTH-Set-Property", Poco::format("device;vncPort=%hu", _vncPort));
}
if (!_deviceName.empty())
{
request.add("X-PTTH-Set-Property", Poco::format("device;name=\"%s\"", _deviceName));
}
request.set("User-Agent", _userAgent);
Poco::Net::HTTPResponse response;
bool reconnect = true;
while (reconnect)
{
_pContext->logger().debug("Entering reconnect loop...");
try
{
Poco::Net::DNS::reload();
_pContext->logger().debug("Creating WebSocket...");
Poco::SharedPtr<Poco::Net::WebSocket> pWebSocket = new Poco::Net::WebSocket(*_pHTTPClientSession, request, response);
if (response.get(SEC_WEBSOCKET_PROTOCOL, "") == WEBTUNNEL_PROTOCOL)
{
_pContext->logger().debug("WebSocket established. Creating RemotePortForwarder...");
_pDispatcher = new Poco::WebTunnel::SocketDispatcher(_threads);
_pForwarder = new Poco::WebTunnel::RemotePortForwarder(*_pDispatcher, pWebSocket, _host, _ports, _remoteTimeout);
_pForwarder->setConnectTimeout(_connectTimeout);
_pForwarder->setLocalTimeout(_localTimeout);
_pForwarder->webSocketClosed += Poco::delegate(this, &BundleActivator::onClose);
_retryDelay = 1000;
_pContext->logger().information("WebTunnel connection established.");
pWebSocket->setNoDelay(true);
return;
}
else
{
_pContext->logger().error(Poco::format("The host at %s does not support the WebTunnel protocol.", _reflectorURI.toString()));
pWebSocket->shutdown(Poco::Net::WebSocket::WS_PROTOCOL_ERROR);
// receive final frame from peer; ignore if none is sent.
if (pWebSocket->poll(Poco::Timespan(2, 0), Poco::Net::Socket::SELECT_READ))
{
Poco::Buffer<char> buffer(1024);
int flags;
try
{
pWebSocket->receiveFrame(buffer.begin(), static_cast<int>(buffer.size()), flags);
}
catch (Poco::Exception&)
{
}
}
pWebSocket->close();
reconnect = false;
}
}
catch (Poco::Exception& exc)
{
_pContext->logger().error(Poco::format("Cannot connect to reflector at %s: %s", _reflectorURI.toString(), exc.displayText()));
if (_retryDelay < 30000)
{
_retryDelay *= 2;
}
reconnect = !_stopped.tryWait(_retryDelay);
}
}
}
void disconnect()
{
if (_pForwarder)
{
_pContext->logger().information("Disconnecting from reflector server");
_pForwarder->webSocketClosed -= Poco::delegate(this, &BundleActivator::onClose);
_pForwarder->stop();
_pForwarder = 0;
_pDispatcher = 0;
}
if (_pHTTPClientSession)
{
try
{
_pHTTPClientSession->abort();
}
catch (Poco::Exception&)
{
}
}
}
void onClose(const int& reason)
{
_pContext->logger().information("WebTunnel connection closed.");
if (!_stopped.tryWait(_retryDelay))
{
_pTimer->schedule(new Poco::Util::TimerTaskAdapter<BundleActivator>(*this, &BundleActivator::reconnect), Poco::Timestamp());
}
}
void reconnect(Poco::Util::TimerTask&)
{
try
{
disconnect();
connect();
}
catch (Poco::Exception& exc)
{
_pContext->logger().fatal(exc.displayText());
}
}
static const std::string SEC_WEBSOCKET_PROTOCOL;
static const std::string WEBTUNNEL_PROTOCOL;
private:
BundleContext::Ptr _pContext;
PreferencesService::Ptr _pPrefsService;
Preferences::Ptr _pPrefs;
Poco::Net::IPAddress _host;
std::set<Poco::UInt16> _ports;
Poco::URI _reflectorURI;
std::string _deviceName;
std::string _username;
std::string _password;
std::string _userAgent;
Poco::UInt16 _httpPort;
Poco::UInt16 _vncPort;
bool _useProxy;
std::string _proxyHost;
Poco::UInt16 _proxyPort;
std::string _proxyUsername;
std::string _proxyPassword;
Poco::Timespan _localTimeout;
Poco::Timespan _connectTimeout;
Poco::Timespan _remoteTimeout;
Poco::Timespan _httpTimeout;
int _threads;
Poco::SharedPtr<Poco::WebTunnel::SocketDispatcher> _pDispatcher;
Poco::SharedPtr<Poco::WebTunnel::RemotePortForwarder> _pForwarder;
Poco::SharedPtr<Poco::Net::HTTPClientSession> _pHTTPClientSession;
Poco::Event _stopped;
int _retryDelay;
Poco::SharedPtr<Poco::Util::Timer> _pTimer;
};
const std::string BundleActivator::SEC_WEBSOCKET_PROTOCOL("Sec-WebSocket-Protocol");
const std::string BundleActivator::WEBTUNNEL_PROTOCOL("com.appinf.webtunnel.server/1.0");
} } // namespace IoT::WebTunnel
POCO_BEGIN_MANIFEST(Poco::OSP::BundleActivator)
POCO_EXPORT_CLASS(IoT::WebTunnel::BundleActivator)
POCO_END_MANIFEST
<|endoftext|> |
<commit_before><commit_msg>use read_uInt8s_AsOString here<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unokywds.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-16 19:26:22 $
*
* 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_sd.hxx"
#ifndef _SD_UNOKYWDS_HXX_
#define SD_DEFINE_KEYWORDS
#include <unokywds.hxx>
#undef SD_DEFINE_KEYWORDS
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.358); FILE MERGED 2008/03/31 13:59:08 rt 1.4.358.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: unokywds.cxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#ifndef _SD_UNOKYWDS_HXX_
#define SD_DEFINE_KEYWORDS
#include <unokywds.hxx>
#undef SD_DEFINE_KEYWORDS
#endif
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.