text
stringlengths 54
60.6k
|
|---|
<commit_before>#include <string.hpp>
#include <locale> // for wstring_convert
#include <codecvt> // for codecvt_utf8_utf16
#include <cctype> // for tolower and toupper
#include <algorithm> // for transform
#include <libgen.h> // for dirname and basename
#include <zlib.h>
namespace rack {
namespace string {
std::string fromWstring(const std::wstring& s) {
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.to_bytes(s);
}
std::wstring toWstring(const std::string& s) {
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.from_bytes(s);
}
std::string f(const char* format, ...) {
va_list args;
va_start(args, format);
// Compute size of required buffer
int size = vsnprintf(NULL, 0, format, args);
va_end(args);
if (size < 0)
return "";
// Create buffer
std::string s;
s.resize(size);
va_start(args, format);
vsnprintf(&s[0], size + 1, format, args);
va_end(args);
return s;
}
std::string lowercase(const std::string& s) {
std::string r = s;
std::transform(r.begin(), r.end(), r.begin(), [](unsigned char c) {
return std::tolower(c);
});
return r;
}
std::string uppercase(const std::string& s) {
std::string r = s;
std::transform(r.begin(), r.end(), r.begin(), [](unsigned char c) {
return std::toupper(c);
});
return r;
}
std::string trim(const std::string& s) {
const std::string whitespace = " \n\r\t";
size_t first = s.find_first_not_of(whitespace);
if (first == std::string::npos)
return "";
size_t last = s.find_last_not_of(whitespace);
if (last == std::string::npos)
return "";
return s.substr(first, last - first + 1);
}
std::string ellipsize(const std::string& s, size_t len) {
if (s.size() <= len)
return s;
else
return s.substr(0, len - 3) + "...";
}
std::string ellipsizePrefix(const std::string& s, size_t len) {
if (s.size() <= len)
return s;
else
return "..." + s.substr(s.size() - (len - 3));
}
bool startsWith(const std::string& str, const std::string& prefix) {
return str.substr(0, prefix.size()) == prefix;
}
bool endsWith(const std::string& str, const std::string& suffix) {
return str.substr(str.size() - suffix.size(), suffix.size()) == suffix;
}
std::string directory(const std::string& path) {
char* pathDup = strdup(path.c_str());
std::string directory = dirname(pathDup);
free(pathDup);
return directory;
}
std::string filename(const std::string& path) {
char* pathDup = strdup(path.c_str());
std::string filename = basename(pathDup);
free(pathDup);
return filename;
}
std::string filenameBase(const std::string& filename) {
size_t pos = filename.rfind('.');
if (pos == std::string::npos)
return filename;
return std::string(filename, 0, pos);
}
std::string filenameExtension(const std::string& filename) {
size_t pos = filename.rfind('.');
if (pos == std::string::npos)
return "";
return std::string(filename, pos + 1);
}
std::string absolutePath(const std::string& path) {
#if defined ARCH_LIN || defined ARCH_MAC
char buf[PATH_MAX];
char* absPathC = realpath(path.c_str(), buf);
if (absPathC)
return absPathC;
#elif defined ARCH_WIN
std::wstring pathW = toWstring(path);
wchar_t buf[PATH_MAX];
wchar_t* absPathC = _wfullpath(buf, pathW.c_str(), PATH_MAX);
if (absPathC)
return fromWstring(absPathC);
#endif
return "";
}
float fuzzyScore(const std::string& s, const std::string& query) {
size_t pos = s.find(query);
if (pos == std::string::npos)
return 0.f;
return (float)(query.size() + 1) / (s.size() + 1);
}
std::string toBase64(const uint8_t* data, size_t dataLen) {
static const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
size_t numBlocks = (dataLen + 2) / 3;
size_t strLen = numBlocks * 4;
std::string str;
str.reserve(strLen);
for (size_t b = 0; b < numBlocks; b++) {
// Encode block
uint32_t block = 0;
int i;
for (i = 0; i < 3 && 3 * b + i < dataLen; i++) {
block |= uint32_t(data[3 * b + i]) << (8 * (2 - i));
}
// Decode block
str += alphabet[(block >> 18) & 0x3f];
str += alphabet[(block >> 12) & 0x3f];
str += (i > 1) ? alphabet[(block >> 6) & 0x3f] : '=';
str += (i > 2) ? alphabet[(block >> 0) & 0x3f] : '=';
}
return str;
}
std::string toBase64(const std::vector<uint8_t>& data) {
return toBase64(data.data(), data.size());
}
std::vector<uint8_t> fromBase64(const std::string& str) {
size_t strLen = str.size();
if (strLen % 4 != 0)
throw std::runtime_error("String length not a factor of 4");
size_t numBlocks = strLen / 4;
size_t len = numBlocks * 3;
if (strLen >= 4) {
if (str[strLen - 1] == '=')
len--;
if (str[strLen - 2] == '=')
len--;
}
std::vector<uint8_t> data(len);
for (size_t b = 0; b < numBlocks; b++) {
// Encode block
uint32_t block = 0;
size_t i;
for (i = 0; i < 4; i++) {
uint8_t c = str[4 * b + i];
uint8_t d = 0;
if ('A' <= c && c <= 'Z') {
d = c - 'A';
}
else if ('a' <= c && c <= 'z') {
d = c - 'a' + 26;
}
else if ('0' <= c && c <= '9') {
d = c - '0' + 52;
}
else if (c == '+') {
d = 62;
}
else if (c == '/') {
d = 63;
}
else if (c == '=') {
// Padding ends block encoding
break;
}
else {
// Since we assumed the string was a factor of 4 bytes, fail if an invalid character, such as whitespace, was found.
throw std::runtime_error("String contains non-base64 character");
}
block |= uint32_t(d) << (6 * (3 - i));
}
// Decode block
for (size_t k = 0; k < i - 1; k++) {
data[3 * b + k] = (block >> (8 * (2 - k))) & 0xff;
}
}
return data;
}
std::vector<uint8_t> compress(const uint8_t* data, size_t dataLen) {
std::vector<uint8_t> compressed;
size_t outCap = ::compressBound(dataLen);
compressed.resize(outCap);
int err = ::compress2(compressed.data(), &outCap, data, dataLen, Z_BEST_COMPRESSION);
if (err)
throw std::runtime_error("Zlib error");
compressed.resize(outCap);
return compressed;
}
std::vector<uint8_t> compress(const std::vector<uint8_t>& data) {
return compress(data.data(), data.size());
}
void uncompress(const uint8_t* compressed, size_t compressedLen, uint8_t* data, size_t* dataLen) {
int err = ::uncompress(data, dataLen, compressed, compressedLen);
(void) err;
}
void uncompress(const std::vector<uint8_t>& compressed, uint8_t* data, size_t* dataLen) {
uncompress(compressed.data(), compressed.size(), data, dataLen);
}
} // namespace string
} // namespace rack
<commit_msg>Use zlib types for string::compress/uncompress implementation.<commit_after>#include <string.hpp>
#include <locale> // for wstring_convert
#include <codecvt> // for codecvt_utf8_utf16
#include <cctype> // for tolower and toupper
#include <algorithm> // for transform
#include <libgen.h> // for dirname and basename
#include <zlib.h>
namespace rack {
namespace string {
std::string fromWstring(const std::wstring& s) {
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.to_bytes(s);
}
std::wstring toWstring(const std::string& s) {
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.from_bytes(s);
}
std::string f(const char* format, ...) {
va_list args;
va_start(args, format);
// Compute size of required buffer
int size = vsnprintf(NULL, 0, format, args);
va_end(args);
if (size < 0)
return "";
// Create buffer
std::string s;
s.resize(size);
va_start(args, format);
vsnprintf(&s[0], size + 1, format, args);
va_end(args);
return s;
}
std::string lowercase(const std::string& s) {
std::string r = s;
std::transform(r.begin(), r.end(), r.begin(), [](unsigned char c) {
return std::tolower(c);
});
return r;
}
std::string uppercase(const std::string& s) {
std::string r = s;
std::transform(r.begin(), r.end(), r.begin(), [](unsigned char c) {
return std::toupper(c);
});
return r;
}
std::string trim(const std::string& s) {
const std::string whitespace = " \n\r\t";
size_t first = s.find_first_not_of(whitespace);
if (first == std::string::npos)
return "";
size_t last = s.find_last_not_of(whitespace);
if (last == std::string::npos)
return "";
return s.substr(first, last - first + 1);
}
std::string ellipsize(const std::string& s, size_t len) {
if (s.size() <= len)
return s;
else
return s.substr(0, len - 3) + "...";
}
std::string ellipsizePrefix(const std::string& s, size_t len) {
if (s.size() <= len)
return s;
else
return "..." + s.substr(s.size() - (len - 3));
}
bool startsWith(const std::string& str, const std::string& prefix) {
return str.substr(0, prefix.size()) == prefix;
}
bool endsWith(const std::string& str, const std::string& suffix) {
return str.substr(str.size() - suffix.size(), suffix.size()) == suffix;
}
std::string directory(const std::string& path) {
char* pathDup = strdup(path.c_str());
std::string directory = dirname(pathDup);
free(pathDup);
return directory;
}
std::string filename(const std::string& path) {
char* pathDup = strdup(path.c_str());
std::string filename = basename(pathDup);
free(pathDup);
return filename;
}
std::string filenameBase(const std::string& filename) {
size_t pos = filename.rfind('.');
if (pos == std::string::npos)
return filename;
return std::string(filename, 0, pos);
}
std::string filenameExtension(const std::string& filename) {
size_t pos = filename.rfind('.');
if (pos == std::string::npos)
return "";
return std::string(filename, pos + 1);
}
std::string absolutePath(const std::string& path) {
#if defined ARCH_LIN || defined ARCH_MAC
char buf[PATH_MAX];
char* absPathC = realpath(path.c_str(), buf);
if (absPathC)
return absPathC;
#elif defined ARCH_WIN
std::wstring pathW = toWstring(path);
wchar_t buf[PATH_MAX];
wchar_t* absPathC = _wfullpath(buf, pathW.c_str(), PATH_MAX);
if (absPathC)
return fromWstring(absPathC);
#endif
return "";
}
float fuzzyScore(const std::string& s, const std::string& query) {
size_t pos = s.find(query);
if (pos == std::string::npos)
return 0.f;
return (float)(query.size() + 1) / (s.size() + 1);
}
std::string toBase64(const uint8_t* data, size_t dataLen) {
static const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
size_t numBlocks = (dataLen + 2) / 3;
size_t strLen = numBlocks * 4;
std::string str;
str.reserve(strLen);
for (size_t b = 0; b < numBlocks; b++) {
// Encode block
uint32_t block = 0;
int i;
for (i = 0; i < 3 && 3 * b + i < dataLen; i++) {
block |= uint32_t(data[3 * b + i]) << (8 * (2 - i));
}
// Decode block
str += alphabet[(block >> 18) & 0x3f];
str += alphabet[(block >> 12) & 0x3f];
str += (i > 1) ? alphabet[(block >> 6) & 0x3f] : '=';
str += (i > 2) ? alphabet[(block >> 0) & 0x3f] : '=';
}
return str;
}
std::string toBase64(const std::vector<uint8_t>& data) {
return toBase64(data.data(), data.size());
}
std::vector<uint8_t> fromBase64(const std::string& str) {
size_t strLen = str.size();
if (strLen % 4 != 0)
throw std::runtime_error("String length not a factor of 4");
size_t numBlocks = strLen / 4;
size_t len = numBlocks * 3;
if (strLen >= 4) {
if (str[strLen - 1] == '=')
len--;
if (str[strLen - 2] == '=')
len--;
}
std::vector<uint8_t> data(len);
for (size_t b = 0; b < numBlocks; b++) {
// Encode block
uint32_t block = 0;
size_t i;
for (i = 0; i < 4; i++) {
uint8_t c = str[4 * b + i];
uint8_t d = 0;
if ('A' <= c && c <= 'Z') {
d = c - 'A';
}
else if ('a' <= c && c <= 'z') {
d = c - 'a' + 26;
}
else if ('0' <= c && c <= '9') {
d = c - '0' + 52;
}
else if (c == '+') {
d = 62;
}
else if (c == '/') {
d = 63;
}
else if (c == '=') {
// Padding ends block encoding
break;
}
else {
// Since we assumed the string was a factor of 4 bytes, fail if an invalid character, such as whitespace, was found.
throw std::runtime_error("String contains non-base64 character");
}
block |= uint32_t(d) << (6 * (3 - i));
}
// Decode block
for (size_t k = 0; k < i - 1; k++) {
data[3 * b + k] = (block >> (8 * (2 - k))) & 0xff;
}
}
return data;
}
std::vector<uint8_t> compress(const uint8_t* data, size_t dataLen) {
std::vector<uint8_t> compressed;
uLongf outCap = ::compressBound(dataLen);
compressed.resize(outCap);
int err = ::compress2(compressed.data(), &outCap, data, dataLen, Z_BEST_COMPRESSION);
if (err)
throw std::runtime_error("Zlib error");
compressed.resize(outCap);
return compressed;
}
std::vector<uint8_t> compress(const std::vector<uint8_t>& data) {
return compress(data.data(), data.size());
}
void uncompress(const uint8_t* compressed, size_t compressedLen, uint8_t* data, size_t* dataLen) {
uLongf dataLenF = *dataLen;
int err = ::uncompress(data, &dataLenF, compressed, compressedLen);
(void) err;
*dataLen = dataLenF;
}
void uncompress(const std::vector<uint8_t>& compressed, uint8_t* data, size_t* dataLen) {
uncompress(compressed.data(), compressed.size(), data, dataLen);
}
} // namespace string
} // namespace rack
<|endoftext|>
|
<commit_before>#pragma once
#include "numerics/polynomial_evaluators.hpp"
#include <cstddef>
#include <tuple>
#include "base/bits.hpp"
#include "quantities/elementary_functions.hpp"
namespace principia {
namespace numerics {
namespace internal_polynomial_evaluators {
using base::FloorLog2;
using base::PowerOf2Le;
using quantities::FusedMultiplyAdd;
// Generator for repeated squaring:
// SquareGenerator<Length, 0>::Type is Exponentiation<Length, 2>
// SquareGenerator<Length, 1>::Type is Exponentiation<Length, 4>
// SquareGenerator<Length, n>::Type is Exponentiation<Length, 2^(n + 1)>
// etc.
template<typename Argument, int n>
struct SquareGenerator {
using Type = Square<typename SquareGenerator<Argument, n - 1>::Type>;
static Type Evaluate(Argument const& argument);
};
template<typename Argument>
struct SquareGenerator<Argument, 0> {
using Type = Square<Argument>;
static Type Evaluate(Argument const& argument);
};
template<typename Argument, typename>
struct SquaresGenerator;
template<typename Argument, std::size_t... orders>
struct SquaresGenerator<Argument, std::index_sequence<orders...>> {
using Type = std::tuple<typename SquareGenerator<Argument, orders>::Type...>;
static Type Evaluate(Argument const& argument);
};
template<typename Argument, int n>
auto SquareGenerator<Argument, n>::Evaluate(Argument const& argument) -> Type {
auto const argument_n_minus_1 =
SquareGenerator<Argument, n - 1>::Evaluate(argument);
return argument_n_minus_1 * argument_n_minus_1;
}
template<typename Argument>
auto SquareGenerator<Argument, 0>::Evaluate(Argument const& argument) -> Type {
return argument * argument;
}
template<typename Argument, std::size_t... orders>
auto SquaresGenerator<Argument, std::index_sequence<orders...>>::
Evaluate(Argument const& argument) -> Type {
return std::make_tuple(
SquareGenerator<Argument, orders>::Evaluate(argument)...);
}
// Internal helper for Estrin evaluation. |degree| is the degree of the overall
// polynomial, |low| and |subdegree| defines the subpolynomial that we currently
// evaluate, i.e., the one with a constant term coefficient
// |std::get<low>(coefficients)| and degree |subdegree|.
template<typename Value, typename Argument, int degree, int low, int subdegree, bool fma>
struct InternalEstrinEvaluator {
using ArgumentSquaresGenerator =
SquaresGenerator<Argument, std::make_index_sequence<FloorLog2(degree)>>;
using ArgumentSquares = typename ArgumentSquaresGenerator::Type;
using Coefficients =
typename PolynomialInMonomialBasis<Value, Argument, degree,
EstrinEvaluator>::Coefficients;
FORCE_INLINE(static) Derivative<Value, Argument, low> Evaluate(
Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares);
FORCE_INLINE(static) Derivative<Value, Argument, low> EvaluateDerivative(
Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares);
};
template<typename Value, typename Argument, int degree, int low, bool fma>
struct InternalEstrinEvaluator<Value, Argument, degree, low, 1, fma> {
using ArgumentSquaresGenerator =
SquaresGenerator<Argument, std::make_index_sequence<FloorLog2(degree)>>;
using ArgumentSquares = typename ArgumentSquaresGenerator::Type;
using Coefficients =
typename PolynomialInMonomialBasis<Value, Argument, degree,
EstrinEvaluator>::Coefficients;
FORCE_INLINE(static) Derivative<Value, Argument, low> Evaluate(
Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares);
FORCE_INLINE(static) Derivative<Value, Argument, low> EvaluateDerivative(
Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares);
};
template<typename Value, typename Argument, int degree, int low, bool fma>
struct InternalEstrinEvaluator<Value, Argument, degree, low, 0, fma> {
using ArgumentSquaresGenerator =
SquaresGenerator<Argument, std::make_index_sequence<FloorLog2(degree)>>;
using ArgumentSquares = typename ArgumentSquaresGenerator::Type;
using Coefficients =
typename PolynomialInMonomialBasis<Value, Argument, degree,
EstrinEvaluator>::Coefficients;
FORCE_INLINE(static) Derivative<Value, Argument, low> Evaluate(
Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares);
FORCE_INLINE(static) Derivative<Value, Argument, low> EvaluateDerivative(
Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares);
};
template<typename Value,
typename Argument,
int degree,
int low,
int subdegree,
bool fma>
Derivative<Value, Argument, low>
InternalEstrinEvaluator<Value, Argument, degree, low, subdegree, fma>::Evaluate(
Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares) {
static_assert(subdegree >= 2,
"Unexpected subdegree in InternalEstrinEvaluator::Evaluate");
// |n| is used to select |argument^(2^(n + 1))| = |argument^m|.
constexpr int n = FloorLog2(subdegree) - 1;
// |m| is |2^(n + 1)|.
constexpr int m = PowerOf2Le(subdegree);
auto const& xᵐ = std::get<n>(argument_squares);
auto const a = InternalEstrinEvaluator<Value,
Argument,
degree,
low + m,
subdegree - m,
fma>::Evaluate(coefficients,
argument,
argument_squares);
auto const b =
InternalEstrinEvaluator<Value, Argument, degree, low, m - 1, fma>::
Evaluate(coefficients, argument, argument_squares);
if constexpr (fma) {
return FusedMultiplyAdd(a, xᵐ, b);
} else {
return a * xᵐ + b;
}
}
template<typename Value,
typename Argument,
int degree,
int low,
int subdegree,
bool fma>
Derivative<Value, Argument, low>
InternalEstrinEvaluator<Value, Argument, degree, low, subdegree, fma>::
EvaluateDerivative(Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares) {
static_assert(subdegree >= 2,
"Unexpected subdegree in InternalEstrinEvaluator::"
"EvaluateDerivative");
// |n| is used to select |argument^(2^(n + 1))| = |argument^m|.
constexpr int n = FloorLog2(subdegree) - 1;
// |m| is |2^(n + 1)|.
constexpr int m = PowerOf2Le(subdegree);
auto const& xᵐ = std::get<n>(argument_squares);
auto const a =
InternalEstrinEvaluator<Value,
Argument,
degree,
low + m,
subdegree - m,
fma>::EvaluateDerivative(coefficients,
argument,
argument_squares);
auto const b =
InternalEstrinEvaluator<Value, Argument, degree, low, m - 1, fma>::
EvaluateDerivative(coefficients, argument, argument_squares);
if constexpr (fma) {
return FusedMultiplyAdd(a, xᵐ, b);
} else {
return a * xᵐ + b;
}
}
template<typename Value, typename Argument, int degree, int low, bool fma>
Derivative<Value, Argument, low>
InternalEstrinEvaluator<Value, Argument, degree, low, 1, fma>::Evaluate(
Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares) {
auto const& x = argument;
auto const& a = std::get<low + 1>(coefficients);
auto const& b = std::get<low>(coefficients);
if constexpr (fma) {
return FusedMultiplyAdd(a, x, b);
} else {
return a * x + b;
}
}
template<typename Value, typename Argument, int degree, int low, bool fma>
Derivative<Value, Argument, low>
InternalEstrinEvaluator<Value, Argument, degree, low, 0, fma>::Evaluate(
Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares) {
return std::get<low>(coefficients);
}
template<typename Value, typename Argument, int degree, int low, bool fma>
Derivative<Value, Argument, low>
InternalEstrinEvaluator<Value, Argument, degree, low, 1, fma>::
EvaluateDerivative(Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares) {
auto const& x = argument;
auto const& a = low * std::get<low>(coefficients);
auto const& b = (low + 1) * std::get<low + 1>(coefficients);
if constexpr (fma) {
return FusedMultiplyAdd(a, x, b);
} else {
return a * x + b;
}
}
template<typename Value, typename Argument, int degree, int low, bool fma>
Derivative<Value, Argument, low>
InternalEstrinEvaluator<Value, Argument, degree, low, 0, fma>::
EvaluateDerivative(Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares) {
return low * std::get<low>(coefficients);
}
template<typename Value, typename Argument, int degree>
template<bool fma>
Value EstrinEvaluator<Value, Argument, degree>::Evaluate(
Coefficients const& coefficients,
Argument const& argument) {
using InternalEvaluator = InternalEstrinEvaluator<Value,
Argument,
degree,
/*low=*/0,
/*subdegree=*/degree,
fma>;
return InternalEvaluator::Evaluate(
coefficients,
argument,
InternalEvaluator::ArgumentSquaresGenerator::Evaluate(argument));
}
template<typename Value, typename Argument, int degree>
template<bool fma>
Derivative<Value, Argument>
EstrinEvaluator<Value, Argument, degree>::EvaluateDerivative(
Coefficients const& coefficients,
Argument const& argument) {
if constexpr (degree == 0) {
return Derivative<Value, Argument>{};
} else {
using InternalEvaluator = InternalEstrinEvaluator<Value,
Argument,
degree,
/*low=*/1,
/*subdegree=*/degree - 1,
fma>;
return InternalEvaluator::EvaluateDerivative(
coefficients,
argument,
InternalEvaluator::ArgumentSquaresGenerator::Evaluate(argument));
}
}
// Internal helper for Horner evaluation. |degree| is the degree of the overall
// polynomial, |low| defines the subpolynomial that we currently evaluate, i.e.,
// the one with a constant term coefficient |std::get<low>(coefficients)|.
template<typename Value, typename Argument, int degree, int low, bool fma>
struct InternalHornerEvaluator {
using Coefficients =
typename PolynomialInMonomialBasis<Value, Argument, degree,
HornerEvaluator>::Coefficients;
FORCE_INLINE(static) Derivative<Value, Argument, low>
Evaluate(Coefficients const& coefficients,
Argument const& argument);
FORCE_INLINE(static) Derivative<Value, Argument, low>
EvaluateDerivative(Coefficients const& coefficients,
Argument const& argument);
};
template<typename Value, typename Argument, int degree, bool fma>
struct InternalHornerEvaluator<Value, Argument, degree, degree, fma> {
using Coefficients =
typename PolynomialInMonomialBasis<Value, Argument, degree,
HornerEvaluator>::Coefficients;
FORCE_INLINE(static) Derivative<Value, Argument, degree>
Evaluate(Coefficients const& coefficients,
Argument const& argument);
FORCE_INLINE(static) Derivative<Value, Argument, degree>
EvaluateDerivative(Coefficients const& coefficients,
Argument const& argument);
};
template<typename Value, typename Argument, int degree, int low, bool fma>
Derivative<Value, Argument, low>
InternalHornerEvaluator<Value, Argument, degree, low, fma>::Evaluate(
Coefficients const& coefficients,
Argument const& argument) {
auto const& x = argument;
auto const a =
InternalHornerEvaluator<Value, Argument, degree, low + 1, fma>::Evaluate(
coefficients, argument);
auto const& b = std::get<low>(coefficients);
if constexpr (fma) {
return FusedMultiplyAdd(a, x, b);
} else {
return a * x + b;
}
}
template<typename Value, typename Argument, int degree, int low, bool fma>
Derivative<Value, Argument, low>
InternalHornerEvaluator<Value, Argument, degree, low, fma>::EvaluateDerivative(
Coefficients const& coefficients,
Argument const& argument) {
auto const& x = argument;
auto const a =
InternalHornerEvaluator<Value, Argument, degree, low + 1, fma>::
EvaluateDerivative(coefficients, argument);
auto const b = std::get<low>(coefficients) * low;
if constexpr (fma) {
return FusedMultiplyAdd(a, x, b);
} else {
return a * x + b;
}
}
template<typename Value, typename Argument, int degree, bool fma>
Derivative<Value, Argument, degree>
InternalHornerEvaluator<Value, Argument, degree, degree, fma>::Evaluate(
Coefficients const& coefficients,
Argument const& argument) {
return std::get<degree>(coefficients);
}
template<typename Value, typename Argument, int degree, bool fma>
Derivative<Value, Argument, degree>
InternalHornerEvaluator<Value, Argument, degree, degree, fma>::
EvaluateDerivative(Coefficients const& coefficients,
Argument const& argument) {
return std::get<degree>(coefficients) * degree;
}
template<typename Value, typename Argument, int degree>
template<bool fma>
Value HornerEvaluator<Value, Argument, degree>::Evaluate(
Coefficients const& coefficients,
Argument const& argument) {
return InternalHornerEvaluator<Value, Argument, degree, /*low=*/0, fma>::
Evaluate(coefficients, argument);
}
template<typename Value, typename Argument, int degree>
template<bool fma>
Derivative<Value, Argument>
HornerEvaluator<Value, Argument, degree>::EvaluateDerivative(
Coefficients const& coefficients,
Argument const& argument) {
if constexpr (degree == 0) {
return Derivative<Value, Argument>{};
} else {
return InternalHornerEvaluator<Value, Argument, degree, /*low=*/1, fma>::
EvaluateDerivative(coefficients, argument);
}
}
} // namespace internal_polynomial_evaluators
} // namespace numerics
} // namespace principia
<commit_msg>all hail the typechecking<commit_after>#pragma once
#include "numerics/polynomial_evaluators.hpp"
#include <cstddef>
#include <tuple>
#include "base/bits.hpp"
#include "quantities/elementary_functions.hpp"
namespace principia {
namespace numerics {
namespace internal_polynomial_evaluators {
using base::FloorLog2;
using base::PowerOf2Le;
using quantities::FusedMultiplyAdd;
// Generator for repeated squaring:
// SquareGenerator<Length, 0>::Type is Exponentiation<Length, 2>
// SquareGenerator<Length, 1>::Type is Exponentiation<Length, 4>
// SquareGenerator<Length, n>::Type is Exponentiation<Length, 2^(n + 1)>
// etc.
template<typename Argument, int n>
struct SquareGenerator {
using Type = Square<typename SquareGenerator<Argument, n - 1>::Type>;
static Type Evaluate(Argument const& argument);
};
template<typename Argument>
struct SquareGenerator<Argument, 0> {
using Type = Square<Argument>;
static Type Evaluate(Argument const& argument);
};
template<typename Argument, typename>
struct SquaresGenerator;
template<typename Argument, std::size_t... orders>
struct SquaresGenerator<Argument, std::index_sequence<orders...>> {
using Type = std::tuple<typename SquareGenerator<Argument, orders>::Type...>;
static Type Evaluate(Argument const& argument);
};
template<typename Argument, int n>
auto SquareGenerator<Argument, n>::Evaluate(Argument const& argument) -> Type {
auto const argument_n_minus_1 =
SquareGenerator<Argument, n - 1>::Evaluate(argument);
return argument_n_minus_1 * argument_n_minus_1;
}
template<typename Argument>
auto SquareGenerator<Argument, 0>::Evaluate(Argument const& argument) -> Type {
return argument * argument;
}
template<typename Argument, std::size_t... orders>
auto SquaresGenerator<Argument, std::index_sequence<orders...>>::
Evaluate(Argument const& argument) -> Type {
return std::make_tuple(
SquareGenerator<Argument, orders>::Evaluate(argument)...);
}
// Internal helper for Estrin evaluation. |degree| is the degree of the overall
// polynomial, |low| and |subdegree| defines the subpolynomial that we currently
// evaluate, i.e., the one with a constant term coefficient
// |std::get<low>(coefficients)| and degree |subdegree|.
template<typename Value, typename Argument, int degree, int low, int subdegree, bool fma>
struct InternalEstrinEvaluator {
using ArgumentSquaresGenerator =
SquaresGenerator<Argument, std::make_index_sequence<FloorLog2(degree)>>;
using ArgumentSquares = typename ArgumentSquaresGenerator::Type;
using Coefficients =
typename PolynomialInMonomialBasis<Value, Argument, degree,
EstrinEvaluator>::Coefficients;
FORCE_INLINE(static) Derivative<Value, Argument, low> Evaluate(
Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares);
FORCE_INLINE(static) Derivative<Value, Argument, low> EvaluateDerivative(
Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares);
};
template<typename Value, typename Argument, int degree, int low, bool fma>
struct InternalEstrinEvaluator<Value, Argument, degree, low, 1, fma> {
using ArgumentSquaresGenerator =
SquaresGenerator<Argument, std::make_index_sequence<FloorLog2(degree)>>;
using ArgumentSquares = typename ArgumentSquaresGenerator::Type;
using Coefficients =
typename PolynomialInMonomialBasis<Value, Argument, degree,
EstrinEvaluator>::Coefficients;
FORCE_INLINE(static) Derivative<Value, Argument, low> Evaluate(
Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares);
FORCE_INLINE(static) Derivative<Value, Argument, low> EvaluateDerivative(
Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares);
};
template<typename Value, typename Argument, int degree, int low, bool fma>
struct InternalEstrinEvaluator<Value, Argument, degree, low, 0, fma> {
using ArgumentSquaresGenerator =
SquaresGenerator<Argument, std::make_index_sequence<FloorLog2(degree)>>;
using ArgumentSquares = typename ArgumentSquaresGenerator::Type;
using Coefficients =
typename PolynomialInMonomialBasis<Value, Argument, degree,
EstrinEvaluator>::Coefficients;
FORCE_INLINE(static) Derivative<Value, Argument, low> Evaluate(
Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares);
FORCE_INLINE(static) Derivative<Value, Argument, low> EvaluateDerivative(
Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares);
};
template<typename Value,
typename Argument,
int degree,
int low,
int subdegree,
bool fma>
Derivative<Value, Argument, low>
InternalEstrinEvaluator<Value, Argument, degree, low, subdegree, fma>::Evaluate(
Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares) {
static_assert(subdegree >= 2,
"Unexpected subdegree in InternalEstrinEvaluator::Evaluate");
// |n| is used to select |argument^(2^(n + 1))| = |argument^m|.
constexpr int n = FloorLog2(subdegree) - 1;
// |m| is |2^(n + 1)|.
constexpr int m = PowerOf2Le(subdegree);
auto const& xᵐ = std::get<n>(argument_squares);
auto const a = InternalEstrinEvaluator<Value,
Argument,
degree,
low + m,
subdegree - m,
fma>::Evaluate(coefficients,
argument,
argument_squares);
auto const b =
InternalEstrinEvaluator<Value, Argument, degree, low, m - 1, fma>::
Evaluate(coefficients, argument, argument_squares);
if constexpr (fma) {
return FusedMultiplyAdd(a, xᵐ, b);
} else {
return a * xᵐ + b;
}
}
template<typename Value,
typename Argument,
int degree,
int low,
int subdegree,
bool fma>
Derivative<Value, Argument, low>
InternalEstrinEvaluator<Value, Argument, degree, low, subdegree, fma>::
EvaluateDerivative(Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares) {
static_assert(subdegree >= 2,
"Unexpected subdegree in InternalEstrinEvaluator::"
"EvaluateDerivative");
// |n| is used to select |argument^(2^(n + 1))| = |argument^m|.
constexpr int n = FloorLog2(subdegree) - 1;
// |m| is |2^(n + 1)|.
constexpr int m = PowerOf2Le(subdegree);
auto const& xᵐ = std::get<n>(argument_squares);
auto const a =
InternalEstrinEvaluator<Value,
Argument,
degree,
low + m,
subdegree - m,
fma>::EvaluateDerivative(coefficients,
argument,
argument_squares);
auto const b =
InternalEstrinEvaluator<Value, Argument, degree, low, m - 1, fma>::
EvaluateDerivative(coefficients, argument, argument_squares);
if constexpr (fma) {
return FusedMultiplyAdd(a, xᵐ, b);
} else {
return a * xᵐ + b;
}
}
template<typename Value, typename Argument, int degree, int low, bool fma>
Derivative<Value, Argument, low>
InternalEstrinEvaluator<Value, Argument, degree, low, 1, fma>::Evaluate(
Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares) {
auto const& x = argument;
auto const& a = std::get<low + 1>(coefficients);
auto const& b = std::get<low>(coefficients);
if constexpr (fma) {
return FusedMultiplyAdd(a, x, b);
} else {
return a * x + b;
}
}
template<typename Value, typename Argument, int degree, int low, bool fma>
Derivative<Value, Argument, low>
InternalEstrinEvaluator<Value, Argument, degree, low, 0, fma>::Evaluate(
Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares) {
return std::get<low>(coefficients);
}
template<typename Value, typename Argument, int degree, int low, bool fma>
Derivative<Value, Argument, low>
InternalEstrinEvaluator<Value, Argument, degree, low, 1, fma>::
EvaluateDerivative(Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares) {
auto const& x = argument;
auto const& a = (low + 1) * std::get<low + 1>(coefficients);
auto const& b = low * std::get<low>(coefficients);
if constexpr (fma) {
return FusedMultiplyAdd(a, x, b);
} else {
return a * x + b;
}
}
template<typename Value, typename Argument, int degree, int low, bool fma>
Derivative<Value, Argument, low>
InternalEstrinEvaluator<Value, Argument, degree, low, 0, fma>::
EvaluateDerivative(Coefficients const& coefficients,
Argument const& argument,
ArgumentSquares const& argument_squares) {
return low * std::get<low>(coefficients);
}
template<typename Value, typename Argument, int degree>
template<bool fma>
Value EstrinEvaluator<Value, Argument, degree>::Evaluate(
Coefficients const& coefficients,
Argument const& argument) {
using InternalEvaluator = InternalEstrinEvaluator<Value,
Argument,
degree,
/*low=*/0,
/*subdegree=*/degree,
fma>;
return InternalEvaluator::Evaluate(
coefficients,
argument,
InternalEvaluator::ArgumentSquaresGenerator::Evaluate(argument));
}
template<typename Value, typename Argument, int degree>
template<bool fma>
Derivative<Value, Argument>
EstrinEvaluator<Value, Argument, degree>::EvaluateDerivative(
Coefficients const& coefficients,
Argument const& argument) {
if constexpr (degree == 0) {
return Derivative<Value, Argument>{};
} else {
using InternalEvaluator = InternalEstrinEvaluator<Value,
Argument,
degree,
/*low=*/1,
/*subdegree=*/degree - 1,
fma>;
return InternalEvaluator::EvaluateDerivative(
coefficients,
argument,
InternalEvaluator::ArgumentSquaresGenerator::Evaluate(argument));
}
}
// Internal helper for Horner evaluation. |degree| is the degree of the overall
// polynomial, |low| defines the subpolynomial that we currently evaluate, i.e.,
// the one with a constant term coefficient |std::get<low>(coefficients)|.
template<typename Value, typename Argument, int degree, int low, bool fma>
struct InternalHornerEvaluator {
using Coefficients =
typename PolynomialInMonomialBasis<Value, Argument, degree,
HornerEvaluator>::Coefficients;
FORCE_INLINE(static) Derivative<Value, Argument, low>
Evaluate(Coefficients const& coefficients,
Argument const& argument);
FORCE_INLINE(static) Derivative<Value, Argument, low>
EvaluateDerivative(Coefficients const& coefficients,
Argument const& argument);
};
template<typename Value, typename Argument, int degree, bool fma>
struct InternalHornerEvaluator<Value, Argument, degree, degree, fma> {
using Coefficients =
typename PolynomialInMonomialBasis<Value, Argument, degree,
HornerEvaluator>::Coefficients;
FORCE_INLINE(static) Derivative<Value, Argument, degree>
Evaluate(Coefficients const& coefficients,
Argument const& argument);
FORCE_INLINE(static) Derivative<Value, Argument, degree>
EvaluateDerivative(Coefficients const& coefficients,
Argument const& argument);
};
template<typename Value, typename Argument, int degree, int low, bool fma>
Derivative<Value, Argument, low>
InternalHornerEvaluator<Value, Argument, degree, low, fma>::Evaluate(
Coefficients const& coefficients,
Argument const& argument) {
auto const& x = argument;
auto const a =
InternalHornerEvaluator<Value, Argument, degree, low + 1, fma>::Evaluate(
coefficients, argument);
auto const& b = std::get<low>(coefficients);
if constexpr (fma) {
return FusedMultiplyAdd(a, x, b);
} else {
return a * x + b;
}
}
template<typename Value, typename Argument, int degree, int low, bool fma>
Derivative<Value, Argument, low>
InternalHornerEvaluator<Value, Argument, degree, low, fma>::EvaluateDerivative(
Coefficients const& coefficients,
Argument const& argument) {
auto const& x = argument;
auto const a =
InternalHornerEvaluator<Value, Argument, degree, low + 1, fma>::
EvaluateDerivative(coefficients, argument);
auto const b = std::get<low>(coefficients) * low;
if constexpr (fma) {
return FusedMultiplyAdd(a, x, b);
} else {
return a * x + b;
}
}
template<typename Value, typename Argument, int degree, bool fma>
Derivative<Value, Argument, degree>
InternalHornerEvaluator<Value, Argument, degree, degree, fma>::Evaluate(
Coefficients const& coefficients,
Argument const& argument) {
return std::get<degree>(coefficients);
}
template<typename Value, typename Argument, int degree, bool fma>
Derivative<Value, Argument, degree>
InternalHornerEvaluator<Value, Argument, degree, degree, fma>::
EvaluateDerivative(Coefficients const& coefficients,
Argument const& argument) {
return std::get<degree>(coefficients) * degree;
}
template<typename Value, typename Argument, int degree>
template<bool fma>
Value HornerEvaluator<Value, Argument, degree>::Evaluate(
Coefficients const& coefficients,
Argument const& argument) {
return InternalHornerEvaluator<Value, Argument, degree, /*low=*/0, fma>::
Evaluate(coefficients, argument);
}
template<typename Value, typename Argument, int degree>
template<bool fma>
Derivative<Value, Argument>
HornerEvaluator<Value, Argument, degree>::EvaluateDerivative(
Coefficients const& coefficients,
Argument const& argument) {
if constexpr (degree == 0) {
return Derivative<Value, Argument>{};
} else {
return InternalHornerEvaluator<Value, Argument, degree, /*low=*/1, fma>::
EvaluateDerivative(coefficients, argument);
}
}
} // namespace internal_polynomial_evaluators
} // namespace numerics
} // namespace principia
<|endoftext|>
|
<commit_before>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#include <nvcore/StrLib.h>
#include <nvcore/StdStream.h>
#include <nvcore/Containers.h>
#include <nvimage/Image.h>
#include <nvimage/DirectDrawSurface.h>
#include <nvmath/Color.h>
#include <nvmath/Vector.h>
#include <math.h>
#include "cmdline.h"
static bool loadImage(nv::Image & image, const char * fileName)
{
if (nv::strCaseCmp(nv::Path::extension(fileName), ".dds") == 0)
{
nv::DirectDrawSurface dds(fileName);
if (!dds.isValid())
{
printf("The file '%s' is not a valid DDS file.\n", fileName);
return false;
}
dds.mipmap(&image, 0, 0); // get first image
}
else
{
// Regular image.
if (!image.load(fileName))
{
printf("The file '%s' is not a supported image type.\n", fileName);
return false;
}
}
return true;
}
// @@ Compute per-tile errors.
struct Error
{
Error()
{
samples = 0;
mabse = 0.0f;
maxabse = 0.0f;
mse = 0.0f;
}
void addSample(float e)
{
samples++;
mabse += fabsf(e);
maxabse = nv::max(maxabse, fabsf(e));
mse += e * e;
}
void done()
{
mabse /= samples;
mse /= samples;
rmse = sqrt(mse);
psnr = (rmse == 0) ? 999.0f : 20.0f * log10(255.0f / rmse);
}
void print()
{
printf(" Mean absolute error: %f\n", mabse);
printf(" Max absolute error: %f\n", maxabse);
printf(" Root mean squared error: %f\n", rmse);
printf(" Peak signal to noise ratio in dB: %f\n", psnr);
}
int samples;
float mabse;
float maxabse;
float mse;
float rmse;
float psnr;
};
struct NormalError
{
NormalError()
{
samples = 0;
ade = 0.0f;
mse = 0.0f;
}
void addSample(nv::Color32 o, nv::Color32 c)
{
nv::Vector3 vo = nv::Vector3(o.r, o.g, o.b);
nv::Vector3 vc = nv::Vector3(c.r, c.g, c.b);
// Unpack and normalize.
vo = nv::normalize(2.0f * (vo / 255.0f) - 1.0f);
vc = nv::normalize(2.0f * (vc / 255.0f) - 1.0f);
ade += acosf(nv::clamp(dot(vo, vc), -1.0f, 1.0f));
mse += length_squared((vo - vc) * (255 / 2.0f));
samples++;
}
void done()
{
if (samples)
{
ade /= samples;
mse /= samples * 3;
rmse = sqrt(mse);
psnr = (rmse == 0) ? 999.0f : 20.0f * log10(255.0f / rmse);
}
}
void print()
{
printf(" Angular deviation error: %f\n", ade);
printf(" Root mean squared error: %f\n", rmse);
printf(" Peak signal to noise ratio in dB: %f\n", psnr);
}
int samples;
float ade;
float mse;
float rmse;
float psnr;
};
int main(int argc, char *argv[])
{
MyAssertHandler assertHandler;
MyMessageHandler messageHandler;
bool compareNormal = false;
bool compareAlpha = false;
nv::Path input0;
nv::Path input1;
nv::Path output;
// Parse arguments.
for (int i = 1; i < argc; i++)
{
// Input options.
if (strcmp("-normal", argv[i]) == 0)
{
compareNormal = true;
}
if (strcmp("-alpha", argv[i]) == 0)
{
compareAlpha = true;
}
else if (argv[i][0] != '-')
{
input0 = argv[i];
if (i+1 < argc && argv[i+1][0] != '-') {
input1 = argv[i+1];
}
break;
}
}
if (input0.isNull() || input1.isNull())
{
printf("NVIDIA Texture Tools - Copyright NVIDIA Corporation 2007\n\n");
printf("usage: nvimgdiff [options] original_file updated_file [output]\n\n");
printf("Diff options:\n");
printf(" -normal \tCompare images as if they were normal maps.\n");
printf(" -alpha \tCompare alpha weighted images.\n");
return 1;
}
nv::Image image0, image1;
if (!loadImage(image0, input0)) return 0;
if (!loadImage(image1, input1)) return 0;
const uint w0 = image0.width();
const uint h0 = image0.height();
const uint w1 = image1.width();
const uint h1 = image1.height();
const uint w = nv::min(w0, w1);
const uint h = nv::min(h0, h1);
// Compute errors.
Error error_r;
Error error_g;
Error error_b;
Error error_a;
Error error_total;
NormalError error_normal;
for (uint i = 0; i < h; i++)
{
for (uint e = 0; e < w; e++)
{
const nv::Color32 c0(image0.pixel(e, i));
const nv::Color32 c1(image1.pixel(e, i));
float r = float(c0.r - c1.r);
float g = float(c0.g - c1.g);
float b = float(c0.b - c1.b);
float a = float(c0.a - c1.a);
error_r.addSample(r);
error_g.addSample(g);
error_b.addSample(b);
error_a.addSample(a);
if (compareNormal)
{
error_normal.addSample(c0, c1);
}
if (compareAlpha)
{
error_total.addSample(r * c0.a / 255.0f);
error_total.addSample(g * c0.a / 255.0f);
error_total.addSample(b * c0.a / 255.0f);
}
else
{
error_total.addSample(r);
error_total.addSample(g);
error_total.addSample(b);
}
}
}
error_r.done();
error_g.done();
error_b.done();
error_a.done();
error_total.done();
error_normal.done();
printf("Image size compared: %dx%d\n", w, h);
if (w != w0 || w != w1 || h != h0 || h != h1) {
printf("--- NOTE: only the overlap between the 2 images (%d,%d) and (%d,%d) was compared\n", w0, h0, w1, h1);
}
printf("Total pixels: %d\n", w*h);
printf("Color:\n");
error_total.print();
if (compareNormal)
{
printf("Normal:\n");
error_normal.print();
}
if (compareAlpha)
{
printf("Alpha:\n");
error_a.print();
}
// @@ Write image difference.
return 0;
}
<commit_msg>Fix msvc warnings.<commit_after>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#include <nvcore/StrLib.h>
#include <nvcore/StdStream.h>
#include <nvcore/Containers.h>
#include <nvimage/Image.h>
#include <nvimage/DirectDrawSurface.h>
#include <nvmath/Color.h>
#include <nvmath/Vector.h>
#include <math.h>
#include "cmdline.h"
static bool loadImage(nv::Image & image, const char * fileName)
{
if (nv::strCaseCmp(nv::Path::extension(fileName), ".dds") == 0)
{
nv::DirectDrawSurface dds(fileName);
if (!dds.isValid())
{
printf("The file '%s' is not a valid DDS file.\n", fileName);
return false;
}
dds.mipmap(&image, 0, 0); // get first image
}
else
{
// Regular image.
if (!image.load(fileName))
{
printf("The file '%s' is not a supported image type.\n", fileName);
return false;
}
}
return true;
}
// @@ Compute per-tile errors.
struct Error
{
Error()
{
samples = 0;
mabse = 0.0f;
maxabse = 0.0f;
mse = 0.0f;
}
void addSample(float e)
{
samples++;
mabse += fabsf(e);
maxabse = nv::max(maxabse, fabsf(e));
mse += e * e;
}
void done()
{
mabse /= samples;
mse /= samples;
rmse = sqrtf(mse);
psnr = (rmse == 0) ? 999.0f : 20.0f * log10(255.0f / rmse);
}
void print()
{
printf(" Mean absolute error: %f\n", mabse);
printf(" Max absolute error: %f\n", maxabse);
printf(" Root mean squared error: %f\n", rmse);
printf(" Peak signal to noise ratio in dB: %f\n", psnr);
}
int samples;
float mabse;
float maxabse;
float mse;
float rmse;
float psnr;
};
struct NormalError
{
NormalError()
{
samples = 0;
ade = 0.0f;
mse = 0.0f;
}
void addSample(nv::Color32 o, nv::Color32 c)
{
nv::Vector3 vo = nv::Vector3(o.r, o.g, o.b);
nv::Vector3 vc = nv::Vector3(c.r, c.g, c.b);
// Unpack and normalize.
vo = nv::normalize(2.0f * (vo / 255.0f) - 1.0f);
vc = nv::normalize(2.0f * (vc / 255.0f) - 1.0f);
ade += acosf(nv::clamp(dot(vo, vc), -1.0f, 1.0f));
mse += length_squared((vo - vc) * (255 / 2.0f));
samples++;
}
void done()
{
if (samples)
{
ade /= samples;
mse /= samples * 3;
rmse = sqrtf(mse);
psnr = (rmse == 0) ? 999.0f : 20.0f * log10(255.0f / rmse);
}
}
void print()
{
printf(" Angular deviation error: %f\n", ade);
printf(" Root mean squared error: %f\n", rmse);
printf(" Peak signal to noise ratio in dB: %f\n", psnr);
}
int samples;
float ade;
float mse;
float rmse;
float psnr;
};
int main(int argc, char *argv[])
{
MyAssertHandler assertHandler;
MyMessageHandler messageHandler;
bool compareNormal = false;
bool compareAlpha = false;
nv::Path input0;
nv::Path input1;
nv::Path output;
// Parse arguments.
for (int i = 1; i < argc; i++)
{
// Input options.
if (strcmp("-normal", argv[i]) == 0)
{
compareNormal = true;
}
if (strcmp("-alpha", argv[i]) == 0)
{
compareAlpha = true;
}
else if (argv[i][0] != '-')
{
input0 = argv[i];
if (i+1 < argc && argv[i+1][0] != '-') {
input1 = argv[i+1];
}
break;
}
}
if (input0.isNull() || input1.isNull())
{
printf("NVIDIA Texture Tools - Copyright NVIDIA Corporation 2007\n\n");
printf("usage: nvimgdiff [options] original_file updated_file [output]\n\n");
printf("Diff options:\n");
printf(" -normal \tCompare images as if they were normal maps.\n");
printf(" -alpha \tCompare alpha weighted images.\n");
return 1;
}
nv::Image image0, image1;
if (!loadImage(image0, input0)) return 0;
if (!loadImage(image1, input1)) return 0;
const uint w0 = image0.width();
const uint h0 = image0.height();
const uint w1 = image1.width();
const uint h1 = image1.height();
const uint w = nv::min(w0, w1);
const uint h = nv::min(h0, h1);
// Compute errors.
Error error_r;
Error error_g;
Error error_b;
Error error_a;
Error error_total;
NormalError error_normal;
for (uint i = 0; i < h; i++)
{
for (uint e = 0; e < w; e++)
{
const nv::Color32 c0(image0.pixel(e, i));
const nv::Color32 c1(image1.pixel(e, i));
float r = float(c0.r - c1.r);
float g = float(c0.g - c1.g);
float b = float(c0.b - c1.b);
float a = float(c0.a - c1.a);
error_r.addSample(r);
error_g.addSample(g);
error_b.addSample(b);
error_a.addSample(a);
if (compareNormal)
{
error_normal.addSample(c0, c1);
}
if (compareAlpha)
{
error_total.addSample(r * c0.a / 255.0f);
error_total.addSample(g * c0.a / 255.0f);
error_total.addSample(b * c0.a / 255.0f);
}
else
{
error_total.addSample(r);
error_total.addSample(g);
error_total.addSample(b);
}
}
}
error_r.done();
error_g.done();
error_b.done();
error_a.done();
error_total.done();
error_normal.done();
printf("Image size compared: %dx%d\n", w, h);
if (w != w0 || w != w1 || h != h0 || h != h1) {
printf("--- NOTE: only the overlap between the 2 images (%d,%d) and (%d,%d) was compared\n", w0, h0, w1, h1);
}
printf("Total pixels: %d\n", w*h);
printf("Color:\n");
error_total.print();
if (compareNormal)
{
printf("Normal:\n");
error_normal.print();
}
if (compareAlpha)
{
printf("Alpha:\n");
error_a.print();
}
// @@ Write image difference.
return 0;
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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
* @brief IronBee — CLIPP Parse Modifier Implementation
*
* @author Christopher Alfeld <calfeld@qualys.com>
*/
#include "parse_modifier.hpp"
#include <boost/spirit/include/qi.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/function.hpp>
#include <boost/make_shared.hpp>
#include <boost/fusion/adapted/boost_tuple.hpp>
using namespace std;
namespace IronBee {
namespace CLIPP {
namespace {
typedef boost::iterator_range<const char*> span_t;
typedef boost::tuple<span_t, span_t> two_span_t;
typedef boost::tuple<span_t, span_t, span_t> three_span_t;
Input::Buffer to_buffer(const span_t& span)
{
if (span.empty()) {
return Input::Buffer();
}
return Input::Buffer(span.begin(), span.size());
}
span_t from_buffer(const Input::Buffer& buffer)
{
return span_t(buffer.data, buffer.data + buffer.length);
}
// Read until \r, \n, \r\n, or \n\r.
// Updates @a span to start just after line.
span_t fetch_line(span_t& span)
{
using namespace boost::spirit::qi;
span_t line;
const char* new_begin = span.begin();
parse(
new_begin, span.end(),
raw[*(ascii::char_ - ascii::char_("\n\r"))]
>> omit[lit("\r\n") | "\n\r" | "\n" | "\r"],
line
);
span = span_t(new_begin, span.end());
return line;
}
three_span_t parse_first_line(const span_t& span)
{
using namespace boost::spirit::qi;
three_span_t result;
parse(
span.begin(), span.end(),
raw[+ascii::char_-' '] >> -(omit[+space] >>
raw[+ascii::char_-' '] >> -(omit[+space] >>
raw[+ascii::char_])),
result
);
return result;
}
two_span_t parse_header(const span_t& span)
{
using namespace boost::spirit::qi;
two_span_t result;
parse(
span.begin(), span.end(),
raw[+(ascii::char_ - ':')] >>
-(omit[lit(':') >> *space] >> raw[+ascii::char_]),
result
);
return result;
}
template <typename StartEventType>
void convert_connection_data(
Input::event_list_t& events,
const span_t& data,
Input::event_e start_event,
Input::event_e header_event,
Input::event_e body_event,
Input::event_e finished_event,
double pre_delay,
double post_delay
)
{
span_t input = data;
// Request line
{
span_t current_line = fetch_line(input);
three_span_t info = parse_first_line(current_line);
events.push_back(
boost::make_shared<StartEventType>(
start_event,
to_buffer(current_line),
to_buffer(info.get<0>()),
to_buffer(info.get<1>()),
to_buffer(info.get<2>())
)
);
events.back()->pre_delay = pre_delay;
}
// Headers
Input::header_list_t headers;
while (! input.empty()) {
span_t current_line = fetch_line(input);
if (current_line.empty()) {
// End of headers
break;
}
two_span_t info = parse_header(current_line);
headers.push_back(make_pair(
to_buffer(info.get<0>()),
to_buffer(info.get<1>())
));
}
if (! headers.empty()) {
boost::shared_ptr<Input::HeaderEvent> specific =
boost::make_shared<Input::HeaderEvent>(header_event);
specific->headers.swap(headers);
events.push_back(specific);
}
// Remainder is body.
if (! input.empty()) {
events.push_back(
boost::make_shared<Input::DataEvent>(body_event, to_buffer(input))
);
}
events.push_back(
boost::make_shared<Input::NullEvent>(finished_event)
);
events.back()->post_delay = post_delay;
}
struct data_t
{
boost::any old_source;
Input::transaction_list_t transactions;
};
}
bool ParseModifier::operator()(Input::input_p& input)
{
if (! input) {
return true;
}
boost::shared_ptr<data_t> data = boost::make_shared<data_t>();
data->old_source = input->source;
data->transactions = input->connection.transactions;
input->source = data;
Input::transaction_list_t new_transactions;
enum last_seen_e {
NOTHING,
IN,
OUT
};
last_seen_e last_seen = NOTHING;
BOOST_FOREACH(Input::Transaction& tx, input->connection.transactions) {
new_transactions.push_back(Input::Transaction());
Input::Transaction& new_tx = new_transactions.back();
BOOST_FOREACH(const Input::event_p& event, tx.events) {
switch (event->which) {
case Input::CONNECTION_DATA_IN: {
if (last_seen == IN) {
throw runtime_error(
"@parse does not support repeated connection "
"data in events."
);
}
last_seen = IN;
Input::DataEvent& specific =
dynamic_cast<Input::DataEvent&>(
*event
);
convert_connection_data<Input::RequestEvent>(
new_tx.events,
from_buffer(specific.data),
Input::REQUEST_STARTED,
Input::REQUEST_HEADER,
Input::REQUEST_BODY,
Input::REQUEST_FINISHED,
specific.pre_delay,
specific.post_delay
);
break;
}
case Input::CONNECTION_DATA_OUT: {
if (last_seen == OUT) {
throw runtime_error(
"@parse does not support repeated connection "
"data out events."
);
}
last_seen = OUT;
Input::DataEvent& specific =
dynamic_cast<Input::DataEvent&>(
*event
);
convert_connection_data<Input::ResponseEvent>(
new_tx.events,
from_buffer(specific.data),
Input::RESPONSE_STARTED,
Input::RESPONSE_HEADER,
Input::RESPONSE_BODY,
Input::RESPONSE_FINISHED,
specific.pre_delay,
specific.post_delay
);
break;
}
default:
new_tx.events.push_back(event);
}
}
}
input->connection.transactions.swap(new_transactions);
return true;
}
} // CLIPP
} // IronBee
<commit_msg>clipp: Update @parse to produce *_header_finished events.<commit_after>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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
* @brief IronBee — CLIPP Parse Modifier Implementation
*
* @author Christopher Alfeld <calfeld@qualys.com>
*/
#include "parse_modifier.hpp"
#include <boost/spirit/include/qi.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/function.hpp>
#include <boost/make_shared.hpp>
#include <boost/fusion/adapted/boost_tuple.hpp>
using namespace std;
namespace IronBee {
namespace CLIPP {
namespace {
typedef boost::iterator_range<const char*> span_t;
typedef boost::tuple<span_t, span_t> two_span_t;
typedef boost::tuple<span_t, span_t, span_t> three_span_t;
Input::Buffer to_buffer(const span_t& span)
{
if (span.empty()) {
return Input::Buffer();
}
return Input::Buffer(span.begin(), span.size());
}
span_t from_buffer(const Input::Buffer& buffer)
{
return span_t(buffer.data, buffer.data + buffer.length);
}
// Read until \r, \n, \r\n, or \n\r.
// Updates @a span to start just after line.
span_t fetch_line(span_t& span)
{
using namespace boost::spirit::qi;
span_t line;
const char* new_begin = span.begin();
parse(
new_begin, span.end(),
raw[*(ascii::char_ - ascii::char_("\n\r"))]
>> omit[lit("\r\n") | "\n\r" | "\n" | "\r"],
line
);
span = span_t(new_begin, span.end());
return line;
}
three_span_t parse_first_line(const span_t& span)
{
using namespace boost::spirit::qi;
three_span_t result;
parse(
span.begin(), span.end(),
raw[+ascii::char_-' '] >> -(omit[+space] >>
raw[+ascii::char_-' '] >> -(omit[+space] >>
raw[+ascii::char_])),
result
);
return result;
}
two_span_t parse_header(const span_t& span)
{
using namespace boost::spirit::qi;
two_span_t result;
parse(
span.begin(), span.end(),
raw[+(ascii::char_ - ':')] >>
-(omit[lit(':') >> *space] >> raw[+ascii::char_]),
result
);
return result;
}
template <typename StartEventType>
void convert_connection_data(
Input::event_list_t& events,
const span_t& data,
Input::event_e start_event,
Input::event_e header_event,
Input::event_e header_finished_event,
Input::event_e body_event,
Input::event_e finished_event,
double pre_delay,
double post_delay
)
{
span_t input = data;
// Request line
{
span_t current_line = fetch_line(input);
three_span_t info = parse_first_line(current_line);
events.push_back(
boost::make_shared<StartEventType>(
start_event,
to_buffer(current_line),
to_buffer(info.get<0>()),
to_buffer(info.get<1>()),
to_buffer(info.get<2>())
)
);
events.back()->pre_delay = pre_delay;
}
// Headers
Input::header_list_t headers;
while (! input.empty()) {
span_t current_line = fetch_line(input);
if (current_line.empty()) {
// End of headers
break;
}
two_span_t info = parse_header(current_line);
headers.push_back(make_pair(
to_buffer(info.get<0>()),
to_buffer(info.get<1>())
));
}
if (! headers.empty()) {
boost::shared_ptr<Input::HeaderEvent> specific =
boost::make_shared<Input::HeaderEvent>(header_event);
specific->headers.swap(headers);
events.push_back(specific);
}
events.push_back(
boost::make_shared<Input::NullEvent>(header_finished_event)
);
// Remainder is body.
if (! input.empty()) {
events.push_back(
boost::make_shared<Input::DataEvent>(body_event, to_buffer(input))
);
}
events.push_back(
boost::make_shared<Input::NullEvent>(finished_event)
);
events.back()->post_delay = post_delay;
}
struct data_t
{
boost::any old_source;
Input::transaction_list_t transactions;
};
}
bool ParseModifier::operator()(Input::input_p& input)
{
if (! input) {
return true;
}
boost::shared_ptr<data_t> data = boost::make_shared<data_t>();
data->old_source = input->source;
data->transactions = input->connection.transactions;
input->source = data;
Input::transaction_list_t new_transactions;
enum last_seen_e {
NOTHING,
IN,
OUT
};
last_seen_e last_seen = NOTHING;
BOOST_FOREACH(Input::Transaction& tx, input->connection.transactions) {
new_transactions.push_back(Input::Transaction());
Input::Transaction& new_tx = new_transactions.back();
BOOST_FOREACH(const Input::event_p& event, tx.events) {
switch (event->which) {
case Input::CONNECTION_DATA_IN: {
if (last_seen == IN) {
throw runtime_error(
"@parse does not support repeated connection "
"data in events."
);
}
last_seen = IN;
Input::DataEvent& specific =
dynamic_cast<Input::DataEvent&>(
*event
);
convert_connection_data<Input::RequestEvent>(
new_tx.events,
from_buffer(specific.data),
Input::REQUEST_STARTED,
Input::REQUEST_HEADER,
Input::REQUEST_HEADER_FINISHED,
Input::REQUEST_BODY,
Input::REQUEST_FINISHED,
specific.pre_delay,
specific.post_delay
);
break;
}
case Input::CONNECTION_DATA_OUT: {
if (last_seen == OUT) {
throw runtime_error(
"@parse does not support repeated connection "
"data out events."
);
}
last_seen = OUT;
Input::DataEvent& specific =
dynamic_cast<Input::DataEvent&>(
*event
);
convert_connection_data<Input::ResponseEvent>(
new_tx.events,
from_buffer(specific.data),
Input::RESPONSE_STARTED,
Input::RESPONSE_HEADER,
Input::RESPONSE_HEADER_FINISHED,
Input::RESPONSE_BODY,
Input::RESPONSE_FINISHED,
specific.pre_delay,
specific.post_delay
);
break;
}
default:
new_tx.events.push_back(event);
}
}
}
input->connection.transactions.swap(new_transactions);
return true;
}
} // CLIPP
} // IronBee
<|endoftext|>
|
<commit_before>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/PointCloud.h>
#include <math.h>
static const float tol = 0.000000000000001f;
double magnitude(double vec[3]){
return sqrt(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]);
}
void normalize(double vec[3]){
float m = magnitude(vec);
if(tol <= m) m = 1;
vec[0] /= m;
vec[1] /= m;
vec[2] /= m;
if(fabs(vec[0]) < tol) vec[0] = 0.0f;
if(fabs(vec[1]) < tol) vec[1] = 0.0f;
if(fabs(vec[2]) < tol) vec[2] = 0.0f;
}
class ArtificialPotentialField{
public:
ArtificialPotentialField(ros::NodeHandle &node) :
cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)),
obs_sub_(node.subscribe("slam_cloud", 10, &ArtificialPotentialField::obstacleCallback, this))
{
for(int i=0; i < 3; i++) obs_[i] = 0;
}
void spin(){
ros::Rate r(10);
ros::Duration(1).sleep();
geometry_msgs::Twist cmd;
cmd.linear.z = 0.15;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
cmd.linear.z = 0;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
const double A = 0;
const double B = 3;
const double n = 1;
const double m = 1.5;
const double force = 0.025;
while(ros::ok()){
double Fs[3];
Fs[0] = Fs[1] = Fs[2] = 0;
double u[3];
u[0] = obs_[0];
u[1] = obs_[1];
u[2] = obs_[2];
normalize(u);
const double d = magnitude(obs_);
double U = -A/pow(d, n) + B/pow(d, m);
Fs[0] += U * u[0];
Fs[1] += U * u[1];
Fs[2] += U * u[2];
cmd.linear.x = Fs[0] * force;
cmd.linear.y = Fs[1] * force;
//ROS_INFO_STREAM("cmd = " << cmd);
cmd_pub_.publish(cmd);
r.sleep();
ros::spinOnce();
}
}
private:
void obstacleCallback(const sensor_msgs::PointCloudPtr &obs_msg){
ROS_INFO_STREAM("size = " << obs_msg->points.size());
if(obs_msg->points.size() == 0){
return;
}
double min_obs[3];
min_obs[0] = obs_msg->points[0].x;
min_obs[1] = obs_msg->points[0].y;
min_obs[2] = obs_msg->points[0].z;
float min_dist = magnitude(min_obs);
for(int i=1; i < obs_msg->points.size(); i++){
double obs[3];
obs[0] = obs_msg->points[i].x;
obs[1] = obs_msg->points[i].y;
obs[2] = obs_msg->points[i].z;
ROS_INFO("(%f, %f)", obs[0], obs[1]);
double dist = magnitude(obs);
if(dist < min_dist){
min_obs[0] = obs[0];
min_obs[1] = obs[1];
min_obs[2] = obs[2];
min_dist = dist;
}
}
obs_[0] = min_obs[0];
obs_[1] = min_obs[1];
obs_[2] = min_obs[2];
}
double obs_[3];
ros::Publisher cmd_pub_;
ros::Subscriber obs_sub_;
};
int main(int argc, char *argv[]){
ros::init(argc, argv, "obstacle_avoidance");
ros::NodeHandle node;
ArtificialPotentialField apf = ArtificialPotentialField(node);
apf.spin();
return 0;
}
<commit_msg>change output log<commit_after>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/PointCloud.h>
#include <math.h>
static const float tol = 0.000000000000001f;
double magnitude(double vec[3]){
return sqrt(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]);
}
void normalize(double vec[3]){
float m = magnitude(vec);
if(tol <= m) m = 1;
vec[0] /= m;
vec[1] /= m;
vec[2] /= m;
if(fabs(vec[0]) < tol) vec[0] = 0.0f;
if(fabs(vec[1]) < tol) vec[1] = 0.0f;
if(fabs(vec[2]) < tol) vec[2] = 0.0f;
}
class ArtificialPotentialField{
public:
ArtificialPotentialField(ros::NodeHandle &node) :
cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)),
obs_sub_(node.subscribe("slam_cloud", 10, &ArtificialPotentialField::obstacleCallback, this))
{
for(int i=0; i < 3; i++) obs_[i] = 0;
}
void spin(){
ros::Rate r(10);
ros::Duration(1).sleep();
geometry_msgs::Twist cmd;
cmd.linear.z = 0.15;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
cmd.linear.z = 0;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
const double A = 0;
const double B = 3;
const double n = 1;
const double m = 1.5;
const double force = 0.025;
while(ros::ok()){
double Fs[3];
Fs[0] = Fs[1] = Fs[2] = 0;
double u[3];
u[0] = obs_[0];
u[1] = obs_[1];
u[2] = obs_[2];
normalize(u);
const double d = magnitude(obs_);
double U = -A/pow(d, n) + B/pow(d, m);
Fs[0] += U * u[0];
Fs[1] += U * u[1];
Fs[2] += U * u[2];
cmd.linear.x = Fs[0] * force;
cmd.linear.y = Fs[1] * force;
ROS_INFO_STREAM("cmd = " << cmd);
cmd_pub_.publish(cmd);
r.sleep();
ros::spinOnce();
}
}
private:
void obstacleCallback(const sensor_msgs::PointCloudPtr &obs_msg){
if(obs_msg->points.size() == 0){
return;
}
double min_obs[3];
min_obs[0] = obs_msg->points[0].x;
min_obs[1] = obs_msg->points[0].y;
min_obs[2] = obs_msg->points[0].z;
float min_dist = magnitude(min_obs);
for(int i=1; i < obs_msg->points.size(); i++){
double obs[3];
obs[0] = obs_msg->points[i].x;
obs[1] = obs_msg->points[i].y;
obs[2] = obs_msg->points[i].z;
//ROS_INFO("(%f, %f)", obs[0], obs[1]);
double dist = magnitude(obs);
if(dist < min_dist){
min_obs[0] = obs[0];
min_obs[1] = obs[1];
min_obs[2] = obs[2];
min_dist = dist;
}
}
obs_[0] = min_obs[0];
obs_[1] = min_obs[1];
obs_[2] = min_obs[2];
}
double obs_[3];
ros::Publisher cmd_pub_;
ros::Subscriber obs_sub_;
};
int main(int argc, char *argv[]){
ros::init(argc, argv, "obstacle_avoidance");
ros::NodeHandle node;
ArtificialPotentialField apf = ArtificialPotentialField(node);
apf.spin();
return 0;
}
<|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 "views/controls/menu/simple_menu_model.h"
#include "app/l10n_util.h"
namespace views {
////////////////////////////////////////////////////////////////////////////////
// SimpleMenuModel, public:
SimpleMenuModel::SimpleMenuModel(Delegate* delegate) : delegate_(delegate) {
}
SimpleMenuModel::~SimpleMenuModel() {
}
void SimpleMenuModel::AddItem(int command_id, const string16& label) {
Item item = { command_id, label, TYPE_COMMAND, -1, NULL };
items_.push_back(item);
}
void SimpleMenuModel::AddItemWithStringId(int command_id, int string_id) {
AddItem(command_id, l10n_util::GetStringUTF16(string_id));
}
void SimpleMenuModel::AddSeparator() {
Item item = { -1, string16(), TYPE_SEPARATOR, -1, NULL };
items_.push_back(item);
}
void SimpleMenuModel::AddCheckItem(int command_id, const string16& label) {
Item item = { command_id, label, TYPE_CHECK, -1, NULL };
items_.push_back(item);
}
void SimpleMenuModel::AddCheckItemWithStringId(int command_id, int string_id) {
AddCheckItem(command_id, l10n_util::GetStringUTF16(string_id));
}
void SimpleMenuModel::AddRadioItem(int command_id, const string16& label,
int group_id) {
Item item = { command_id, label, TYPE_RADIO, group_id, NULL };
items_.push_back(item);
}
void SimpleMenuModel::AddRadioItemWithStringId(int command_id, int string_id,
int group_id) {
AddRadioItem(command_id, l10n_util::GetStringUTF16(string_id), group_id);
}
void SimpleMenuModel::AddSubMenu(const string16& label, Menu2Model* model) {
Item item = { -1, label, TYPE_SUBMENU, -1, model };
items_.push_back(item);
}
void SimpleMenuModel::AddSubMenuWithStringId(int string_id, Menu2Model* model) {
AddSubMenu(l10n_util::GetStringUTF16(string_id), model);
}
////////////////////////////////////////////////////////////////////////////////
// SimpleMenuModel, Menu2Model implementation:
bool SimpleMenuModel::HasIcons() const {
return false;
}
int SimpleMenuModel::GetItemCount() const {
return static_cast<int>(items_.size());
}
Menu2Model::ItemType SimpleMenuModel::GetTypeAt(int index) const {
return items_.at(FlipIndex(index)).type;
}
int SimpleMenuModel::GetCommandIdAt(int index) const {
return items_.at(FlipIndex(index)).command_id;
}
string16 SimpleMenuModel::GetLabelAt(int index) const {
if (IsLabelDynamicAt(index))
return delegate_->GetLabelForCommandId(GetCommandIdAt(index));
return items_.at(FlipIndex(index)).label;
}
bool SimpleMenuModel::IsLabelDynamicAt(int index) const {
if (delegate_)
return delegate_->IsLabelForCommandIdDynamic(GetCommandIdAt(index));
return false;
}
bool SimpleMenuModel::GetAcceleratorAt(int index,
views::Accelerator* accelerator) const {
if (delegate_) {
return delegate_->GetAcceleratorForCommandId(GetCommandIdAt(index),
accelerator);
}
return false;
}
bool SimpleMenuModel::IsItemCheckedAt(int index) const {
if (!delegate_)
return false;
int item_index = FlipIndex(index);
return (items_[item_index].type == TYPE_CHECK) ?
delegate_->IsCommandIdChecked(GetCommandIdAt(index)) : false;
}
int SimpleMenuModel::GetGroupIdAt(int index) const {
return items_.at(FlipIndex(index)).group_id;
}
bool SimpleMenuModel::GetIconAt(int index, SkBitmap* icon) const {
return false;
}
bool SimpleMenuModel::IsEnabledAt(int index) const {
int command_id = GetCommandIdAt(index);
// Submenus have a command id of -1, they should always be enabled.
if (!delegate_ || command_id == -1)
return true;
return delegate_->IsCommandIdEnabled(command_id);
}
void SimpleMenuModel::HighlightChangedTo(int index) {
if (delegate_)
delegate_->CommandIdHighlighted(GetCommandIdAt(index));
}
void SimpleMenuModel::ActivatedAt(int index) {
if (delegate_)
delegate_->ExecuteCommand(GetCommandIdAt(index));
}
Menu2Model* SimpleMenuModel::GetSubmenuModelAt(int index) const {
return items_.at(FlipIndex(index)).submenu;
}
} // namespace views
<commit_msg>Make the char encoding indicator visible again on Windows<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 "views/controls/menu/simple_menu_model.h"
#include "app/l10n_util.h"
namespace views {
////////////////////////////////////////////////////////////////////////////////
// SimpleMenuModel, public:
SimpleMenuModel::SimpleMenuModel(Delegate* delegate) : delegate_(delegate) {
}
SimpleMenuModel::~SimpleMenuModel() {
}
void SimpleMenuModel::AddItem(int command_id, const string16& label) {
Item item = { command_id, label, TYPE_COMMAND, -1, NULL };
items_.push_back(item);
}
void SimpleMenuModel::AddItemWithStringId(int command_id, int string_id) {
AddItem(command_id, l10n_util::GetStringUTF16(string_id));
}
void SimpleMenuModel::AddSeparator() {
Item item = { -1, string16(), TYPE_SEPARATOR, -1, NULL };
items_.push_back(item);
}
void SimpleMenuModel::AddCheckItem(int command_id, const string16& label) {
Item item = { command_id, label, TYPE_CHECK, -1, NULL };
items_.push_back(item);
}
void SimpleMenuModel::AddCheckItemWithStringId(int command_id, int string_id) {
AddCheckItem(command_id, l10n_util::GetStringUTF16(string_id));
}
void SimpleMenuModel::AddRadioItem(int command_id, const string16& label,
int group_id) {
Item item = { command_id, label, TYPE_RADIO, group_id, NULL };
items_.push_back(item);
}
void SimpleMenuModel::AddRadioItemWithStringId(int command_id, int string_id,
int group_id) {
AddRadioItem(command_id, l10n_util::GetStringUTF16(string_id), group_id);
}
void SimpleMenuModel::AddSubMenu(const string16& label, Menu2Model* model) {
Item item = { -1, label, TYPE_SUBMENU, -1, model };
items_.push_back(item);
}
void SimpleMenuModel::AddSubMenuWithStringId(int string_id, Menu2Model* model) {
AddSubMenu(l10n_util::GetStringUTF16(string_id), model);
}
////////////////////////////////////////////////////////////////////////////////
// SimpleMenuModel, Menu2Model implementation:
bool SimpleMenuModel::HasIcons() const {
return false;
}
int SimpleMenuModel::GetItemCount() const {
return static_cast<int>(items_.size());
}
Menu2Model::ItemType SimpleMenuModel::GetTypeAt(int index) const {
return items_.at(FlipIndex(index)).type;
}
int SimpleMenuModel::GetCommandIdAt(int index) const {
return items_.at(FlipIndex(index)).command_id;
}
string16 SimpleMenuModel::GetLabelAt(int index) const {
if (IsLabelDynamicAt(index))
return delegate_->GetLabelForCommandId(GetCommandIdAt(index));
return items_.at(FlipIndex(index)).label;
}
bool SimpleMenuModel::IsLabelDynamicAt(int index) const {
if (delegate_)
return delegate_->IsLabelForCommandIdDynamic(GetCommandIdAt(index));
return false;
}
bool SimpleMenuModel::GetAcceleratorAt(int index,
views::Accelerator* accelerator) const {
if (delegate_) {
return delegate_->GetAcceleratorForCommandId(GetCommandIdAt(index),
accelerator);
}
return false;
}
bool SimpleMenuModel::IsItemCheckedAt(int index) const {
if (!delegate_)
return false;
int item_index = FlipIndex(index);
Menu2Model::ItemType item_type = items_[item_index].type;
return (item_type == TYPE_CHECK || item_type == TYPE_RADIO) ?
delegate_->IsCommandIdChecked(GetCommandIdAt(index)) : false;
}
int SimpleMenuModel::GetGroupIdAt(int index) const {
return items_.at(FlipIndex(index)).group_id;
}
bool SimpleMenuModel::GetIconAt(int index, SkBitmap* icon) const {
return false;
}
bool SimpleMenuModel::IsEnabledAt(int index) const {
int command_id = GetCommandIdAt(index);
// Submenus have a command id of -1, they should always be enabled.
if (!delegate_ || command_id == -1)
return true;
return delegate_->IsCommandIdEnabled(command_id);
}
void SimpleMenuModel::HighlightChangedTo(int index) {
if (delegate_)
delegate_->CommandIdHighlighted(GetCommandIdAt(index));
}
void SimpleMenuModel::ActivatedAt(int index) {
if (delegate_)
delegate_->ExecuteCommand(GetCommandIdAt(index));
}
Menu2Model* SimpleMenuModel::GetSubmenuModelAt(int index) const {
return items_.at(FlipIndex(index)).submenu;
}
} // namespace views
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "views/focus/accelerator_handler.h"
#include <bitset>
#include <gtk/gtk.h>
#if defined(HAVE_XINPUT2)
#include <X11/extensions/XInput2.h>
#else
#include <X11/Xlib.h>
#endif
#include "views/accelerator.h"
#include "views/event.h"
#include "views/focus/focus_manager.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_gtk.h"
namespace views {
#if defined(HAVE_XINPUT2)
// Functions related to determining touch devices.
class TouchFactory {
public:
// Keep a list of touch devices so that it is possible to determine if a
// pointer event is a touch-event or a mouse-event.
static void SetTouchDeviceListInternal(
const std::vector<unsigned int>& devices) {
for (std::vector<unsigned int>::const_iterator iter = devices.begin();
iter != devices.end(); ++iter) {
DCHECK(*iter < touch_devices.size());
touch_devices[*iter] = true;
}
}
// Is the device a touch-device?
static bool IsTouchDevice(unsigned int deviceid) {
return deviceid < touch_devices.size() ? touch_devices[deviceid] : false;
}
private:
// A quick lookup table for determining if a device is a touch device.
static std::bitset<128> touch_devices;
DISALLOW_COPY_AND_ASSIGN(TouchFactory);
};
std::bitset<128> TouchFactory::touch_devices;
#endif
namespace {
RootView* FindRootViewForGdkWindow(GdkWindow* gdk_window) {
gpointer data = NULL;
gdk_window_get_user_data(gdk_window, &data);
GtkWidget* gtk_widget = reinterpret_cast<GtkWidget*>(data);
if (!gtk_widget || !GTK_IS_WIDGET(gtk_widget)) {
DLOG(WARNING) << "no GtkWidget found for that GdkWindow";
return NULL;
}
WidgetGtk* widget_gtk = WidgetGtk::GetViewForNative(gtk_widget);
if (!widget_gtk) {
DLOG(WARNING) << "no WidgetGtk found for that GtkWidget";
return NULL;
}
return widget_gtk->GetRootView();
}
#if defined(HAVE_XINPUT2)
bool X2EventIsTouchEvent(XEvent* xev) {
// TODO(sad): Determine if the captured event is a touch-event.
XGenericEventCookie* cookie = &xev->xcookie;
switch (cookie->evtype) {
case XI_ButtonPress:
case XI_ButtonRelease:
case XI_Motion: {
// Is the event coming from a touch device?
return TouchFactory::IsTouchDevice(
static_cast<XIDeviceEvent*>(cookie->data)->sourceid);
}
default:
return false;
}
}
#endif // HAVE_XINPUT2
} // namespace
#if defined(HAVE_XINPUT2)
bool DispatchX2Event(RootView* root, XEvent* xev) {
if (X2EventIsTouchEvent(xev)) {
// Create a TouchEvent, and send it off to |root|. If the event
// is processed by |root|, then return. Otherwise let it fall through so it
// can be used (if desired) as a mouse event.
TouchEvent touch(xev);
if (root->OnTouchEvent(touch))
return true;
}
XGenericEventCookie* cookie = &xev->xcookie;
switch (cookie->evtype) {
case XI_KeyPress:
case XI_KeyRelease: {
// TODO(sad): We don't capture XInput2 events from keyboard yet.
break;
}
case XI_ButtonPress:
case XI_ButtonRelease: {
MouseEvent mouseev(xev);
if (cookie->evtype == XI_ButtonPress) {
return root->OnMousePressed(mouseev);
} else {
root->OnMouseReleased(mouseev, false);
return true;
}
}
case XI_Motion: {
MouseEvent mouseev(xev);
if (mouseev.GetType() == Event::ET_MOUSE_DRAGGED) {
return root->OnMouseDragged(mouseev);
} else {
root->OnMouseMoved(mouseev);
return true;
}
break;
}
}
return false;
}
#endif // HAVE_XINPUT2
bool DispatchXEvent(XEvent* xev) {
GdkDisplay* gdisp = gdk_display_get_default();
XID xwindow = xev->xany.window;
#if defined(HAVE_XINPUT2)
if (xev->type == GenericEvent) {
XGenericEventCookie* cookie = &xev->xcookie;
XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(cookie->data);
xwindow = xiev->event;
}
#endif
GdkWindow* gwind = gdk_window_lookup_for_display(gdisp, xwindow);
if (RootView* root = FindRootViewForGdkWindow(gwind)) {
switch (xev->type) {
case KeyPress:
case KeyRelease: {
KeyEvent keyev(xev);
// If it's a keypress, check to see if it triggers an accelerator.
if (xev->type == KeyPress) {
FocusManager* focus_manager = root->GetFocusManager();
if (focus_manager && !focus_manager->OnKeyEvent(keyev))
return true;
}
return root->ProcessKeyEvent(keyev);
}
case ButtonPress:
case ButtonRelease: {
if (xev->xbutton.button == 4 || xev->xbutton.button == 5) {
// Scrolling the wheel triggers button press/release events.
MouseWheelEvent wheelev(xev);
return root->ProcessMouseWheelEvent(wheelev);
} else {
MouseEvent mouseev(xev);
if (xev->type == ButtonPress) {
return root->OnMousePressed(mouseev);
} else {
root->OnMouseReleased(mouseev, false);
return true; // Assume the event has been processed to make sure we
// don't process it twice.
}
}
}
case MotionNotify: {
MouseEvent mouseev(xev);
if (mouseev.GetType() == Event::ET_MOUSE_DRAGGED) {
return root->OnMouseDragged(mouseev);
} else {
root->OnMouseMoved(mouseev);
return true;
}
}
#if defined(HAVE_XINPUT2)
case GenericEvent: {
return DispatchX2Event(root, xev);
}
#endif
}
}
return false;
}
#if defined(HAVE_XINPUT2)
void SetTouchDeviceList(std::vector<unsigned int>& devices) {
TouchFactory::SetTouchDeviceListInternal(devices);
}
#endif
AcceleratorHandler::AcceleratorHandler() {}
bool AcceleratorHandler::Dispatch(GdkEvent* event) {
gtk_main_do_event(event);
return true;
}
base::MessagePumpGlibXDispatcher::DispatchStatus AcceleratorHandler::Dispatch(
XEvent* xev) {
return DispatchXEvent(xev) ?
base::MessagePumpGlibXDispatcher::EVENT_PROCESSED :
base::MessagePumpGlibXDispatcher::EVENT_IGNORED;
}
} // namespace views
<commit_msg>touch: Fix switching focus among fields in webpages.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "views/focus/accelerator_handler.h"
#include <bitset>
#include <gtk/gtk.h>
#if defined(HAVE_XINPUT2)
#include <X11/extensions/XInput2.h>
#else
#include <X11/Xlib.h>
#endif
#include "views/accelerator.h"
#include "views/event.h"
#include "views/focus/focus_manager.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_gtk.h"
namespace views {
#if defined(HAVE_XINPUT2)
// Functions related to determining touch devices.
class TouchFactory {
public:
// Keep a list of touch devices so that it is possible to determine if a
// pointer event is a touch-event or a mouse-event.
static void SetTouchDeviceListInternal(
const std::vector<unsigned int>& devices) {
for (std::vector<unsigned int>::const_iterator iter = devices.begin();
iter != devices.end(); ++iter) {
DCHECK(*iter < touch_devices.size());
touch_devices[*iter] = true;
}
}
// Is the device a touch-device?
static bool IsTouchDevice(unsigned int deviceid) {
return deviceid < touch_devices.size() ? touch_devices[deviceid] : false;
}
private:
// A quick lookup table for determining if a device is a touch device.
static std::bitset<128> touch_devices;
DISALLOW_COPY_AND_ASSIGN(TouchFactory);
};
std::bitset<128> TouchFactory::touch_devices;
#endif
namespace {
RootView* FindRootViewForGdkWindow(GdkWindow* gdk_window) {
gpointer data = NULL;
gdk_window_get_user_data(gdk_window, &data);
GtkWidget* gtk_widget = reinterpret_cast<GtkWidget*>(data);
if (!gtk_widget || !GTK_IS_WIDGET(gtk_widget)) {
DLOG(WARNING) << "no GtkWidget found for that GdkWindow";
return NULL;
}
WidgetGtk* widget_gtk = WidgetGtk::GetViewForNative(gtk_widget);
if (!widget_gtk) {
DLOG(WARNING) << "no WidgetGtk found for that GtkWidget";
return NULL;
}
return widget_gtk->GetRootView();
}
#if defined(HAVE_XINPUT2)
bool X2EventIsTouchEvent(XEvent* xev) {
// TODO(sad): Determine if the captured event is a touch-event.
XGenericEventCookie* cookie = &xev->xcookie;
switch (cookie->evtype) {
case XI_ButtonPress:
case XI_ButtonRelease:
case XI_Motion: {
// Is the event coming from a touch device?
return TouchFactory::IsTouchDevice(
static_cast<XIDeviceEvent*>(cookie->data)->sourceid);
}
default:
return false;
}
}
#endif // HAVE_XINPUT2
} // namespace
#if defined(HAVE_XINPUT2)
bool DispatchX2Event(RootView* root, XEvent* xev) {
if (X2EventIsTouchEvent(xev)) {
// Create a TouchEvent, and send it off to |root|. If the event
// is processed by |root|, then return. Otherwise let it fall through so it
// can be used (if desired) as a mouse event.
TouchEvent touch(xev);
if (root->OnTouchEvent(touch))
return true;
}
XGenericEventCookie* cookie = &xev->xcookie;
switch (cookie->evtype) {
case XI_KeyPress:
case XI_KeyRelease: {
// TODO(sad): We don't capture XInput2 events from keyboard yet.
break;
}
case XI_ButtonPress:
case XI_ButtonRelease: {
MouseEvent mouseev(xev);
if (cookie->evtype == XI_ButtonPress) {
return root->OnMousePressed(mouseev);
} else {
root->OnMouseReleased(mouseev, false);
return true;
}
}
case XI_Motion: {
MouseEvent mouseev(xev);
if (mouseev.GetType() == Event::ET_MOUSE_DRAGGED) {
return root->OnMouseDragged(mouseev);
} else {
root->OnMouseMoved(mouseev);
return true;
}
break;
}
}
return false;
}
#endif // HAVE_XINPUT2
bool DispatchXEvent(XEvent* xev) {
GdkDisplay* gdisp = gdk_display_get_default();
XID xwindow = xev->xany.window;
#if defined(HAVE_XINPUT2)
if (xev->type == GenericEvent) {
XGenericEventCookie* cookie = &xev->xcookie;
XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(cookie->data);
xwindow = xiev->event;
}
#endif
GdkWindow* gwind = gdk_window_lookup_for_display(gdisp, xwindow);
if (RootView* root = FindRootViewForGdkWindow(gwind)) {
switch (xev->type) {
case KeyPress: {
// If Tab is pressed, then the RootView needs to process it first,
// because the focus-manager will move the focus to the next focusable
// view, without letting the currently focused view process it (which
// means, for example, tab-ing to move focus between fields/links in a
// RenderWidgetHostViewViews won't work). For all other keys, let the
// focus manager process it first so that the keyboard accelerators can
// be triggered.
KeyEvent keyev(xev);
FocusManager* focus_manager = root->GetFocusManager();
if (FocusManager::IsTabTraversalKeyEvent(keyev)) {
return root->ProcessKeyEvent(keyev) ||
(focus_manager && !focus_manager->OnKeyEvent(keyev));
} else {
return (focus_manager && !focus_manager->OnKeyEvent(keyev)) ||
root->ProcessKeyEvent(keyev);
}
}
case KeyRelease:
return root->ProcessKeyEvent(KeyEvent(xev));
case ButtonPress:
case ButtonRelease: {
if (xev->xbutton.button == 4 || xev->xbutton.button == 5) {
// Scrolling the wheel triggers button press/release events.
MouseWheelEvent wheelev(xev);
return root->ProcessMouseWheelEvent(wheelev);
} else {
MouseEvent mouseev(xev);
if (xev->type == ButtonPress) {
return root->OnMousePressed(mouseev);
} else {
root->OnMouseReleased(mouseev, false);
return true; // Assume the event has been processed to make sure we
// don't process it twice.
}
}
}
case MotionNotify: {
MouseEvent mouseev(xev);
if (mouseev.GetType() == Event::ET_MOUSE_DRAGGED) {
return root->OnMouseDragged(mouseev);
} else {
root->OnMouseMoved(mouseev);
return true;
}
}
#if defined(HAVE_XINPUT2)
case GenericEvent: {
return DispatchX2Event(root, xev);
}
#endif
}
}
return false;
}
#if defined(HAVE_XINPUT2)
void SetTouchDeviceList(std::vector<unsigned int>& devices) {
TouchFactory::SetTouchDeviceListInternal(devices);
}
#endif
AcceleratorHandler::AcceleratorHandler() {}
bool AcceleratorHandler::Dispatch(GdkEvent* event) {
gtk_main_do_event(event);
return true;
}
base::MessagePumpGlibXDispatcher::DispatchStatus AcceleratorHandler::Dispatch(
XEvent* xev) {
return DispatchXEvent(xev) ?
base::MessagePumpGlibXDispatcher::EVENT_PROCESSED :
base::MessagePumpGlibXDispatcher::EVENT_IGNORED;
}
} // namespace views
<|endoftext|>
|
<commit_before>// ===== ---- ofp/sys/tcp_server.cpp ----------------------*- C++ -*- ===== //
//
// Copyright (c) 2013 William W. Fisher
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ===== ------------------------------------------------------------ ===== //
/// \file
/// \brief Implements TCP_Server class.
// ===== ------------------------------------------------------------ ===== //
#include "ofp/sys/tcp_server.h"
#include "ofp/sys/engine.h"
#include "ofp/log.h"
namespace ofp { // <namespace ofp>
namespace sys { // <namespace sys>
TCP_Server::TCP_Server(Engine *engine, Driver::Role role,
const Features *features, const tcp::endpoint &endpt,
ProtocolVersions versions,
ChannelListener::Factory listenerFactory)
: engine_{engine}, acceptor_{engine->io()}, socket_{engine->io()},
role_{role}, versions_{versions}, factory_{listenerFactory}
{
listen(endpt);
if (features) {
features_ = *features;
}
asyncAccept();
engine_->registerServer(this);
log::info("Start TCP listening on", endpt);
}
TCP_Server::~TCP_Server()
{
error_code err;
tcp::endpoint endpt = acceptor_.local_endpoint(err);
log::info("Stop TCP listening on", endpt);
engine_->releaseServer(this);
}
void TCP_Server::listen(const tcp::endpoint &endpt)
{
acceptor_.open(endpt.protocol());
acceptor_.set_option(boost::asio::socket_base::reuse_address(true));
// Handle case where IPv6 is not supported on this system.
try {
acceptor_.bind(endpt);
} catch (boost::system::system_error &ex) {
if (ex.code() == boost::asio::error::address_family_not_supported && endpt.address().is_v6() && endpt.address().is_unspecified()) {
acceptor_.bind(tcp::endpoint{tcp::v4(), endpt.port()});
} else {
throw;
}
}
acceptor_.listen(boost::asio::socket_base::max_connections);
}
void TCP_Server::asyncAccept()
{
acceptor_.async_accept(socket_, [this](error_code err) {
// N.B. ASIO still sends a cancellation error even after
// async_accept() throws an exception. Check for cancelled operation
// first; our TCP_Server instance will have been destroyed.
if (isAsioCanceled(err))
return;
log::Lifetime lifetime("async_accept callback");
if (!err) {
auto conn = std::make_shared<TCP_Connection>(
engine_, std::move(socket_), role_, versions_, factory_);
conn->setFeatures(features_);
conn->asyncAccept();
} else {
Exception exc = makeException(err);
log::error("Error in TCP_Server.asyncAcept:", exc.toString());
}
asyncAccept();
});
}
} // </namespace sys>
} // </namespace ofp>
<commit_msg>Fix bug in listen() - doesn't properly handle case where system doesn't support IPv6.<commit_after>// ===== ---- ofp/sys/tcp_server.cpp ----------------------*- C++ -*- ===== //
//
// Copyright (c) 2013 William W. Fisher
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ===== ------------------------------------------------------------ ===== //
/// \file
/// \brief Implements TCP_Server class.
// ===== ------------------------------------------------------------ ===== //
#include "ofp/sys/tcp_server.h"
#include "ofp/sys/engine.h"
#include "ofp/log.h"
namespace ofp { // <namespace ofp>
namespace sys { // <namespace sys>
TCP_Server::TCP_Server(Engine *engine, Driver::Role role,
const Features *features, const tcp::endpoint &endpt,
ProtocolVersions versions,
ChannelListener::Factory listenerFactory)
: engine_{engine}, acceptor_{engine->io()}, socket_{engine->io()},
role_{role}, versions_{versions}, factory_{listenerFactory}
{
listen(endpt);
if (features) {
features_ = *features;
}
asyncAccept();
engine_->registerServer(this);
log::info("Start TCP listening on", endpt);
}
TCP_Server::~TCP_Server()
{
error_code err;
tcp::endpoint endpt = acceptor_.local_endpoint(err);
log::info("Stop TCP listening on", endpt);
engine_->releaseServer(this);
}
void TCP_Server::listen(const tcp::endpoint &endpt)
{
// Handle case where IPv6 is not supported on this system.
tcp::endpoint ep = endpt;
try {
acceptor_.open(ep.protocol());
}
catch (boost::system::system_error &ex)
{
auto addr = ep.address();
if (ex.code() == boost::asio::error::address_family_not_supported &&
addr.is_v6() && addr.is_unspecified()) {
ep = tcp::endpoint{tcp::v4(), ep.port()};
acceptor_.open(ep.protocol());
} else {
throw;
}
}
acceptor_.set_option(boost::asio::socket_base::reuse_address(true));
acceptor_.bind(ep);
acceptor_.listen(boost::asio::socket_base::max_connections);
}
void TCP_Server::asyncAccept()
{
acceptor_.async_accept(socket_, [this](error_code err) {
// N.B. ASIO still sends a cancellation error even after
// async_accept() throws an exception. Check for cancelled operation
// first; our TCP_Server instance will have been destroyed.
if (isAsioCanceled(err))
return;
log::Lifetime lifetime("async_accept callback");
if (!err) {
auto conn = std::make_shared<TCP_Connection>(
engine_, std::move(socket_), role_, versions_, factory_);
conn->setFeatures(features_);
conn->asyncAccept();
} else {
Exception exc = makeException(err);
log::error("Error in TCP_Server.asyncAcept:", exc.toString());
}
asyncAccept();
});
}
} // </namespace sys>
} // </namespace ofp>
<|endoftext|>
|
<commit_before>/***************************************************************************
*
* Project: libLAS -- C/C++ read/write library for LAS LIDAR data
* Purpose: LAS translation with optional configuration
* Author: Howard Butler, hobu.inc at gmail.com
***************************************************************************
* Copyright (c) 2010, Howard Butler, hobu.inc at gmail.com
*
* See LICENSE.txt in this source distribution for more information.
**************************************************************************/
#include <iostream>
#include <libpc/exceptions.hpp>
//#include <libpc/libpc_config.hpp>
//#include <libpc/Bounds.hpp>
//#include <libpc/Color.hpp>
//#include <libpc/Dimension.hpp>
//#include <libpc/Schema.hpp>
#include <libpc/filters/Chipper.hpp>
//#include <libpc/ColorFilter.hpp>
//#include <libpc/MosaicFilter.hpp>
//#include <libpc/FauxReader.hpp>
//#include <libpc/FauxWriter.hpp>
#include <libpc/drivers/las/Reader.hpp>
//#include <libpc/LasHeader.hpp>
#include <libpc/drivers/las/Writer.hpp>
#include <libpc/filters/CacheFilter.hpp>
#include <libpc/drivers/liblas/Writer.hpp>
#include <libpc/drivers/liblas/Reader.hpp>
#ifdef LIBPC_HAVE_ORACLE
#include <libpc/drivers/oci/Writer.hpp>
#include <libpc/drivers/oci/Reader.hpp>
#endif
#include "Application.hpp"
using namespace libpc;
namespace po = boost::program_options;
class Application_pc2pc : public Application
{
public:
Application_pc2pc(int argc, char* argv[]);
int execute();
private:
void addOptions();
bool validateOptions();
std::string m_inputFile;
std::string m_outputFile;
std::string m_OracleReadSQL;
std::string m_OracleWriteSQL;
};
Application_pc2pc::Application_pc2pc(int argc, char* argv[])
: Application(argc, argv, "pc2pc")
{
}
bool Application_pc2pc::validateOptions()
{
if (!hasOption("input"))
{
usageError("--input/-i required");
return false;
}
if (!hasOption("output"))
{
usageError("--output/-o required");
return false;
}
return true;
}
void Application_pc2pc::addOptions()
{
po::options_description* file_options = new po::options_description("file options");
file_options->add_options()
("input,i", po::value<std::string>(&m_inputFile), "input file name")
("output,o", po::value<std::string>(&m_outputFile), "output file name")
("native", "use native LAS classes (not liblas)")
("oracle-writer", "write data into oracle (must edit source to make this work right now)")
("oracle-reader", po::value<std::string>(&m_OracleReadSQL), "SQL to select a block table")
;
addOptionSet(file_options);
}
int Application_pc2pc::execute()
{
if (!Utils::fileExists(m_inputFile))
{
runtimeError("file not found: " + m_inputFile);
return 1;
}
std::ostream* ofs = Utils::createFile(m_outputFile);
if (hasOption("native"))
{
libpc::drivers::las::LasReader reader(m_inputFile);
const boost::uint64_t numPoints = reader.getNumPoints();
libpc::drivers::las::LasWriter writer(reader, *ofs);
//BUG: handle laz writer.setCompressed(false);
//writer.setPointFormat( reader.getPointFormatNumber() );
writer.write(numPoints);
}
else if (hasOption("oracle-writer"))
{
#ifdef LIBPC_HAVE_ORACLE
libpc::drivers::liblas::LiblasReader reader(m_inputFile);
const boost::uint64_t numPoints = reader.getNumPoints();
libpc::drivers::oci::Options options;
boost::property_tree::ptree& tree = options.GetPTree();
boost::uint32_t capacity = 10000;
tree.put("capacity", capacity);
tree.put("overwrite", true);
tree.put("connection", "lidar/lidar@oracle.hobu.biz/orcl");
// tree.put("connection", "lidar/lidar@oracle.hobu.biz/crrel");
tree.put("debug", true);
tree.put("verbose", true);
tree.put("scale.x", 0.0000001);
tree.put("scale.y", 0.0000001);
tree.put("scale.z", 0.001);
libpc::filters::CacheFilter cache(reader, 1, 1024);
libpc::filters::Chipper chipper(cache, capacity);
libpc::drivers::oci::Writer writer(chipper, options);
writer.write(numPoints);
#else
throw configuration_error("libPC not compiled with Oracle support");
#endif
}
else if (hasOption("oracle-reader"))
{
#ifdef LIBPC_HAVE_ORACLE
libpc::drivers::oci::Options options;
boost::property_tree::ptree& tree = options.GetPTree();
tree.put("capacity", 12);
tree.put("connection", "lidar/lidar@oracle.hobu.biz/orcl");
// tree.put("connection", "lidar/lidar@oracle.hobu.biz/crrel");
tree.put("debug", true);
tree.put("verbose", true);
tree.put("scale.x", 0.0000001);
tree.put("scale.y", 0.0000001);
tree.put("scale.z", 0.001);
// tree.put("select_sql", "select * from output");
// tree.put("select_sql", "select cloud from hobu where id = 5");
// tree.put("select_sql", "select cloud from hobu where id = 1");
if (m_OracleReadSQL.size() == 0) {
throw libpc_error("Select statement to read OCI data is empty!");
}
tree.put("select_sql", m_OracleReadSQL);
libpc::drivers::oci::Reader reader(options);
const boost::uint64_t numPoints = reader.getNumPoints();
libpc::drivers::liblas::LiblasWriter writer(reader, *ofs);
// writer.setPointFormat( 3);
writer.write(numPoints);
#else
throw configuration_error("libPC not compiled with Oracle support");
#endif
}
else
{
libpc::drivers::liblas::LiblasReader reader(m_inputFile);
const boost::uint64_t numPoints = reader.getNumPoints();
libpc::drivers::liblas::LiblasWriter writer(reader, *ofs);
//BUG: handle laz writer.setCompressed(false);
writer.setPointFormat( reader.getPointFormatNumber() );
writer.write(numPoints);
}
Utils::closeFile(ofs);
return 0;
}
int main(int argc, char* argv[])
{
Application_pc2pc app(argc, argv);
return app.run();
}
<commit_msg>use LasWriter instead of LiblasWriter<commit_after>/***************************************************************************
*
* Project: libLAS -- C/C++ read/write library for LAS LIDAR data
* Purpose: LAS translation with optional configuration
* Author: Howard Butler, hobu.inc at gmail.com
***************************************************************************
* Copyright (c) 2010, Howard Butler, hobu.inc at gmail.com
*
* See LICENSE.txt in this source distribution for more information.
**************************************************************************/
#include <iostream>
#include <libpc/exceptions.hpp>
//#include <libpc/libpc_config.hpp>
//#include <libpc/Bounds.hpp>
//#include <libpc/Color.hpp>
//#include <libpc/Dimension.hpp>
//#include <libpc/Schema.hpp>
#include <libpc/filters/Chipper.hpp>
//#include <libpc/ColorFilter.hpp>
//#include <libpc/MosaicFilter.hpp>
//#include <libpc/FauxReader.hpp>
//#include <libpc/FauxWriter.hpp>
#include <libpc/drivers/las/Reader.hpp>
//#include <libpc/LasHeader.hpp>
#include <libpc/drivers/las/Writer.hpp>
#include <libpc/filters/CacheFilter.hpp>
#include <libpc/drivers/liblas/Writer.hpp>
#include <libpc/drivers/liblas/Reader.hpp>
#ifdef LIBPC_HAVE_ORACLE
#include <libpc/drivers/oci/Writer.hpp>
#include <libpc/drivers/oci/Reader.hpp>
#endif
#include "Application.hpp"
using namespace libpc;
namespace po = boost::program_options;
class Application_pc2pc : public Application
{
public:
Application_pc2pc(int argc, char* argv[]);
int execute();
private:
void addOptions();
bool validateOptions();
std::string m_inputFile;
std::string m_outputFile;
std::string m_OracleReadSQL;
std::string m_OracleWriteSQL;
};
Application_pc2pc::Application_pc2pc(int argc, char* argv[])
: Application(argc, argv, "pc2pc")
{
}
bool Application_pc2pc::validateOptions()
{
if (!hasOption("input"))
{
usageError("--input/-i required");
return false;
}
if (!hasOption("output"))
{
usageError("--output/-o required");
return false;
}
return true;
}
void Application_pc2pc::addOptions()
{
po::options_description* file_options = new po::options_description("file options");
file_options->add_options()
("input,i", po::value<std::string>(&m_inputFile), "input file name")
("output,o", po::value<std::string>(&m_outputFile), "output file name")
("native", "use native LAS classes (not liblas)")
("oracle-writer", "write data into oracle (must edit source to make this work right now)")
("oracle-reader", po::value<std::string>(&m_OracleReadSQL), "SQL to select a block table")
;
addOptionSet(file_options);
}
int Application_pc2pc::execute()
{
if (!Utils::fileExists(m_inputFile))
{
runtimeError("file not found: " + m_inputFile);
return 1;
}
std::ostream* ofs = Utils::createFile(m_outputFile);
if (hasOption("native"))
{
libpc::drivers::las::LasReader reader(m_inputFile);
const boost::uint64_t numPoints = reader.getNumPoints();
libpc::drivers::las::LasWriter writer(reader, *ofs);
//BUG: handle laz writer.setCompressed(false);
//writer.setPointFormat( reader.getPointFormatNumber() );
writer.write(numPoints);
}
else if (hasOption("oracle-writer"))
{
#ifdef LIBPC_HAVE_ORACLE
libpc::drivers::liblas::LiblasReader reader(m_inputFile);
const boost::uint64_t numPoints = reader.getNumPoints();
libpc::drivers::oci::Options options;
boost::property_tree::ptree& tree = options.GetPTree();
boost::uint32_t capacity = 10000;
tree.put("capacity", capacity);
tree.put("overwrite", true);
tree.put("connection", "lidar/lidar@oracle.hobu.biz/orcl");
// tree.put("connection", "lidar/lidar@oracle.hobu.biz/crrel");
tree.put("debug", true);
tree.put("verbose", true);
tree.put("scale.x", 0.0000001);
tree.put("scale.y", 0.0000001);
tree.put("scale.z", 0.001);
libpc::filters::CacheFilter cache(reader, 1, 1024);
libpc::filters::Chipper chipper(cache, capacity);
libpc::drivers::oci::Writer writer(chipper, options);
writer.write(numPoints);
#else
throw configuration_error("libPC not compiled with Oracle support");
#endif
}
else if (hasOption("oracle-reader"))
{
#ifdef LIBPC_HAVE_ORACLE
libpc::drivers::oci::Options options;
boost::property_tree::ptree& tree = options.GetPTree();
tree.put("capacity", 12);
tree.put("connection", "lidar/lidar@oracle.hobu.biz/orcl");
// tree.put("connection", "lidar/lidar@oracle.hobu.biz/crrel");
tree.put("debug", true);
tree.put("verbose", true);
tree.put("scale.x", 0.0000001);
tree.put("scale.y", 0.0000001);
tree.put("scale.z", 0.001);
// tree.put("select_sql", "select * from output");
// tree.put("select_sql", "select cloud from hobu where id = 5");
// tree.put("select_sql", "select cloud from hobu where id = 1");
if (m_OracleReadSQL.size() == 0) {
throw libpc_error("Select statement to read OCI data is empty!");
}
tree.put("select_sql", m_OracleReadSQL);
libpc::drivers::oci::Reader reader(options);
const boost::uint64_t numPoints = reader.getNumPoints();
libpc::drivers::las::LasWriter writer(reader, *ofs);
// writer.setPointFormat( 3);
writer.write(numPoints);
#else
throw configuration_error("libPC not compiled with Oracle support");
#endif
}
else
{
libpc::drivers::liblas::LiblasReader reader(m_inputFile);
const boost::uint64_t numPoints = reader.getNumPoints();
libpc::drivers::liblas::LiblasWriter writer(reader, *ofs);
//BUG: handle laz writer.setCompressed(false);
writer.setPointFormat( reader.getPointFormatNumber() );
writer.write(numPoints);
}
Utils::closeFile(ofs);
return 0;
}
int main(int argc, char* argv[])
{
Application_pc2pc app(argc, argv);
return app.run();
}
<|endoftext|>
|
<commit_before>#include "ornsearchappsmodel.h"
#include <QCryptographicHash>
OrnSearchAppsModel::OrnSearchAppsModel(QObject *parent)
: OrnAppsModel(true, parent)
{
mCanFetchMore = false;
}
QString OrnSearchAppsModel::searchKey() const
{
return mSearchKey;
}
void OrnSearchAppsModel::setSearchKey(const QString &searchKey)
{
if (mSearchKey != searchKey)
{
mSearchKey = searchKey;
emit this->searchKeyChanged();
this->reset();
mCanFetchMore = !mSearchKey.isEmpty();
}
}
void OrnSearchAppsModel::resetImpl()
{
mPrevReplyHash.clear();
OrnAbstractListModel::resetImpl();
}
void OrnSearchAppsModel::fetchMore(const QModelIndex &parent)
{
if (parent.isValid())
{
return;
}
if (mSearchKey.isEmpty())
{
qWarning() << "Could not search with an empty search key";
return;
}
QUrlQuery query;
query.addQueryItem(QStringLiteral("keys"), mSearchKey);
OrnAbstractListModel::fetch(QStringLiteral("search/apps"), query);
}
void OrnSearchAppsModel::processReply(const QJsonDocument &jsonDoc)
{
// An ugly patch for srepeating data
auto replyHash = QCryptographicHash::hash(
jsonDoc.toJson(), QCryptographicHash::Md5);
if (mPrevReplyHash == replyHash)
{
qDebug() << "Current reply is equal to the previous one. "
"Considering the model has fetched all data";
mCanFetchMore = false;
}
else
{
mPrevReplyHash = replyHash;
}
OrnAbstractListModel::processReply(jsonDoc);
}
<commit_msg>Fix duplicate results in search model<commit_after>#include "ornsearchappsmodel.h"
#include <QCryptographicHash>
OrnSearchAppsModel::OrnSearchAppsModel(QObject *parent)
: OrnAppsModel(true, parent)
{
mCanFetchMore = false;
}
QString OrnSearchAppsModel::searchKey() const
{
return mSearchKey;
}
void OrnSearchAppsModel::setSearchKey(const QString &searchKey)
{
if (mSearchKey != searchKey)
{
mSearchKey = searchKey;
emit this->searchKeyChanged();
this->reset();
mCanFetchMore = !mSearchKey.isEmpty();
}
}
void OrnSearchAppsModel::resetImpl()
{
mPrevReplyHash.clear();
OrnAbstractListModel::resetImpl();
}
void OrnSearchAppsModel::fetchMore(const QModelIndex &parent)
{
if (parent.isValid())
{
return;
}
if (mSearchKey.isEmpty())
{
qWarning() << "Could not search with an empty search key";
return;
}
QUrlQuery query;
query.addQueryItem(QStringLiteral("keys"), mSearchKey);
OrnAbstractListModel::fetch(QStringLiteral("search/apps"), query);
}
void OrnSearchAppsModel::processReply(const QJsonDocument &jsonDoc)
{
// An ugly patch for repeating data
auto replyHash = QCryptographicHash::hash(jsonDoc.toJson(), QCryptographicHash::Md5);
if (mPrevReplyHash == replyHash)
{
qDebug() << "Current reply is equal to the previous one. "
"Considering the model has fetched all data";
mCanFetchMore = false;
return;
}
mPrevReplyHash = replyHash;
OrnAbstractListModel::processReply(jsonDoc);
}
<|endoftext|>
|
<commit_before>#include "mainwindow.h"
MainWindow::MainWindow() {
m_ui.setupUi(this);
}
<commit_msg>mainwindow: setting a label as the central widget<commit_after>#include "mainwindow.h"
#include <QLabel>
MainWindow::MainWindow() {
m_ui.setupUi(this);
QLabel *label1 = new QLabel("Hi", this);
setCentralWidget(label1);
}
<|endoftext|>
|
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QMessageBox>
#include <string>
#include <iostream>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::showFloatSummary(struct FloatSummary summary) {
if (model != nullptr) {
delete model;
}
model = new QStandardItemModel(2, 3, this);
QStringList rows, cols;
cols.append("x");
cols.append("y");
rows.append("bisekcja");
rows.append("sieczne");
rows.append("regula falsi");
model->index(1,1, model->index(0,0));
model->setHorizontalHeaderLabels(rows);
model->setVerticalHeaderLabels(cols);
model->setItem(0, 0, new QStandardItem(QString::fromStdString(summary.bisection.x)));
model->setItem(1, 0, new QStandardItem(QString::fromStdString(summary.bisection.y)));
model->setItem(0, 1, new QStandardItem(QString::fromStdString(summary.secant.x)));
model->setItem(1, 1, new QStandardItem(QString::fromStdString(summary.secant.y)));
model->setItem(0, 2, new QStandardItem(QString::fromStdString(summary.regulafalsi.x)));
model->setItem(1, 2, new QStandardItem(QString::fromStdString(summary.regulafalsi.y)));
ui->result->setModel(model);
ui->result->resizeRowsToContents();
ui->result->resizeColumnsToContents();
}
void MainWindow::showIntervalSummary(struct IntervalSummary summary) {
if (model != nullptr) {
delete model;
}
model = new QStandardItemModel(2, 3, this);
QStringList rows, cols;
cols.append("x");
cols.append("m(x)");
cols.append("d(x)");
cols.append("y");
rows.append("bisekcja");
rows.append("sieczne");
rows.append("regula falsi");
model->index(1,1, model->index(0,0));
model->setHorizontalHeaderLabels(rows);
model->setVerticalHeaderLabels(cols);
model->setItem(0, 0, new QStandardItem(QString::fromStdString(summary.bisection.x)));
model->setItem(1, 0, new QStandardItem(QString::fromStdString(summary.bisection.median)));
model->setItem(2, 0, new QStandardItem(QString::fromStdString(summary.bisection.width)));
model->setItem(3, 0, new QStandardItem(QString::fromStdString(summary.bisection.y)));
model->setItem(0, 1, new QStandardItem(QString::fromStdString(summary.secant.x)));
model->setItem(1, 1, new QStandardItem(QString::fromStdString(summary.secant.median)));
model->setItem(2, 1, new QStandardItem(QString::fromStdString(summary.secant.width)));
model->setItem(3, 1, new QStandardItem(QString::fromStdString(summary.secant.y)));
model->setItem(0, 2, new QStandardItem(QString::fromStdString(summary.regulafalsi.x)));
model->setItem(1, 2, new QStandardItem(QString::fromStdString(summary.regulafalsi.median)));
model->setItem(2, 2, new QStandardItem(QString::fromStdString(summary.regulafalsi.width)));
model->setItem(3, 2, new QStandardItem(QString::fromStdString(summary.regulafalsi.y)));
ui->result->setModel(model);
ui->result->resizeRowsToContents();
ui->result->resizeColumnsToContents();
}
void MainWindow::on_loadFunction_clicked()
{
QString library_path = QFileDialog::getOpenFileName(this, "Wczytaj funkcję",
QDir::currentPath(),
"Biblioteka dynamiczna (*.so)");
if (library_path.isNull()) {
return;
}
try {
backend.loadFunction(library_path.toLatin1().data());
} catch (const char *error) {
QMessageBox::warning(this, "Błąd", error);
return;
}
ui->solve->setEnabled(true);
}
void MainWindow::on_solve_clicked()
{
std::string a_str, b_str;
int mode;
a_str = ui->aInput->text().toStdString();
b_str = ui->bInput->text().toStdString();
mode = ui->intervalArithmetic->isChecked();
backend.decimals = ui->decimals->value();
try {
if (mode == 1) {
struct IntervalSummary output = backend.solveInterval(a_str, b_str);
showIntervalSummary(output);
} else {
struct FloatSummary output = backend.solveFloatingPoint(a_str, b_str);
showFloatSummary(output);
}
} catch (const char *error) {
QMessageBox::warning(this, "Błąd", error);
return;
}
}
<commit_msg>Display regula falsi results before secant method in the main window<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QMessageBox>
#include <string>
#include <iostream>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::showFloatSummary(struct FloatSummary summary) {
if (model != nullptr) {
delete model;
}
model = new QStandardItemModel(2, 3, this);
QStringList rows, cols;
cols.append("x");
cols.append("y");
rows.append("bisekcja");
rows.append("regula falsi");
rows.append("sieczne");
model->index(1,1, model->index(0,0));
model->setHorizontalHeaderLabels(rows);
model->setVerticalHeaderLabels(cols);
model->setItem(0, 0, new QStandardItem(QString::fromStdString(summary.bisection.x)));
model->setItem(1, 0, new QStandardItem(QString::fromStdString(summary.bisection.y)));
model->setItem(0, 1, new QStandardItem(QString::fromStdString(summary.regulafalsi.x)));
model->setItem(1, 1, new QStandardItem(QString::fromStdString(summary.regulafalsi.y)));
model->setItem(0, 2, new QStandardItem(QString::fromStdString(summary.secant.x)));
model->setItem(1, 2, new QStandardItem(QString::fromStdString(summary.secant.y)));
ui->result->setModel(model);
ui->result->resizeRowsToContents();
ui->result->resizeColumnsToContents();
}
void MainWindow::showIntervalSummary(struct IntervalSummary summary) {
if (model != nullptr) {
delete model;
}
model = new QStandardItemModel(2, 3, this);
QStringList rows, cols;
cols.append("x");
cols.append("m(x)");
cols.append("d(x)");
cols.append("y");
rows.append("bisekcja");
rows.append("regula falsi");
rows.append("sieczne");
model->index(1,1, model->index(0,0));
model->setHorizontalHeaderLabels(rows);
model->setVerticalHeaderLabels(cols);
model->setItem(0, 0, new QStandardItem(QString::fromStdString(summary.bisection.x)));
model->setItem(1, 0, new QStandardItem(QString::fromStdString(summary.bisection.median)));
model->setItem(2, 0, new QStandardItem(QString::fromStdString(summary.bisection.width)));
model->setItem(3, 0, new QStandardItem(QString::fromStdString(summary.bisection.y)));
model->setItem(0, 1, new QStandardItem(QString::fromStdString(summary.regulafalsi.x)));
model->setItem(1, 1, new QStandardItem(QString::fromStdString(summary.regulafalsi.median)));
model->setItem(2, 1, new QStandardItem(QString::fromStdString(summary.regulafalsi.width)));
model->setItem(3, 1, new QStandardItem(QString::fromStdString(summary.regulafalsi.y)));
model->setItem(0, 2, new QStandardItem(QString::fromStdString(summary.secant.x)));
model->setItem(1, 2, new QStandardItem(QString::fromStdString(summary.secant.median)));
model->setItem(2, 2, new QStandardItem(QString::fromStdString(summary.secant.width)));
model->setItem(3, 2, new QStandardItem(QString::fromStdString(summary.secant.y)));
ui->result->setModel(model);
ui->result->resizeRowsToContents();
ui->result->resizeColumnsToContents();
}
void MainWindow::on_loadFunction_clicked()
{
QString library_path = QFileDialog::getOpenFileName(this, "Wczytaj funkcję",
QDir::currentPath(),
"Biblioteka dynamiczna (*.so)");
if (library_path.isNull()) {
return;
}
try {
backend.loadFunction(library_path.toLatin1().data());
} catch (const char *error) {
QMessageBox::warning(this, "Błąd", error);
return;
}
ui->solve->setEnabled(true);
}
void MainWindow::on_solve_clicked()
{
std::string a_str, b_str;
int mode;
a_str = ui->aInput->text().toStdString();
b_str = ui->bInput->text().toStdString();
mode = ui->intervalArithmetic->isChecked();
backend.decimals = ui->decimals->value();
try {
if (mode == 1) {
struct IntervalSummary output = backend.solveInterval(a_str, b_str);
showIntervalSummary(output);
} else {
struct FloatSummary output = backend.solveFloatingPoint(a_str, b_str);
showFloatSummary(output);
}
} catch (const char *error) {
QMessageBox::warning(this, "Błąd", error);
return;
}
}
<|endoftext|>
|
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
marks_select();
ui->form_save_lable->hide();
ui->dateEdit->setDate(current_date);
connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(send_form()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::marks_select()
{
marks_text = "";
QSqlDatabase dbase = QSqlDatabase::addDatabase("QSQLITE");
dbase.setDatabaseName("C:/qtprojects/curs/mydatabase.sqlite");
if (!dbase.open())
{
qDebug() << "Ошибка открытия базы данных!";
}
QSqlQuery a_query;
if (!a_query.exec("SELECT * FROM marks WHERE time = date('now')"))
{
qDebug() << "Ошибка выполнения запроса SELECT";
}
QSqlRecord rec = a_query.record();
while (a_query.next())
{
marks_text.append("\n\n");
marks_text.append(a_query.value(rec.indexOf("text")).toString());
}
ui->marks_conteiner->setText(marks_text);
}
void MainWindow::send_form()
{
QSqlQuery a_query;
mark = ui->textEdit->toPlainText();
form_date = ui->dateEdit->text();
QString str_insert = "INSERT INTO marks(text,time) "
"VALUES ('%1', '%2');";
QString str = str_insert.arg(mark)
.arg(form_date);
bool b = a_query.exec(str);
if (!b)
{
qDebug() << "Ошибка выполнения запроса INSERT";
}
ui->textEdit->clear();
ui->dateEdit->setDate(current_date);
ui->form_save_lable->show();
marks_select();
}
<commit_msg>изменение пути файла базы данных<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
marks_select();
ui->form_save_lable->hide();
ui->dateEdit->setDate(current_date);
connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(send_form()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::marks_select()
{
marks_text = "";
QSqlDatabase dbase = QSqlDatabase::addDatabase("QSQLITE");
dbase.setDatabaseName("C:/qtprojects/curs/course_2016.git/mydatabase.sqlite");
if (!dbase.open())
{
qDebug() << "Ошибка открытия базы данных!";
}
QSqlQuery a_query;
if (!a_query.exec("SELECT * FROM marks WHERE time = date('now')"))
{
qDebug() << "Ошибка выполнения запроса SELECT";
}
QSqlRecord rec = a_query.record();
while (a_query.next())
{
marks_text.append("\n\n");
marks_text.append(a_query.value(rec.indexOf("text")).toString());
}
ui->marks_conteiner->setText(marks_text);
}
void MainWindow::send_form()
{
QSqlQuery a_query;
mark = ui->textEdit->toPlainText();
form_date = ui->dateEdit->text();
QString str_insert = "INSERT INTO marks(text,time) "
"VALUES ('%1', '%2');";
QString str = str_insert.arg(mark)
.arg(form_date);
bool b = a_query.exec(str);
if (!b)
{
qDebug() << "Ошибка выполнения запроса INSERT";
}
ui->textEdit->clear();
ui->dateEdit->setDate(current_date);
ui->form_save_lable->show();
marks_select();
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2006, MassaRoddel, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/shared_ptr.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/peer_connection.hpp"
#include "libtorrent/bt_peer_connection.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent.hpp"
#include "libtorrent/extensions.hpp"
#include "libtorrent/extensions/ut_pex.hpp"
namespace libtorrent { namespace
{
const char extension_name[] = "ut_pex";
enum
{
extension_index = 1,
max_peer_entries = 100
};
bool send_peer(peer_connection const& p)
{
// don't send out peers that we haven't connected to
// (that have connected to us)
if (!p.is_local()) return false;
// don't send out peers that we haven't successfully connected to
if (p.is_connecting()) return false;
return true;
}
struct ut_pex_plugin: torrent_plugin
{
ut_pex_plugin(torrent& t): m_torrent(t), m_1_minute(55) {}
virtual boost::shared_ptr<peer_plugin> new_connection(peer_connection* pc);
std::vector<char>& get_ut_pex_msg()
{
return m_ut_pex_msg;
}
// the second tick of the torrent
// each minute the new lists of "added" + "added.f" and "dropped"
// are calculated here and the pex message is created
// each peer connection will use this message
// max_peer_entries limits the packet size
virtual void tick()
{
if (++m_1_minute < 60) return;
m_1_minute = 0;
entry pex;
std::string& pla = pex["added"].string();
std::string& pld = pex["dropped"].string();
std::string& plf = pex["added.f"].string();
std::string& pla6 = pex["added6"].string();
std::string& pld6 = pex["dropped6"].string();
std::string& plf6 = pex["added6.f"].string();
std::back_insert_iterator<std::string> pla_out(pla);
std::back_insert_iterator<std::string> pld_out(pld);
std::back_insert_iterator<std::string> plf_out(plf);
std::back_insert_iterator<std::string> pla6_out(pla6);
std::back_insert_iterator<std::string> pld6_out(pld6);
std::back_insert_iterator<std::string> plf6_out(plf6);
std::set<tcp::endpoint> dropped;
m_old_peers.swap(dropped);
int num_added = 0;
for (torrent::peer_iterator i = m_torrent.begin()
, end(m_torrent.end()); i != end; ++i)
{
peer_connection* peer = *i;
if (!send_peer(*peer)) continue;
tcp::endpoint const& remote = peer->remote();
m_old_peers.insert(remote);
std::set<tcp::endpoint>::iterator di = dropped.find(remote);
if (di == dropped.end())
{
// don't write too big of a package
if (num_added >= max_peer_entries) break;
// only send proper bittorrent peers
bt_peer_connection* p = dynamic_cast<bt_peer_connection*>(peer);
if (!p) continue;
// no supported flags to set yet
// 0x01 - peer supports encryption
// 0x02 - peer is a seed
int flags = p->is_seed() ? 2 : 0;
#ifndef TORRENT_DISABLE_ENCRYPTION
flags |= p->supports_encryption() ? 1 : 0;
#endif
// i->first was added since the last time
if (remote.address().is_v4())
{
detail::write_endpoint(remote, pla_out);
detail::write_uint8(flags, plf_out);
}
else
{
detail::write_endpoint(remote, pla6_out);
detail::write_uint8(flags, plf6_out);
}
++num_added;
}
else
{
// this was in the previous message
// so, it wasn't dropped
dropped.erase(di);
}
}
for (std::set<tcp::endpoint>::const_iterator i = dropped.begin()
, end(dropped.end()); i != end; ++i)
{
if (i->address().is_v4())
detail::write_endpoint(*i, pld_out);
else
detail::write_endpoint(*i, pld6_out);
}
m_ut_pex_msg.clear();
bencode(std::back_inserter(m_ut_pex_msg), pex);
}
private:
torrent& m_torrent;
std::set<tcp::endpoint> m_old_peers;
int m_1_minute;
std::vector<char> m_ut_pex_msg;
};
struct ut_pex_peer_plugin : peer_plugin
{
ut_pex_peer_plugin(torrent& t, peer_connection& pc, ut_pex_plugin& tp)
: m_torrent(t)
, m_pc(pc)
, m_tp(tp)
, m_1_minute(55)
, m_message_index(0)
, m_first_time(true)
{}
virtual void add_handshake(entry& h)
{
entry& messages = h["m"];
messages[extension_name] = extension_index;
}
virtual bool on_extension_handshake(entry const& h)
{
m_message_index = 0;
entry const* messages = h.find_key("m");
if (!messages || messages->type() != entry::dictionary_t) return false;
entry const* index = messages->find_key(extension_name);
if (!index || index->type() != entry::int_t) return false;
m_message_index = int(index->integer());
return true;
}
virtual bool on_extended(int length, int msg, buffer::const_interval body)
{
if (msg != extension_index) return false;
if (m_message_index == 0) return false;
if (length > 500 * 1024)
throw protocol_error("uT peer exchange message larger than 500 kB");
if (body.left() < length) return true;
entry pex_msg = bdecode(body.begin, body.end);
entry const* p = pex_msg.find_key("added");
entry const* pf = pex_msg.find_key("added.f");
if (p != 0 && pf != 0 && p->type() == entry::string_t && pf->type() == entry::string_t)
{
std::string const& peers = p->string();
std::string const& peer_flags = pf->string();
int num_peers = peers.length() / 6;
char const* in = peers.c_str();
char const* fin = peer_flags.c_str();
if (int(peer_flags.size()) != num_peers)
return true;
peer_id pid(0);
policy& p = m_torrent.get_policy();
for (int i = 0; i < num_peers; ++i)
{
tcp::endpoint adr = detail::read_v4_endpoint<tcp::endpoint>(in);
char flags = detail::read_uint8(fin);
p.peer_from_tracker(adr, pid, peer_info::pex, flags);
}
}
entry const* p6 = pex_msg.find_key("added6");
entry const* p6f = pex_msg.find_key("added6.f");
if (p6 && p6f && p6->type() == entry::string_t && p6f->type() == entry::string_t)
{
std::string const& peers6 = p6->string();
std::string const& peer6_flags = p6f->string();
int num_peers = peers6.length() / 18;
char const* in = peers6.c_str();
char const* fin = peer6_flags.c_str();
if (int(peer6_flags.size()) != num_peers)
return true;
peer_id pid(0);
policy& p = m_torrent.get_policy();
for (int i = 0; i < num_peers; ++i)
{
tcp::endpoint adr = detail::read_v6_endpoint<tcp::endpoint>(in);
char flags = detail::read_uint8(fin);
p.peer_from_tracker(adr, pid, peer_info::pex, flags);
}
}
return true;
}
// the peers second tick
// every minute we send a pex message
virtual void tick()
{
if (!m_message_index) return; // no handshake yet
if (++m_1_minute <= 60) return;
if (m_first_time)
{
send_ut_peer_list();
m_first_time = false;
}
else
{
send_ut_peer_diff();
}
m_1_minute = 0;
}
private:
void send_ut_peer_diff()
{
std::vector<char> const& pex_msg = m_tp.get_ut_pex_msg();
buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size());
detail::write_uint32(1 + 1 + pex_msg.size(), i.begin);
detail::write_uint8(bt_peer_connection::msg_extended, i.begin);
detail::write_uint8(m_message_index, i.begin);
std::copy(pex_msg.begin(), pex_msg.end(), i.begin);
i.begin += pex_msg.size();
TORRENT_ASSERT(i.begin == i.end);
m_pc.setup_send();
}
void send_ut_peer_list()
{
entry pex;
// leave the dropped string empty
pex["dropped"].string();
std::string& pla = pex["added"].string();
std::string& plf = pex["added.f"].string();
pex["dropped6"].string();
std::string& pla6 = pex["added6"].string();
std::string& plf6 = pex["added6.f"].string();
std::back_insert_iterator<std::string> pla_out(pla);
std::back_insert_iterator<std::string> plf_out(plf);
std::back_insert_iterator<std::string> pla6_out(pla6);
std::back_insert_iterator<std::string> plf6_out(plf6);
int num_added = 0;
for (torrent::peer_iterator i = m_torrent.begin()
, end(m_torrent.end()); i != end; ++i)
{
peer_connection* peer = *i;
if (!send_peer(*peer)) continue;
// don't write too big of a package
if (num_added >= max_peer_entries) break;
// only send proper bittorrent peers
bt_peer_connection* p = dynamic_cast<bt_peer_connection*>(peer);
if (!p) continue;
// no supported flags to set yet
// 0x01 - peer supports encryption
// 0x02 - peer is a seed
int flags = p->is_seed() ? 2 : 0;
#ifndef TORRENT_DISABLE_ENCRYPTION
flags |= p->supports_encryption() ? 1 : 0;
#endif
tcp::endpoint const& remote = peer->remote();
// i->first was added since the last time
if (remote.address().is_v4())
{
detail::write_endpoint(remote, pla_out);
detail::write_uint8(flags, plf_out);
}
else
{
detail::write_endpoint(remote, pla6_out);
detail::write_uint8(flags, plf6_out);
}
++num_added;
}
std::vector<char> pex_msg;
bencode(std::back_inserter(pex_msg), pex);
buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size());
detail::write_uint32(1 + 1 + pex_msg.size(), i.begin);
detail::write_uint8(bt_peer_connection::msg_extended, i.begin);
detail::write_uint8(m_message_index, i.begin);
std::copy(pex_msg.begin(), pex_msg.end(), i.begin);
i.begin += pex_msg.size();
TORRENT_ASSERT(i.begin == i.end);
m_pc.setup_send();
}
torrent& m_torrent;
peer_connection& m_pc;
ut_pex_plugin& m_tp;
int m_1_minute;
int m_message_index;
// this is initialized to true, and set to
// false after the first pex message has been sent.
// it is used to know if a diff message or a full
// message should be sent.
bool m_first_time;
};
boost::shared_ptr<peer_plugin> ut_pex_plugin::new_connection(peer_connection* pc)
{
bt_peer_connection* c = dynamic_cast<bt_peer_connection*>(pc);
if (!c) return boost::shared_ptr<peer_plugin>();
return boost::shared_ptr<peer_plugin>(new ut_pex_peer_plugin(m_torrent
, *pc, *this));
}
}}
namespace libtorrent
{
boost::shared_ptr<torrent_plugin> create_ut_pex_plugin(torrent* t, void*)
{
if (t->torrent_file().priv())
{
return boost::shared_ptr<torrent_plugin>();
}
return boost::shared_ptr<torrent_plugin>(new ut_pex_plugin(*t));
}
}
<commit_msg>ut_pex exception fix<commit_after>/*
Copyright (c) 2006, MassaRoddel, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/shared_ptr.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/peer_connection.hpp"
#include "libtorrent/bt_peer_connection.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent.hpp"
#include "libtorrent/extensions.hpp"
#include "libtorrent/extensions/ut_pex.hpp"
namespace libtorrent { namespace
{
const char extension_name[] = "ut_pex";
enum
{
extension_index = 1,
max_peer_entries = 100
};
bool send_peer(peer_connection const& p)
{
// don't send out peers that we haven't connected to
// (that have connected to us)
if (!p.is_local()) return false;
// don't send out peers that we haven't successfully connected to
if (p.is_connecting()) return false;
return true;
}
struct ut_pex_plugin: torrent_plugin
{
ut_pex_plugin(torrent& t): m_torrent(t), m_1_minute(55) {}
virtual boost::shared_ptr<peer_plugin> new_connection(peer_connection* pc);
std::vector<char>& get_ut_pex_msg()
{
return m_ut_pex_msg;
}
// the second tick of the torrent
// each minute the new lists of "added" + "added.f" and "dropped"
// are calculated here and the pex message is created
// each peer connection will use this message
// max_peer_entries limits the packet size
virtual void tick()
{
if (++m_1_minute < 60) return;
m_1_minute = 0;
entry pex;
std::string& pla = pex["added"].string();
std::string& pld = pex["dropped"].string();
std::string& plf = pex["added.f"].string();
std::string& pla6 = pex["added6"].string();
std::string& pld6 = pex["dropped6"].string();
std::string& plf6 = pex["added6.f"].string();
std::back_insert_iterator<std::string> pla_out(pla);
std::back_insert_iterator<std::string> pld_out(pld);
std::back_insert_iterator<std::string> plf_out(plf);
std::back_insert_iterator<std::string> pla6_out(pla6);
std::back_insert_iterator<std::string> pld6_out(pld6);
std::back_insert_iterator<std::string> plf6_out(plf6);
std::set<tcp::endpoint> dropped;
m_old_peers.swap(dropped);
int num_added = 0;
for (torrent::peer_iterator i = m_torrent.begin()
, end(m_torrent.end()); i != end; ++i)
{
peer_connection* peer = *i;
if (!send_peer(*peer)) continue;
tcp::endpoint const& remote = peer->remote();
m_old_peers.insert(remote);
std::set<tcp::endpoint>::iterator di = dropped.find(remote);
if (di == dropped.end())
{
// don't write too big of a package
if (num_added >= max_peer_entries) break;
// only send proper bittorrent peers
bt_peer_connection* p = dynamic_cast<bt_peer_connection*>(peer);
if (!p) continue;
// no supported flags to set yet
// 0x01 - peer supports encryption
// 0x02 - peer is a seed
int flags = p->is_seed() ? 2 : 0;
#ifndef TORRENT_DISABLE_ENCRYPTION
flags |= p->supports_encryption() ? 1 : 0;
#endif
// i->first was added since the last time
if (remote.address().is_v4())
{
detail::write_endpoint(remote, pla_out);
detail::write_uint8(flags, plf_out);
}
else
{
detail::write_endpoint(remote, pla6_out);
detail::write_uint8(flags, plf6_out);
}
++num_added;
}
else
{
// this was in the previous message
// so, it wasn't dropped
dropped.erase(di);
}
}
for (std::set<tcp::endpoint>::const_iterator i = dropped.begin()
, end(dropped.end()); i != end; ++i)
{
if (i->address().is_v4())
detail::write_endpoint(*i, pld_out);
else
detail::write_endpoint(*i, pld6_out);
}
m_ut_pex_msg.clear();
bencode(std::back_inserter(m_ut_pex_msg), pex);
}
private:
torrent& m_torrent;
std::set<tcp::endpoint> m_old_peers;
int m_1_minute;
std::vector<char> m_ut_pex_msg;
};
struct ut_pex_peer_plugin : peer_plugin
{
ut_pex_peer_plugin(torrent& t, peer_connection& pc, ut_pex_plugin& tp)
: m_torrent(t)
, m_pc(pc)
, m_tp(tp)
, m_1_minute(55)
, m_message_index(0)
, m_first_time(true)
{}
virtual void add_handshake(entry& h)
{
entry& messages = h["m"];
messages[extension_name] = extension_index;
}
virtual bool on_extension_handshake(entry const& h)
{
m_message_index = 0;
entry const* messages = h.find_key("m");
if (!messages || messages->type() != entry::dictionary_t) return false;
entry const* index = messages->find_key(extension_name);
if (!index || index->type() != entry::int_t) return false;
m_message_index = int(index->integer());
return true;
}
virtual bool on_extended(int length, int msg, buffer::const_interval body)
{
if (msg != extension_index) return false;
if (m_message_index == 0) return false;
if (length > 500 * 1024)
{
m_pc.disconnect("peer exchange message larger than 500 kB");
return true;
}
if (body.left() < length) return true;
entry pex_msg = bdecode(body.begin, body.end);
entry const* p = pex_msg.find_key("added");
entry const* pf = pex_msg.find_key("added.f");
if (p != 0 && pf != 0 && p->type() == entry::string_t && pf->type() == entry::string_t)
{
std::string const& peers = p->string();
std::string const& peer_flags = pf->string();
int num_peers = peers.length() / 6;
char const* in = peers.c_str();
char const* fin = peer_flags.c_str();
if (int(peer_flags.size()) != num_peers)
return true;
peer_id pid(0);
policy& p = m_torrent.get_policy();
for (int i = 0; i < num_peers; ++i)
{
tcp::endpoint adr = detail::read_v4_endpoint<tcp::endpoint>(in);
char flags = detail::read_uint8(fin);
p.peer_from_tracker(adr, pid, peer_info::pex, flags);
}
}
entry const* p6 = pex_msg.find_key("added6");
entry const* p6f = pex_msg.find_key("added6.f");
if (p6 && p6f && p6->type() == entry::string_t && p6f->type() == entry::string_t)
{
std::string const& peers6 = p6->string();
std::string const& peer6_flags = p6f->string();
int num_peers = peers6.length() / 18;
char const* in = peers6.c_str();
char const* fin = peer6_flags.c_str();
if (int(peer6_flags.size()) != num_peers)
return true;
peer_id pid(0);
policy& p = m_torrent.get_policy();
for (int i = 0; i < num_peers; ++i)
{
tcp::endpoint adr = detail::read_v6_endpoint<tcp::endpoint>(in);
char flags = detail::read_uint8(fin);
p.peer_from_tracker(adr, pid, peer_info::pex, flags);
}
}
return true;
}
// the peers second tick
// every minute we send a pex message
virtual void tick()
{
if (!m_message_index) return; // no handshake yet
if (++m_1_minute <= 60) return;
if (m_first_time)
{
send_ut_peer_list();
m_first_time = false;
}
else
{
send_ut_peer_diff();
}
m_1_minute = 0;
}
private:
void send_ut_peer_diff()
{
std::vector<char> const& pex_msg = m_tp.get_ut_pex_msg();
buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size());
detail::write_uint32(1 + 1 + pex_msg.size(), i.begin);
detail::write_uint8(bt_peer_connection::msg_extended, i.begin);
detail::write_uint8(m_message_index, i.begin);
std::copy(pex_msg.begin(), pex_msg.end(), i.begin);
i.begin += pex_msg.size();
TORRENT_ASSERT(i.begin == i.end);
m_pc.setup_send();
}
void send_ut_peer_list()
{
entry pex;
// leave the dropped string empty
pex["dropped"].string();
std::string& pla = pex["added"].string();
std::string& plf = pex["added.f"].string();
pex["dropped6"].string();
std::string& pla6 = pex["added6"].string();
std::string& plf6 = pex["added6.f"].string();
std::back_insert_iterator<std::string> pla_out(pla);
std::back_insert_iterator<std::string> plf_out(plf);
std::back_insert_iterator<std::string> pla6_out(pla6);
std::back_insert_iterator<std::string> plf6_out(plf6);
int num_added = 0;
for (torrent::peer_iterator i = m_torrent.begin()
, end(m_torrent.end()); i != end; ++i)
{
peer_connection* peer = *i;
if (!send_peer(*peer)) continue;
// don't write too big of a package
if (num_added >= max_peer_entries) break;
// only send proper bittorrent peers
bt_peer_connection* p = dynamic_cast<bt_peer_connection*>(peer);
if (!p) continue;
// no supported flags to set yet
// 0x01 - peer supports encryption
// 0x02 - peer is a seed
int flags = p->is_seed() ? 2 : 0;
#ifndef TORRENT_DISABLE_ENCRYPTION
flags |= p->supports_encryption() ? 1 : 0;
#endif
tcp::endpoint const& remote = peer->remote();
// i->first was added since the last time
if (remote.address().is_v4())
{
detail::write_endpoint(remote, pla_out);
detail::write_uint8(flags, plf_out);
}
else
{
detail::write_endpoint(remote, pla6_out);
detail::write_uint8(flags, plf6_out);
}
++num_added;
}
std::vector<char> pex_msg;
bencode(std::back_inserter(pex_msg), pex);
buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size());
detail::write_uint32(1 + 1 + pex_msg.size(), i.begin);
detail::write_uint8(bt_peer_connection::msg_extended, i.begin);
detail::write_uint8(m_message_index, i.begin);
std::copy(pex_msg.begin(), pex_msg.end(), i.begin);
i.begin += pex_msg.size();
TORRENT_ASSERT(i.begin == i.end);
m_pc.setup_send();
}
torrent& m_torrent;
peer_connection& m_pc;
ut_pex_plugin& m_tp;
int m_1_minute;
int m_message_index;
// this is initialized to true, and set to
// false after the first pex message has been sent.
// it is used to know if a diff message or a full
// message should be sent.
bool m_first_time;
};
boost::shared_ptr<peer_plugin> ut_pex_plugin::new_connection(peer_connection* pc)
{
bt_peer_connection* c = dynamic_cast<bt_peer_connection*>(pc);
if (!c) return boost::shared_ptr<peer_plugin>();
return boost::shared_ptr<peer_plugin>(new ut_pex_peer_plugin(m_torrent
, *pc, *this));
}
}}
namespace libtorrent
{
boost::shared_ptr<torrent_plugin> create_ut_pex_plugin(torrent* t, void*)
{
if (t->torrent_file().priv())
{
return boost::shared_ptr<torrent_plugin>();
}
return boost::shared_ptr<torrent_plugin>(new ut_pex_plugin(*t));
}
}
<|endoftext|>
|
<commit_before>// Copyright 2012 the V8 project authors. 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "v8.h"
#include "version.h"
// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION 3
#define MINOR_VERSION 20
#define BUILD_NUMBER 16
#define PATCH_LEVEL 0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1
// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME ""
#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif
#define SX(x) #x
#define S(x) SX(x)
#if PATCH_LEVEL > 0
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \
S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \
CANDIDATE_STRING
#endif
namespace v8 {
namespace internal {
int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;
// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
const char* is_simulator = " SIMULATOR";
#else
const char* is_simulator = "";
#endif // USE_SIMULATOR
if (GetPatch() > 0) {
OS::SNPrintF(str, "%d.%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
is_simulator);
} else {
OS::SNPrintF(str, "%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), candidate,
is_simulator);
}
}
// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
if (soname_ == NULL || *soname_ == '\0') {
// Generate generic SONAME if no specific SONAME is defined.
const char* candidate = IsCandidate() ? "-candidate" : "";
if (GetPatch() > 0) {
OS::SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
} else {
OS::SNPrintF(str, "libv8-%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), candidate);
}
} else {
// Use specific SONAME.
OS::SNPrintF(str, "%s", soname_);
}
}
} } // namespace v8::internal
<commit_msg>Fix src/version.cc number to be consistent with next trunk push<commit_after>// Copyright 2012 the V8 project authors. 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "v8.h"
#include "version.h"
// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION 3
#define MINOR_VERSION 20
#define BUILD_NUMBER 17
#define PATCH_LEVEL 0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1
// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME ""
#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif
#define SX(x) #x
#define S(x) SX(x)
#if PATCH_LEVEL > 0
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \
S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \
CANDIDATE_STRING
#endif
namespace v8 {
namespace internal {
int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;
// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
const char* is_simulator = " SIMULATOR";
#else
const char* is_simulator = "";
#endif // USE_SIMULATOR
if (GetPatch() > 0) {
OS::SNPrintF(str, "%d.%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
is_simulator);
} else {
OS::SNPrintF(str, "%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), candidate,
is_simulator);
}
}
// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
if (soname_ == NULL || *soname_ == '\0') {
// Generate generic SONAME if no specific SONAME is defined.
const char* candidate = IsCandidate() ? "-candidate" : "";
if (GetPatch() > 0) {
OS::SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
} else {
OS::SNPrintF(str, "libv8-%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), candidate);
}
} else {
// Use specific SONAME.
OS::SNPrintF(str, "%s", soname_);
}
}
} } // namespace v8::internal
<|endoftext|>
|
<commit_before>#include <string.h>
#if defined(__SSE2__)
#include <emmintrin.h>
#endif
#if defined(__SSE4_1__)
#include <smmintrin.h>
#endif
#include "m_half.h"
#include "m_const.h"
namespace m {
static struct halfData {
halfData();
// 1536 bytes
uint32_t baseTable[512];
uint8_t shiftTable[512];
} gHalf;
halfData::halfData() {
for (int i = 0, e = 0; i < 256; ++i) {
e = i - 127;
if (e < -24) {
// When magnitude of the number is really small (2^-24 or smaller),
// there is no possible half-float representation for the number, so
// it must be mapped to zero (or negative zero). Setting the shift
// table entries to 24 will shift all mantissa bits, leaving just zero.
// Base tables store zero otherwise (0x8000 for negative zero case.)
baseTable[i|0x000] = 0x0000;
baseTable[i|0x100] = 0x8000;
shiftTable[i|0x000] = 24;
shiftTable[i|0x100] = 24;
} else if (e < -14) {
// When the number is small (< 2^-14), the value can only be
// represented using a subnormal half-float. This is the most
// complex case: first, the leading 1-bit, implicitly represented
// in the normalized representation, must be explicitly added, then
// the resulting mantissa must be shifted rightward, or over a number
// of bit-positions as determined by the exponent. Here we prefer to
// shift the original mantissa bits, and add the pre-shifted 1-bit to
// it.
//
// Note: Shifting by -e-14 will never be negative, thus ensuring
// proper conversion, an alternative method is to shift by 18-e, which
// depends on implementation-defined behavior of unsigned shift.
baseTable[i|0x000] = (0x0400 >> (-e-14));
baseTable[i|0x100] = (0x0400 >> (-e-14)) | 0x8000;
shiftTable[i|0x000] = -e-1;
shiftTable[i|0x100] = -e-1;
} else if (e <= 15) {
// Normal numbers (smaller than 2^15), can be represented using half
// floats, albeit with slightly less precision. The entries in the
// base table are simply set to the bias-adjust exponent value, shifted
// into the right position. A sign bit is added for the negative case.
baseTable[i|0x000] = ((e+15) << 10);
baseTable[i|0x100] = ((e+15) << 10) | 0x8000;
shiftTable[i|0x000] = 13;
shiftTable[i|0x100] = 13;
} else if (e < 128) {
// Large values (numbers less than 2^128) must be mapped to half-float
// Infinity, They are too large to be represented as half-floats. In
// this case the base table is set to 0x7C00 (with sign if negative)
// and the mantissa is zeroed out, which is accomplished by shifting
// out all mantissa bits.
baseTable[i|0x000] = 0x7C00;
baseTable[i|0x100] = 0xFC00;
shiftTable[i|0x000] = 24;
shiftTable[i|0x100] = 24;
} else {
// Remaining float numbers such as Infs and NaNs should stay Infs and
// NaNs after conversion. The base table entries are exactly the same
// as the previous case, except the mantissa-bits are to be preserved
// as much as possible.
baseTable[i|0x000] = 0x7C00;
baseTable[i|0x100] = 0xFC00;
shiftTable[i|0x000] = 13;
shiftTable[i|0x100] = 13;
}
}
}
half convertToHalf(float in) {
const floatShape shape = { in };
return gHalf.baseTable[(shape.asInt >> 23) & 0x1FF] +
((shape.asInt & 0x007FFFFF) >> gHalf.shiftTable[(shape.asInt >> 23) & 0x1FF]);
}
float convertToFloat(half in) {
static constexpr uint32_t kMagic = 113 << 23;
static constexpr uint32_t kShiftedExp = 0x7C00 << 13; // exponent mask after shift
static constexpr floatShape kMagicShape = { kMagic };
floatShape out = { uint32_t(in & 0x7FFF) << 13 }; // exponent/mantissa bits
const size_t exp = kShiftedExp & out.asInt; // exponent
out.asInt += (127 - 15) << 23; // adjust exponent
if (exp == kShiftedExp) {
// extra adjustment of exponent for Inf/Nan?
out.asInt += (128 - 16) << 23;
} else if (exp == 0) {
// extra adjustment of exponent for Zero/Denormal?
out.asInt += 1 << 23;
// renormalize
out.asFloat -= kMagicShape.asFloat;
}
// sign bit
out.asInt |= (in & 0x8000) << 16;
return out.asFloat;
}
#if defined(__SSE2__)
union vectorShape {
__m128i asVector;
alignas(16) uint32_t asInt[4];
};
template <unsigned int I>
static inline uint32_t extractScalar(__m128i v) {
#if defined(__SSE4_1__)
return _mm_extract_epi32(v, I);
#else
return _mm_cvtsi128_si32(_mm_shuffle_epi32(v, _MM_SHUFFLE(I,I,I,I)));
#endif
}
static __m128i convertToHalfSSE2(__m128 f) {
// ~15 SSE2 ops
alignas(16) static const uint32_t kMaskAbsolute[4] = { 0x7fffffffu, 0x7fffffffu, 0x7fffffffu, 0x7fffffffu };
alignas(16) static const uint32_t kInf32[4] = { 255 << 23, 255 << 23, 255 << 23, 255 << 23 };
alignas(16) static const uint32_t kExpInf[4] = { (255 ^ 31) << 23, (255 ^ 31) << 23, (255 ^ 31) << 23, (255 ^ 31) << 23 };
alignas(16) static const uint32_t kMax[4] = { (127 + 16) << 23, (127 + 16) << 23, (127 + 16) << 23, (127 + 16) << 23 };
alignas(16) static const uint32_t kMagic[4] = { 15 << 23, 15 << 23, 15 << 23, 15 << 23 };
const __m128 maskAbsolute = *(const __m128 *const)&kMaskAbsolute;
const __m128 absolute = _mm_and_ps(maskAbsolute, f);
const __m128 justSign = _mm_xor_ps(f, absolute);
const __m128 max = *(const __m128 *const)&kMax;
const __m128 expInf = *(const __m128 *const)&kExpInf;
const __m128 infNanCase = _mm_xor_ps(expInf, absolute);
const __m128 clamped = _mm_min_ps(max, absolute);
const __m128 notNormal = _mm_cmpnlt_ps(absolute, *(const __m128 *const)&kInf32);
const __m128 scaled = _mm_mul_ps(clamped, *(const __m128 *const)&kMagic);
const __m128 merge1 = _mm_and_ps(infNanCase, notNormal);
const __m128 merge2 = _mm_andnot_ps(notNormal, scaled);
const __m128 merged = _mm_or_ps(merge1, merge2);
const __m128i shifted = _mm_srli_epi32(_mm_castps_si128(merged), 13);
const __m128i signShifted = _mm_srli_epi32(_mm_castps_si128(justSign), 16);
const __m128i value = _mm_or_si128(shifted, signShifted);
return value;
}
static __m128 convertToFloatSSE2(__m128i h) {
// ~19 SSE2 ops
alignas(16) static const uint32_t kMaskNoSign[4] = { 0x7fff, 0x7fff, 0x7fff, 0x7fff };
alignas(16) static const uint32_t kSmallestNormal[4] = { 0x0400, 0x0400, 0x0400, 0x0400 };
alignas(16) static const uint32_t kInfinity[4] = { 0x7c00, 0x7c00, 0x7c00, 0x7c00 };
alignas(16) static const uint32_t kExpAdjustNormal[4] = { (127 - 15) << 23, (127 - 15) << 23, (127 - 15) << 23, (127 - 15) << 23, };
alignas(16) static const uint32_t kMagicDenormal[4] = { 113 << 23, 113 << 23, 113 << 23, 113 << 23 };
const __m128i noSign = *(const __m128i *const)&kMaskNoSign;
const __m128i exponentAdjust = *(const __m128i *const)&kExpAdjustNormal;
const __m128i smallest = *(const __m128i *const)&kSmallestNormal;
const __m128i infinity = *(const __m128i *const)&kInfinity;
const __m128i expAnd = _mm_and_si128(noSign, h);
const __m128i justSign = _mm_xor_si128(h, expAnd);
const __m128i notInfNan = _mm_cmpgt_epi32(infinity, expAnd);
const __m128i isDenormal = _mm_cmpgt_epi32(smallest, expAnd);
const __m128i shifted = _mm_slli_epi32(expAnd, 13);
const __m128i adjustInfNan = _mm_andnot_si128(notInfNan, exponentAdjust);
const __m128i adjusted = _mm_add_epi32(exponentAdjust, shifted);
const __m128i denormal1 = _mm_add_epi32(shifted, *(const __m128i *const)&kMagicDenormal);
const __m128i adjusted2 = _mm_add_epi32(adjusted, adjustInfNan);
const __m128 denormal2 = _mm_sub_ps(_mm_castsi128_ps(denormal1), *(const __m128 *const)&kMagicDenormal);
const __m128 adjusted3 = _mm_and_ps(denormal2, _mm_castsi128_ps(isDenormal));
const __m128 adjusted4 = _mm_andnot_ps(_mm_castsi128_ps(isDenormal), _mm_castsi128_ps(adjusted2));
const __m128 adjusted5 = _mm_or_ps(adjusted3, adjusted4);
const __m128i sign = _mm_slli_epi32(justSign, 16);
const __m128 value = _mm_or_ps(adjusted5, _mm_castsi128_ps(sign));
return value;
}
#endif
u::vector<half> convertToHalf(const float *const input, size_t length) {
u::vector<half> result(length);
const float *in = input;
U_ASSERT(((uintptr_t)(const void *)in) % 16 == 0);
U_ASSUME_ALIGNED(in, 16);
#if defined(__SSE2__)
const int blocks = int(length) / 4;
const int remainder = int(length) % 4;
int where = 0;
for (int i = 0; i < blocks; i++) {
const __m128 value = _mm_load_ps(&in[where]);
const __m128i convert = convertToHalfSSE2(value);
result[where++] = extractScalar<0>(convert);
result[where++] = extractScalar<1>(convert);
result[where++] = extractScalar<2>(convert);
result[where++] = extractScalar<3>(convert);
}
for (int i = 0; i < remainder; i++)
result[where+i] = convertToHalf(in[where+i]);
#else
for (size_t i = 0; i < length; i++)
result[i] = convertToHalf(in[i]);
#endif
return result;
}
u::vector<float> convertToFloat(const half *const input, size_t length) {
u::vector<float> result(length);
#if defined(__SSE2__)
const half *in = input;
U_ASSUME_ALIGNED(in, 16);
const int blocks = int(length) / 4;
const int remainder = int(length) % 4;
int where = 0;
for (int i = 0; i < blocks; i++, where += 4) {
alignas(16) const __m128i value = _mm_set_epi32(in[where+0], in[where+1], in[where+2], in[where+3]);
const __m128 convert = convertToFloatSSE2(value);
memcpy(&result[where], &convert, sizeof convert);
}
for (int i = 0; i < remainder; i++)
result[where+i] = convertToFloat(in[where+i]);
#else
for (size_t i = 0; i < length; i++)
result[i] = convertToFloat(in[i]);
#endif
return result;
}
}
<commit_msg>vectorShape not needed now either<commit_after>#include <string.h>
#if defined(__SSE2__)
#include <emmintrin.h>
#endif
#if defined(__SSE4_1__)
#include <smmintrin.h>
#endif
#include "m_half.h"
#include "m_const.h"
namespace m {
static struct halfData {
halfData();
// 1536 bytes
uint32_t baseTable[512];
uint8_t shiftTable[512];
} gHalf;
halfData::halfData() {
for (int i = 0, e = 0; i < 256; ++i) {
e = i - 127;
if (e < -24) {
// When magnitude of the number is really small (2^-24 or smaller),
// there is no possible half-float representation for the number, so
// it must be mapped to zero (or negative zero). Setting the shift
// table entries to 24 will shift all mantissa bits, leaving just zero.
// Base tables store zero otherwise (0x8000 for negative zero case.)
baseTable[i|0x000] = 0x0000;
baseTable[i|0x100] = 0x8000;
shiftTable[i|0x000] = 24;
shiftTable[i|0x100] = 24;
} else if (e < -14) {
// When the number is small (< 2^-14), the value can only be
// represented using a subnormal half-float. This is the most
// complex case: first, the leading 1-bit, implicitly represented
// in the normalized representation, must be explicitly added, then
// the resulting mantissa must be shifted rightward, or over a number
// of bit-positions as determined by the exponent. Here we prefer to
// shift the original mantissa bits, and add the pre-shifted 1-bit to
// it.
//
// Note: Shifting by -e-14 will never be negative, thus ensuring
// proper conversion, an alternative method is to shift by 18-e, which
// depends on implementation-defined behavior of unsigned shift.
baseTable[i|0x000] = (0x0400 >> (-e-14));
baseTable[i|0x100] = (0x0400 >> (-e-14)) | 0x8000;
shiftTable[i|0x000] = -e-1;
shiftTable[i|0x100] = -e-1;
} else if (e <= 15) {
// Normal numbers (smaller than 2^15), can be represented using half
// floats, albeit with slightly less precision. The entries in the
// base table are simply set to the bias-adjust exponent value, shifted
// into the right position. A sign bit is added for the negative case.
baseTable[i|0x000] = ((e+15) << 10);
baseTable[i|0x100] = ((e+15) << 10) | 0x8000;
shiftTable[i|0x000] = 13;
shiftTable[i|0x100] = 13;
} else if (e < 128) {
// Large values (numbers less than 2^128) must be mapped to half-float
// Infinity, They are too large to be represented as half-floats. In
// this case the base table is set to 0x7C00 (with sign if negative)
// and the mantissa is zeroed out, which is accomplished by shifting
// out all mantissa bits.
baseTable[i|0x000] = 0x7C00;
baseTable[i|0x100] = 0xFC00;
shiftTable[i|0x000] = 24;
shiftTable[i|0x100] = 24;
} else {
// Remaining float numbers such as Infs and NaNs should stay Infs and
// NaNs after conversion. The base table entries are exactly the same
// as the previous case, except the mantissa-bits are to be preserved
// as much as possible.
baseTable[i|0x000] = 0x7C00;
baseTable[i|0x100] = 0xFC00;
shiftTable[i|0x000] = 13;
shiftTable[i|0x100] = 13;
}
}
}
half convertToHalf(float in) {
const floatShape shape = { in };
return gHalf.baseTable[(shape.asInt >> 23) & 0x1FF] +
((shape.asInt & 0x007FFFFF) >> gHalf.shiftTable[(shape.asInt >> 23) & 0x1FF]);
}
float convertToFloat(half in) {
static constexpr uint32_t kMagic = 113 << 23;
static constexpr uint32_t kShiftedExp = 0x7C00 << 13; // exponent mask after shift
static constexpr floatShape kMagicShape = { kMagic };
floatShape out = { uint32_t(in & 0x7FFF) << 13 }; // exponent/mantissa bits
const size_t exp = kShiftedExp & out.asInt; // exponent
out.asInt += (127 - 15) << 23; // adjust exponent
if (exp == kShiftedExp) {
// extra adjustment of exponent for Inf/Nan?
out.asInt += (128 - 16) << 23;
} else if (exp == 0) {
// extra adjustment of exponent for Zero/Denormal?
out.asInt += 1 << 23;
// renormalize
out.asFloat -= kMagicShape.asFloat;
}
// sign bit
out.asInt |= (in & 0x8000) << 16;
return out.asFloat;
}
#if defined(__SSE2__)
template <unsigned int I>
static inline uint32_t extractScalar(__m128i v) {
#if defined(__SSE4_1__)
return _mm_extract_epi32(v, I);
#else
return _mm_cvtsi128_si32(_mm_shuffle_epi32(v, _MM_SHUFFLE(I,I,I,I)));
#endif
}
static __m128i convertToHalfSSE2(__m128 f) {
// ~15 SSE2 ops
alignas(16) static const uint32_t kMaskAbsolute[4] = { 0x7fffffffu, 0x7fffffffu, 0x7fffffffu, 0x7fffffffu };
alignas(16) static const uint32_t kInf32[4] = { 255 << 23, 255 << 23, 255 << 23, 255 << 23 };
alignas(16) static const uint32_t kExpInf[4] = { (255 ^ 31) << 23, (255 ^ 31) << 23, (255 ^ 31) << 23, (255 ^ 31) << 23 };
alignas(16) static const uint32_t kMax[4] = { (127 + 16) << 23, (127 + 16) << 23, (127 + 16) << 23, (127 + 16) << 23 };
alignas(16) static const uint32_t kMagic[4] = { 15 << 23, 15 << 23, 15 << 23, 15 << 23 };
const __m128 maskAbsolute = *(const __m128 *const)&kMaskAbsolute;
const __m128 absolute = _mm_and_ps(maskAbsolute, f);
const __m128 justSign = _mm_xor_ps(f, absolute);
const __m128 max = *(const __m128 *const)&kMax;
const __m128 expInf = *(const __m128 *const)&kExpInf;
const __m128 infNanCase = _mm_xor_ps(expInf, absolute);
const __m128 clamped = _mm_min_ps(max, absolute);
const __m128 notNormal = _mm_cmpnlt_ps(absolute, *(const __m128 *const)&kInf32);
const __m128 scaled = _mm_mul_ps(clamped, *(const __m128 *const)&kMagic);
const __m128 merge1 = _mm_and_ps(infNanCase, notNormal);
const __m128 merge2 = _mm_andnot_ps(notNormal, scaled);
const __m128 merged = _mm_or_ps(merge1, merge2);
const __m128i shifted = _mm_srli_epi32(_mm_castps_si128(merged), 13);
const __m128i signShifted = _mm_srli_epi32(_mm_castps_si128(justSign), 16);
const __m128i value = _mm_or_si128(shifted, signShifted);
return value;
}
static __m128 convertToFloatSSE2(__m128i h) {
// ~19 SSE2 ops
alignas(16) static const uint32_t kMaskNoSign[4] = { 0x7fff, 0x7fff, 0x7fff, 0x7fff };
alignas(16) static const uint32_t kSmallestNormal[4] = { 0x0400, 0x0400, 0x0400, 0x0400 };
alignas(16) static const uint32_t kInfinity[4] = { 0x7c00, 0x7c00, 0x7c00, 0x7c00 };
alignas(16) static const uint32_t kExpAdjustNormal[4] = { (127 - 15) << 23, (127 - 15) << 23, (127 - 15) << 23, (127 - 15) << 23, };
alignas(16) static const uint32_t kMagicDenormal[4] = { 113 << 23, 113 << 23, 113 << 23, 113 << 23 };
const __m128i noSign = *(const __m128i *const)&kMaskNoSign;
const __m128i exponentAdjust = *(const __m128i *const)&kExpAdjustNormal;
const __m128i smallest = *(const __m128i *const)&kSmallestNormal;
const __m128i infinity = *(const __m128i *const)&kInfinity;
const __m128i expAnd = _mm_and_si128(noSign, h);
const __m128i justSign = _mm_xor_si128(h, expAnd);
const __m128i notInfNan = _mm_cmpgt_epi32(infinity, expAnd);
const __m128i isDenormal = _mm_cmpgt_epi32(smallest, expAnd);
const __m128i shifted = _mm_slli_epi32(expAnd, 13);
const __m128i adjustInfNan = _mm_andnot_si128(notInfNan, exponentAdjust);
const __m128i adjusted = _mm_add_epi32(exponentAdjust, shifted);
const __m128i denormal1 = _mm_add_epi32(shifted, *(const __m128i *const)&kMagicDenormal);
const __m128i adjusted2 = _mm_add_epi32(adjusted, adjustInfNan);
const __m128 denormal2 = _mm_sub_ps(_mm_castsi128_ps(denormal1), *(const __m128 *const)&kMagicDenormal);
const __m128 adjusted3 = _mm_and_ps(denormal2, _mm_castsi128_ps(isDenormal));
const __m128 adjusted4 = _mm_andnot_ps(_mm_castsi128_ps(isDenormal), _mm_castsi128_ps(adjusted2));
const __m128 adjusted5 = _mm_or_ps(adjusted3, adjusted4);
const __m128i sign = _mm_slli_epi32(justSign, 16);
const __m128 value = _mm_or_ps(adjusted5, _mm_castsi128_ps(sign));
return value;
}
#endif
u::vector<half> convertToHalf(const float *const input, size_t length) {
u::vector<half> result(length);
const float *in = input;
U_ASSERT(((uintptr_t)(const void *)in) % 16 == 0);
U_ASSUME_ALIGNED(in, 16);
#if defined(__SSE2__)
const int blocks = int(length) / 4;
const int remainder = int(length) % 4;
int where = 0;
for (int i = 0; i < blocks; i++) {
const __m128 value = _mm_load_ps(&in[where]);
const __m128i convert = convertToHalfSSE2(value);
result[where++] = extractScalar<0>(convert);
result[where++] = extractScalar<1>(convert);
result[where++] = extractScalar<2>(convert);
result[where++] = extractScalar<3>(convert);
}
for (int i = 0; i < remainder; i++)
result[where+i] = convertToHalf(in[where+i]);
#else
for (size_t i = 0; i < length; i++)
result[i] = convertToHalf(in[i]);
#endif
return result;
}
u::vector<float> convertToFloat(const half *const input, size_t length) {
u::vector<float> result(length);
#if defined(__SSE2__)
const half *in = input;
U_ASSUME_ALIGNED(in, 16);
const int blocks = int(length) / 4;
const int remainder = int(length) % 4;
int where = 0;
for (int i = 0; i < blocks; i++, where += 4) {
alignas(16) const __m128i value = _mm_set_epi32(in[where+0], in[where+1], in[where+2], in[where+3]);
const __m128 convert = convertToFloatSSE2(value);
memcpy(&result[where], &convert, sizeof convert);
}
for (int i = 0; i < remainder; i++)
result[where+i] = convertToFloat(in[where+i]);
#else
for (size_t i = 0; i < length; i++)
result[i] = convertToFloat(in[i]);
#endif
return result;
}
}
<|endoftext|>
|
<commit_before>#pragma once
#include <rapidjson/rapidjson.h>
#include <common/SignalVector.hpp>
#include "providers/irc/IrcChannel2.hpp"
#include "providers/irc/IrcServer.hpp"
class QAbstractTableModel;
namespace chatterino {
enum class IrcAuthType { Anonymous, Custom, Pass };
struct IrcServerData {
QString host;
int port = 6667;
bool ssl = false;
QString user;
QString nick;
QString real;
IrcAuthType authType = IrcAuthType::Anonymous;
void getPassword(QObject *receiver,
std::function<void(const QString &)> &&onLoaded) const;
void setPassword(const QString &password);
QStringList connectCommands;
int id;
};
class Irc
{
public:
Irc();
static Irc &getInstance();
static inline void *const noEraseCredentialCaller =
reinterpret_cast<void *>(1);
UnsortedSignalVector<IrcServerData> connections;
QAbstractTableModel *newConnectionModel(QObject *parent);
ChannelPtr getOrAddChannel(int serverId, QString name);
void save();
void load();
int uniqueId();
private:
int currentId_{};
bool loaded_{};
// Servers have a unique id.
// When a server gets changed it gets removed and then added again.
// So we store the channels of that server in abandonedChannels_ temporarily.
// Or if the server got removed permanently then it's still stored there.
std::unordered_map<int, std::unique_ptr<IrcServer>> servers_;
std::unordered_map<int, std::vector<std::weak_ptr<Channel>>>
abandonedChannels_;
};
} // namespace chatterino
<commit_msg>irc default now uses ssl<commit_after>#pragma once
#include <rapidjson/rapidjson.h>
#include <common/SignalVector.hpp>
#include "providers/irc/IrcChannel2.hpp"
#include "providers/irc/IrcServer.hpp"
class QAbstractTableModel;
namespace chatterino {
enum class IrcAuthType { Anonymous, Custom, Pass };
struct IrcServerData {
QString host;
int port = 6697;
bool ssl = true;
QString user;
QString nick;
QString real;
IrcAuthType authType = IrcAuthType::Anonymous;
void getPassword(QObject *receiver,
std::function<void(const QString &)> &&onLoaded) const;
void setPassword(const QString &password);
QStringList connectCommands;
int id;
};
class Irc
{
public:
Irc();
static Irc &getInstance();
static inline void *const noEraseCredentialCaller =
reinterpret_cast<void *>(1);
UnsortedSignalVector<IrcServerData> connections;
QAbstractTableModel *newConnectionModel(QObject *parent);
ChannelPtr getOrAddChannel(int serverId, QString name);
void save();
void load();
int uniqueId();
private:
int currentId_{};
bool loaded_{};
// Servers have a unique id.
// When a server gets changed it gets removed and then added again.
// So we store the channels of that server in abandonedChannels_ temporarily.
// Or if the server got removed permanently then it's still stored there.
std::unordered_map<int, std::unique_ptr<IrcServer>> servers_;
std::unordered_map<int, std::vector<std::weak_ptr<Channel>>>
abandonedChannels_;
};
} // namespace chatterino
<|endoftext|>
|
<commit_before>#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
void init() __attribute__((constructor));
void fini() __attribute__((destructor));
static void panic(...) __attribute__((noreturn));
#ifdef DEBUG
#define debug printf
#define assert xassert
#define xassert(e) if (e); else panic(#e)
#define IFDEBUG(X) X
#else
#define debug(...) (void)0
#define assert(...) (void)0
#define IFDEBUG(X) /* nothing */
#endif
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
/**
* These are adapted to be stored internally in whatever data we have.
*/
struct pairing_ptr_heap
{
typedef pairing_ptr_heap T;
typedef pairing_ptr_heap* Tp;
/**
* down,right: first child and right sibling of this page in pairing heap
* of pages with free space.
*/
pairing_ptr_heap* down;
pairing_ptr_heap* right;
Tp delete_min()
{
assert(!right);
Tp l = down;
down = NULL;
return mergePairs(l);
}
static Tp mergePairs(Tp l)
{
if (!l || !l->right) return l;
Tp r = l->right;
Tp hs = r->right;
l->right = r->right = NULL;
assert(hs != l && hs != r && r != l);
// FIXME recursion...
// We can use l->right after merge returns, since merge() always
// returns something with a right-value of NULL. l will never be
// touched until we're about to merge it with the result of mergePairs
l = merge(l,r);
hs = mergePairs(hs);
return merge(l,hs);
}
static Tp merge(Tp l, Tp r)
{
if (!l)
{
assert(!r->right);
return r;
}
if (!r)
{
assert(!l->right);
return l;
}
assert(!l->right && !r->right);
if (r < l)
{
Tp tmp = r;
r = l;
l = tmp;
}
// l <= r!
r->right = l->down;
l->down = r;
//l->right = NULL; // we know it's already null
return l;
}
};
pairing_ptr_heap* delete_min(pairing_ptr_heap* p)
{
assert(p);
return p->delete_min();
}
pairing_ptr_heap* insert(pairing_ptr_heap* l, pairing_ptr_heap* r)
{
return pairing_ptr_heap::merge(l, r);
}
struct pageinfo
{
/**
* Pointer to where the page starts.
* TODO: Pack some stuff in here. *Twelve* vacant bits!
*/
void* page;
uint16_t size;
//uint16_t isize;
uint16_t chunks;
uint16_t chunks_free;
uint8_t index; // index into array of pages
/**
* The heap of address-sorted pages in this category that have free pages
*/
pairing_ptr_heap heap;
/**
* 1-32 bytes of bitmap data. A set bit means *free* chunk.
*/
uint8_t bitmap[];
// TODO merge bitmap into page?
};
#define pageinfo_from_heap(heap_) \
((pageinfo*)((char*)(heap_) - offsetof(pageinfo, heap)))
bool page_filled(pageinfo* page)
{
return !page->chunks_free;
}
void* page_get_chunk(pageinfo* page)
{
page->chunks_free--;
uint8_t* bitmap = page->bitmap;
for (size_t i = 0; i < page->chunks / 8; i++)
{
const uint8_t found = bitmap[i];
if (found)
{
uint8_t mask = 0x80;
size_t n = i << 3;
while (mask)
{
if (mask & found)
{
bitmap[i] = found & ~mask;
return (uint8_t*)page->page + (n * page->size);
}
mask >>= 1;
n++;
}
}
}
panic("No free chunks found?");
}
void page_free_chunk(pageinfo* page, void* ptr)
{
size_t ix = (uint8_t*)ptr - (uint8_t*)page->page;
ix /= page->size; // FIXME store inverse or something instead
page->bitmap[ix >> 3] |= 1 << (7 - (ix & 7));
page->chunks_free++;
}
#define N_SIZES (128/16+5)
#define PAGE_SHIFT 12
#define PAGE_SIZE (1 << PAGE_SHIFT)
static pairing_ptr_heap* g_free_pages;
static pageinfo* g_chunk_pages[N_SIZES];
static uintptr_t g_first_page;
static uintptr_t g_n_pages;
// Assumes mostly contiguous pages...
static pageinfo** g_pages;
void init()
{
g_first_page = (uintptr_t)sbrk(0);
}
void fini()
{
// TODO Unmap everything?
}
void panic(...)
{
abort();
}
size_t size_ix(size_t size)
{
if (size <= 128)
return (size + 15) / 16 - 1;
size_t ix = 8; // 256 bytes
size >>= 8;
while (size) { size >>= 1; ix++; }
return ix;
}
size_t ix_size(size_t ix)
{
return ix < 8 ? 16 * (ix + 1) : (1 << ix);
}
void* get_page()
{
if (void* ret = g_free_pages)
{
g_free_pages = delete_min(g_free_pages);
return ret;
}
else
{
uintptr_t cur = (uintptr_t)sbrk(0);
sbrk((PAGE_SIZE - cur) & (PAGE_SIZE - 1));
return sbrk(PAGE_SIZE);
}
}
void set_pageinfo(void* page, pageinfo* info)
{
uintptr_t offset;
if (g_pages)
{
offset = ((uintptr_t)page - g_first_page) >> PAGE_SHIFT;
}
else
{
g_first_page = (uintptr_t)page;
offset = 0;
}
if (offset >= g_n_pages)
{
size_t required = (offset + PAGE_SIZE) & ~(PAGE_SIZE-1);
pageinfo** new_pages = (pageinfo**)mmap(NULL, required, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
assert(new_pages != MAP_FAILED);
memcpy(new_pages, g_pages, g_n_pages * sizeof(pageinfo*));
munmap(g_pages, g_n_pages * sizeof(pageinfo*));
g_pages = new_pages;
g_n_pages = required / sizeof(pageinfo*);
}
g_pages[offset] = info;
}
pageinfo* new_chunkpage(size_t size)
{
size_t ix = size_ix(size);
size = ix_size(ix);
size_t nchunks = 4096/size;
pageinfo* ret = NULL;
size_t pisize = sizeof(pageinfo) + nchunks/8;
if (!g_chunk_pages[size_ix(pisize)])
{
ret = (pageinfo*)get_page();
set_pageinfo(ret, NULL);
}
else
{
ret = (pageinfo*)malloc(pisize);
}
memset(&ret->heap, 0, sizeof(ret->heap));
ret->page = get_page();
ret->size = size;
// ret->shift = ix_shift(ix);
ret->chunks = nchunks;
ret->chunks_free = nchunks;
ret->index = ix;
memset(ret->bitmap, 0xff, nchunks/8);
set_pageinfo(ret->page, ret);
return ret;
}
pageinfo* ptr_pageinfo(void* ptr)
{
uintptr_t offset = ((uintptr_t)ptr - g_first_page) >> PAGE_SHIFT;
if (offset > g_n_pages) return NULL;
pageinfo* ret = g_pages[offset];
assert(!ret || !(((uintptr_t)ret->page ^ (uintptr_t)ptr) >> PAGE_SHIFT));
return ret;
}
size_t get_alloc_size(void* ptr)
{
pageinfo* info = ptr_pageinfo(ptr);
if (!info) panic("get_alloc_size for unknown pointer %p", ptr);
return info->size;
}
void *malloc(size_t size)
{
if (!size) return NULL;
pageinfo** pagep = g_chunk_pages + size_ix(size);
pageinfo* page = *pagep;
if (unlikely(!page))
{
debug("Adding new chunk page for size %lu (cat %ld)\n", size, size_ix(size));
page = new_chunkpage(size);
*pagep = page;
}
debug("Allocating chunk from %p (info %p, %d left)\n", page->page, page, page->chunks_free);
void* ret = page_get_chunk(page);
if (unlikely(page_filled(page)))
{
debug("Page %p (info %p) filled\n", page->page, page);
pairing_ptr_heap* newpage = delete_min(&page->heap);
*pagep = newpage ? pageinfo_from_heap(newpage) : NULL;
}
return ret;
}
void* calloc(size_t n, size_t sz)
{
size_t size = n * sz;
void* ptr = malloc(size);
if (likely(ptr)) memset(ptr, 0, size);
return ptr;
}
void* realloc(void* ptr, size_t new_size)
{
size_t old_size = get_alloc_size(ptr);
void* ret = malloc(new_size);
if (likely(ret))
{
memcpy(ret, ptr, unlikely(new_size < old_size) ? new_size : old_size);
}
return ret;
}
void free(void *ptr)
{
if (unlikely(!ptr)) return;
pageinfo* page = ptr_pageinfo(ptr);
if (unlikely(!page)) panic("free on unknown pointer %p", ptr);
bool was_filled = page_filled(page);
page_free_chunk(page, ptr);
if (was_filled)
{
pageinfo** pagep = g_chunk_pages + page->index;
pageinfo* free_page = *pagep;
if (!free_page)
*pagep = page;
else
*pagep = pageinfo_from_heap(insert(&free_page->heap, &page->heap));
}
else if (unlikely(page->chunks_free == page->chunks))
{
debug("Free: page %p (info %p) is now free\n", page->page, page);
}
}
#ifdef TEST
int32_t xrand()
{
static int32_t m_w = 1246987127, m_z = 789456123;
m_z = 36969 * (m_z & 65535) + (m_z >> 16);
m_w = 18000 * (m_w & 65535) + (m_w >> 16);
return (m_z << 16) + m_w; /* 32-bit result */
}
const size_t DELAY = 10;
const size_t NTESTS = 100000;
const size_t MAXALLOC = 512;
int main()
{
void* ptrs[DELAY] = {0};
for (size_t i = 0; i < NTESTS; i++)
{
size_t size = i % MAXALLOC;
void** p = ptrs + (i % DELAY);
debug("free(%p)\n", *p);
free(*p);
debug("malloc(%lu)\n", (unsigned long)size);
*p = malloc(size);
debug("malloc(%lu): %p\n", (unsigned long)size, *p);
for (size_t j = 0; j < DELAY; j++)
{
assert(ptrs + j == p || !p[0] || ptrs[j] != p[0]);
}
}
}
#endif
<commit_msg>Add static to internal functions.<commit_after>#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
void init() __attribute__((constructor));
void fini() __attribute__((destructor));
static void panic(...) __attribute__((noreturn));
#ifdef DEBUG
#define debug printf
#define assert xassert
#define xassert(e) if (e); else panic(#e)
#define IFDEBUG(X) X
#else
#define debug(...) (void)0
#define assert(...) (void)0
#define IFDEBUG(X) /* nothing */
#endif
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
/**
* These are adapted to be stored internally in whatever data we have.
*/
struct pairing_ptr_heap
{
typedef pairing_ptr_heap T;
typedef pairing_ptr_heap* Tp;
/**
* down,right: first child and right sibling of this page in pairing heap
* of pages with free space.
*/
pairing_ptr_heap* down;
pairing_ptr_heap* right;
Tp delete_min()
{
assert(!right);
Tp l = down;
down = NULL;
return mergePairs(l);
}
static Tp mergePairs(Tp l)
{
if (!l || !l->right) return l;
Tp r = l->right;
Tp hs = r->right;
l->right = r->right = NULL;
assert(hs != l && hs != r && r != l);
// FIXME recursion...
// We can use l->right after merge returns, since merge() always
// returns something with a right-value of NULL. l will never be
// touched until we're about to merge it with the result of mergePairs
l = merge(l,r);
hs = mergePairs(hs);
return merge(l,hs);
}
static Tp merge(Tp l, Tp r)
{
if (!l)
{
assert(!r->right);
return r;
}
if (!r)
{
assert(!l->right);
return l;
}
assert(!l->right && !r->right);
if (r < l)
{
Tp tmp = r;
r = l;
l = tmp;
}
// l <= r!
r->right = l->down;
l->down = r;
//l->right = NULL; // we know it's already null
return l;
}
};
static pairing_ptr_heap* delete_min(pairing_ptr_heap* p)
{
assert(p);
return p->delete_min();
}
static pairing_ptr_heap* insert(pairing_ptr_heap* l, pairing_ptr_heap* r)
{
return pairing_ptr_heap::merge(l, r);
}
struct pageinfo
{
/**
* Pointer to where the page starts.
* TODO: Pack some stuff in here. *Twelve* vacant bits!
*/
void* page;
uint16_t size;
//uint16_t isize;
uint16_t chunks;
uint16_t chunks_free;
uint8_t index; // index into array of pages
/**
* The heap of address-sorted pages in this category that have free pages
*/
pairing_ptr_heap heap;
/**
* 1-32 bytes of bitmap data. A set bit means *free* chunk.
*/
uint8_t bitmap[];
// TODO merge bitmap into page?
};
#define pageinfo_from_heap(heap_) \
((pageinfo*)((char*)(heap_) - offsetof(pageinfo, heap)))
static bool page_filled(pageinfo* page)
{
return !page->chunks_free;
}
static void* page_get_chunk(pageinfo* page)
{
page->chunks_free--;
uint8_t* bitmap = page->bitmap;
for (size_t i = 0; i < page->chunks / 8; i++)
{
const uint8_t found = bitmap[i];
if (found)
{
uint8_t mask = 0x80;
size_t n = i << 3;
while (mask)
{
if (mask & found)
{
bitmap[i] = found & ~mask;
return (uint8_t*)page->page + (n * page->size);
}
mask >>= 1;
n++;
}
}
}
panic("No free chunks found?");
}
static void page_free_chunk(pageinfo* page, void* ptr)
{
size_t ix = (uint8_t*)ptr - (uint8_t*)page->page;
ix /= page->size; // FIXME store inverse or something instead
page->bitmap[ix >> 3] |= 1 << (7 - (ix & 7));
page->chunks_free++;
}
#define N_SIZES (128/16+5)
#define PAGE_SHIFT 12
#define PAGE_SIZE (1 << PAGE_SHIFT)
static pairing_ptr_heap* g_free_pages;
static pageinfo* g_chunk_pages[N_SIZES];
static uintptr_t g_first_page;
static uintptr_t g_n_pages;
// Assumes mostly contiguous pages...
static pageinfo** g_pages;
void init()
{
g_first_page = (uintptr_t)sbrk(0);
}
void fini()
{
// TODO Unmap everything?
}
static void panic(...)
{
abort();
}
static size_t size_ix(size_t size)
{
if (size <= 128)
return (size + 15) / 16 - 1;
size_t ix = 8; // 256 bytes
size >>= 8;
while (size) { size >>= 1; ix++; }
return ix;
}
static size_t ix_size(size_t ix)
{
return ix < 8 ? 16 * (ix + 1) : (1 << ix);
}
static void* get_page()
{
if (void* ret = g_free_pages)
{
g_free_pages = delete_min(g_free_pages);
return ret;
}
else
{
uintptr_t cur = (uintptr_t)sbrk(0);
sbrk((PAGE_SIZE - cur) & (PAGE_SIZE - 1));
return sbrk(PAGE_SIZE);
}
}
static void set_pageinfo(void* page, pageinfo* info)
{
uintptr_t offset;
if (g_pages)
{
offset = ((uintptr_t)page - g_first_page) >> PAGE_SHIFT;
}
else
{
g_first_page = (uintptr_t)page;
offset = 0;
}
if (offset >= g_n_pages)
{
size_t required = (offset + PAGE_SIZE) & ~(PAGE_SIZE-1);
pageinfo** new_pages = (pageinfo**)mmap(NULL, required, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
assert(new_pages != MAP_FAILED);
memcpy(new_pages, g_pages, g_n_pages * sizeof(pageinfo*));
munmap(g_pages, g_n_pages * sizeof(pageinfo*));
g_pages = new_pages;
g_n_pages = required / sizeof(pageinfo*);
}
g_pages[offset] = info;
}
static pageinfo* new_chunkpage(size_t size)
{
size_t ix = size_ix(size);
size = ix_size(ix);
size_t nchunks = 4096/size;
pageinfo* ret = NULL;
size_t pisize = sizeof(pageinfo) + nchunks/8;
if (!g_chunk_pages[size_ix(pisize)])
{
ret = (pageinfo*)get_page();
set_pageinfo(ret, NULL);
}
else
{
ret = (pageinfo*)malloc(pisize);
}
memset(&ret->heap, 0, sizeof(ret->heap));
ret->page = get_page();
ret->size = size;
// ret->shift = ix_shift(ix);
ret->chunks = nchunks;
ret->chunks_free = nchunks;
ret->index = ix;
memset(ret->bitmap, 0xff, nchunks/8);
set_pageinfo(ret->page, ret);
return ret;
}
static pageinfo* ptr_pageinfo(void* ptr)
{
uintptr_t offset = ((uintptr_t)ptr - g_first_page) >> PAGE_SHIFT;
if (offset > g_n_pages) return NULL;
pageinfo* ret = g_pages[offset];
assert(!ret || !(((uintptr_t)ret->page ^ (uintptr_t)ptr) >> PAGE_SHIFT));
return ret;
}
static size_t get_alloc_size(void* ptr)
{
pageinfo* info = ptr_pageinfo(ptr);
if (!info) panic("get_alloc_size for unknown pointer %p", ptr);
return info->size;
}
void *malloc(size_t size)
{
if (!size) return NULL;
pageinfo** pagep = g_chunk_pages + size_ix(size);
pageinfo* page = *pagep;
if (unlikely(!page))
{
debug("Adding new chunk page for size %lu (cat %ld)\n", size, size_ix(size));
page = new_chunkpage(size);
*pagep = page;
}
debug("Allocating chunk from %p (info %p, %d left)\n", page->page, page, page->chunks_free);
void* ret = page_get_chunk(page);
if (unlikely(page_filled(page)))
{
debug("Page %p (info %p) filled\n", page->page, page);
pairing_ptr_heap* newpage = delete_min(&page->heap);
*pagep = newpage ? pageinfo_from_heap(newpage) : NULL;
}
return ret;
}
void* calloc(size_t n, size_t sz)
{
size_t size = n * sz;
void* ptr = malloc(size);
if (likely(ptr)) memset(ptr, 0, size);
return ptr;
}
void* realloc(void* ptr, size_t new_size)
{
size_t old_size = get_alloc_size(ptr);
void* ret = malloc(new_size);
if (likely(ret))
{
memcpy(ret, ptr, unlikely(new_size < old_size) ? new_size : old_size);
}
return ret;
}
void free(void *ptr)
{
if (unlikely(!ptr)) return;
pageinfo* page = ptr_pageinfo(ptr);
if (unlikely(!page)) panic("free on unknown pointer %p", ptr);
bool was_filled = page_filled(page);
page_free_chunk(page, ptr);
if (was_filled)
{
pageinfo** pagep = g_chunk_pages + page->index;
pageinfo* free_page = *pagep;
if (!free_page)
*pagep = page;
else
*pagep = pageinfo_from_heap(insert(&free_page->heap, &page->heap));
}
else if (unlikely(page->chunks_free == page->chunks))
{
debug("Free: page %p (info %p) is now free\n", page->page, page);
}
}
#ifdef TEST
static int32_t xrand()
{
static int32_t m_w = 1246987127, m_z = 789456123;
m_z = 36969 * (m_z & 65535) + (m_z >> 16);
m_w = 18000 * (m_w & 65535) + (m_w >> 16);
return (m_z << 16) + m_w; /* 32-bit result */
}
const size_t DELAY = 10;
const size_t NTESTS = 100000;
const size_t MAXALLOC = 512;
int main()
{
void* ptrs[DELAY] = {0};
for (size_t i = 0; i < NTESTS; i++)
{
size_t size = i % MAXALLOC;
void** p = ptrs + (i % DELAY);
debug("free(%p)\n", *p);
free(*p);
debug("malloc(%lu)\n", (unsigned long)size);
*p = malloc(size);
debug("malloc(%lu): %p\n", (unsigned long)size, *p);
for (size_t j = 0; j < DELAY; j++)
{
assert(ptrs + j == p || !p[0] || ptrs[j] != p[0]);
}
}
}
#endif
<|endoftext|>
|
<commit_before>/* This file is part of QJson
*
* Copyright (C) 2009 Flavio Castelli <flavio.castelli@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <limits>
#include <QtTest/QtTest>
#include "parser.h"
#include "serializer.h"
#include <QtCore/QVariant>
class TestSerializer: public QObject
{
Q_OBJECT
private slots:
void testReadWriteEmptyDocument();
void testReadWrite();
void testReadWrite_data();
void testValueNull();
void testValueString();
void testValueString_data();
void testValueInteger();
void testValueInteger_data();
void testValueDouble();
void testValueDouble_data();
void testValueBoolean();
void testValueBoolean_data();
private:
void valueTest( const QVariant& value, const QString& expectedRegExp );
void valueTest( const QObject* object, const QString& expectedRegExp );
};
Q_DECLARE_METATYPE(QVariant)
using namespace QJson;
void TestSerializer::testReadWriteEmptyDocument()
{
QByteArray json = "";
Parser parser;
bool ok;
QVariant result = parser.parse( json, &ok );
QVERIFY(ok);
QVERIFY( ! result.isValid() );
Serializer serializer;
const QByteArray serialized = serializer.serialize( result );
QVERIFY( !serialized.isNull() );
QByteArray expected = "null";
QCOMPARE(expected, serialized);
}
void TestSerializer::testReadWrite()
{
QFETCH( QByteArray, json );
Parser parser;
bool ok;
QVariant result = parser.parse( json, &ok );
QVERIFY(ok);
Serializer serializer;
const QByteArray serialized = serializer.serialize( result );
QVariant writtenThenRead = parser.parse( serialized, &ok );
QVERIFY(ok);
QCOMPARE( result, writtenThenRead );
}
void TestSerializer::testReadWrite_data()
{
QTest::addColumn<QByteArray>( "json" );
// array tests
QTest::newRow( "empty array" ) << QByteArray("[]");
QTest::newRow( "basic array" ) << QByteArray("[\"person\",\"bar\"]");
QTest::newRow( "single int array" ) << QByteArray("[6]");
QTest::newRow( "int array" ) << QByteArray("[6,5,6,7]");
const QByteArray json = "[1,2.4, -100, -3.4, -5e+, 2e,3e+,4.3E,5.4E-]";
QTest::newRow( QByteArray("array of various numbers") ) << json;
// document tests
QTest::newRow( "empty object" ) << QByteArray("{}");
QTest::newRow( "basic document" ) << QByteArray("{\"person\":\"bar\"}");
QTest::newRow( "object with ints" ) << QByteArray("{\"person\":6}");
const QByteArray json2 = "{ \"person\":\"bar\",\n\"number\" : 51.3 , \"array\":[\"item1\", 123]}";
QTest::newRow( "complicated document" ) << json2;
// more complex cases
const QByteArray json3 = "[ {\"person\":\"bar\"},\n\"number\",51.3 , [\"item1\", 123]]";
QTest::newRow( "complicated array" ) << json3;
}
void TestSerializer::valueTest( const QVariant& value, const QString& expectedRegExp )
{
Serializer serializer;
const QByteArray serialized = serializer.serialize( value );
const QString serializedUnicode = QString::fromUtf8( serialized );
QRegExp expected( expectedRegExp );
QVERIFY( expected.isValid() );
QVERIFY2( expected.exactMatch( serializedUnicode ),
qPrintable( QString( QLatin1String( "Expected regexp \"%1\" but got \"%2\"." ) )
.arg( expectedRegExp ).arg( serializedUnicode ) ) );
}
void TestSerializer::valueTest( const QObject* object, const QString& expectedRegExp )
{
Serializer serializer;
const QByteArray serialized = serializer.serialize( object );
const QString serializedUnicode = QString::fromUtf8( serialized );
QRegExp expected( expectedRegExp );
QVERIFY( expected.isValid() );
QVERIFY2( expected.exactMatch( serializedUnicode ),
qPrintable( QString( QLatin1String( "Expected regexp \"%1\" but got \"%2\"." ) )
.arg( expectedRegExp ).arg( serializedUnicode ) ) );
}
void TestSerializer::testValueNull()
{
valueTest( QVariant(), QLatin1String( "\\s*null\\s*" ) );
QVariantMap map;
map[QLatin1String("value")] = QVariant();
valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:\\s*null\\s*\\}\\s*" ) );
}
void TestSerializer::testValueString()
{
QFETCH( QVariant, value );
QFETCH( QString, expected );
valueTest( value, expected );
QVariantMap map;
map[QLatin1String("value")] = value;
valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ) );
}
void TestSerializer::testValueString_data()
{
QTest::addColumn<QVariant>( "value" );
QTest::addColumn<QString>( "expected" );
QTest::newRow( "null string" ) << QVariant( QString() ) << QString( QLatin1String( "\\s*\"\"\\s*" ) );
QTest::newRow( "empty string" ) << QVariant( QString( QLatin1String( "" ) ) ) << QString( QLatin1String( "\\s*\"\"\\s*" ) );
QTest::newRow( "Simple String" ) << QVariant( QString( QLatin1String( "simpleString" ) ) ) << QString( QLatin1String( "\\s*\"simpleString\"\\s*" ) );
QTest::newRow( "string with tab" ) << QVariant( QString( QLatin1String( "string\tstring" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\tstring\"\\s*" ) );
QTest::newRow( "string with newline" ) << QVariant( QString( QLatin1String( "string\nstring" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\nstring\"\\s*" ) );
QTest::newRow( "string with bell" ) << QVariant( QString( QLatin1String( "string\bstring" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\bstring\"\\s*" ) );
QTest::newRow( "string with return" ) << QVariant( QString( QLatin1String( "string\rstring" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\rstring\"\\s*" ) );
QTest::newRow( "string with double quote" ) << QVariant( QString( QLatin1String( "string\"string" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\\"string\"\\s*" ) );
QTest::newRow( "string with backslash" ) << QVariant( QString( QLatin1String( "string\\string" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\\\\\string\"\\s*" ) );
QString testStringWithUnicode = QString( QLatin1String( "string" ) ) + QChar( 0x2665 ) + QLatin1String( "string" );
QTest::newRow( "string with unicode" ) << QVariant( testStringWithUnicode ) << QLatin1String( "\\s*\"" ) + testStringWithUnicode + QLatin1String( "\"\\s*" );
}
void TestSerializer::testValueInteger()
{
QFETCH( QVariant, value );
QFETCH( QString, expected );
valueTest( value, expected );
QVariantMap map;
map[QLatin1String("value")] = value;
valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ) );
}
void TestSerializer::testValueInteger_data()
{
QTest::addColumn<QVariant>( "value" );
QTest::addColumn<QString>( "expected" );
QTest::newRow( "int 0" ) << QVariant( static_cast<int>( 0 ) ) << QString( QLatin1String( "\\s*0\\s*" ) );
QTest::newRow( "uint 0" ) << QVariant( static_cast<uint>( 0 ) ) << QString( QLatin1String( "\\s*0\\s*" ) );
QTest::newRow( "int -1" ) << QVariant( static_cast<int>( -1 ) ) << QString( QLatin1String( "\\s*-1\\s*" ) );
QTest::newRow( "int 2133149800" ) << QVariant( static_cast<int>(2133149800) ) << QString( QLatin1String( "\\s*2133149800\\s*" ) );
QTest::newRow( "uint 4133149800" ) << QVariant( static_cast<uint>(4133149800u) ) << QString( QLatin1String( "\\s*4133149800\\s*" ) );
QTest::newRow( "uint64 932838457459459" ) << QVariant( Q_UINT64_C(932838457459459) ) << QString( QLatin1String( "\\s*932838457459459\\s*" ) );
QTest::newRow( "max unsigned long long" ) << QVariant( std::numeric_limits<unsigned long long>::max() ) << QString( QLatin1String( "\\s*%1\\s*" ) ).arg(std::numeric_limits<unsigned long long>::max());
}
void TestSerializer::testValueDouble()
{
QFETCH( QVariant, value );
QFETCH( QString, expected );
valueTest( value, expected );
QVariantMap map;
map[QLatin1String("value")] = value;
valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ) );
}
void TestSerializer::testValueDouble_data()
{
QTest::addColumn<QVariant>( "value" );
QTest::addColumn<QString>( "expected" );
QTest::newRow( "double 0" ) << QVariant( 0.0 ) << QString( QLatin1String( "\\s*0.0\\s*" ) );
QTest::newRow( "double -1" ) << QVariant( -1.0 ) << QString( QLatin1String( "\\s*-1.0\\s*" ) );
QTest::newRow( "double 1.5E-20" ) << QVariant( 1.5e-20 ) << QString( QLatin1String( "\\s*1.5[Ee]-20\\s*" ) );
QTest::newRow( "double -1.5E-20" ) << QVariant( -1.5e-20 ) << QString( QLatin1String( "\\s*-1.5[Ee]-20\\s*" ) );
QTest::newRow( "double 2.0E-20" ) << QVariant( 2.0e-20 ) << QString( QLatin1String( "\\s*2(?:.0)?[Ee]-20\\s*" ) );
}
void TestSerializer::testValueBoolean()
{
QFETCH( QVariant, value );
QFETCH( QString, expected );
valueTest( value, expected );
QVariantMap map;
map[QLatin1String("value")] = value;
valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ) );
}
void TestSerializer::testValueBoolean_data()
{
QTest::addColumn<QVariant>( "value" );
QTest::addColumn<QString>( "expected" );
QTest::newRow( "bool false" ) << QVariant( false ) << QString( QLatin1String( "\\s*false\\s*" ) );
QTest::newRow( "bool true" ) << QVariant( true ) << QString( QLatin1String( "\\s*true\\s*" ) );
}
QTEST_MAIN(TestSerializer)
#include "moc_testserializer.cxx"
<commit_msg>updated serializer's unit tests<commit_after>/* This file is part of QJson
*
* Copyright (C) 2009 Flavio Castelli <flavio.castelli@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <limits>
#include <QtTest/QtTest>
#include "parser.h"
#include "serializer.h"
#include <QtCore/QVariant>
class TestSerializer: public QObject
{
Q_OBJECT
private slots:
void testReadWriteEmptyDocument();
void testReadWrite();
void testReadWrite_data();
void testValueNull();
void testValueString();
void testValueString_data();
void testValueInteger();
void testValueInteger_data();
void testValueDouble();
void testValueDouble_data();
void testValueBoolean();
void testValueBoolean_data();
private:
void valueTest( const QVariant& value, const QString& expectedRegExp );
void valueTest( const QObject* object, const QString& expectedRegExp );
};
Q_DECLARE_METATYPE(QVariant)
using namespace QJson;
void TestSerializer::testReadWriteEmptyDocument()
{
QByteArray json = "";
Parser parser;
bool ok;
QVariant result = parser.parse( json, &ok );
QVERIFY(ok);
QVERIFY( ! result.isValid() );
Serializer serializer;
const QByteArray serialized = serializer.serialize( result );
QVERIFY( !serialized.isNull() );
QByteArray expected = "null";
QCOMPARE(expected, serialized);
}
void TestSerializer::testReadWrite()
{
QFETCH( QByteArray, json );
Parser parser;
bool ok;
QVariant result = parser.parse( json, &ok );
QVERIFY(ok);
Serializer serializer;
const QByteArray serialized = serializer.serialize( result );
QVariant writtenThenRead = parser.parse( serialized, &ok );
QVERIFY(ok);
QCOMPARE( result, writtenThenRead );
}
void TestSerializer::testReadWrite_data()
{
QTest::addColumn<QByteArray>( "json" );
// array tests
QTest::newRow( "empty array" ) << QByteArray("[]");
QTest::newRow( "basic array" ) << QByteArray("[\"person\",\"bar\"]");
QTest::newRow( "single int array" ) << QByteArray("[6]");
QTest::newRow( "int array" ) << QByteArray("[6,5,6,7]");
const QByteArray json = "[1,2.4, -100, -3.4, -5e+, 2e,3e+,4.3E,5.4E-]";
QTest::newRow( QByteArray("array of various numbers") ) << json;
// document tests
QTest::newRow( "empty object" ) << QByteArray("{}");
QTest::newRow( "basic document" ) << QByteArray("{\"person\":\"bar\"}");
QTest::newRow( "object with ints" ) << QByteArray("{\"person\":6}");
const QByteArray json2 = "{ \"person\":\"bar\",\n\"number\" : 51.3 , \"array\":[\"item1\", 123]}";
QTest::newRow( "complicated document" ) << json2;
// more complex cases
const QByteArray json3 = "[ {\"person\":\"bar\"},\n\"number\",51.3 , [\"item1\", 123]]";
QTest::newRow( "complicated array" ) << json3;
}
void TestSerializer::valueTest( const QVariant& value, const QString& expectedRegExp )
{
Serializer serializer;
const QByteArray serialized = serializer.serialize( value );
const QString serializedUnicode = QString::fromUtf8( serialized );
QRegExp expected( expectedRegExp );
QVERIFY( expected.isValid() );
QVERIFY2( expected.exactMatch( serializedUnicode ),
qPrintable( QString( QLatin1String( "Expected regexp \"%1\" but got \"%2\"." ) )
.arg( expectedRegExp ).arg( serializedUnicode ) ) );
}
void TestSerializer::valueTest( const QObject* object, const QString& expectedRegExp )
{
Serializer serializer;
const QByteArray serialized = serializer.serialize( object );
const QString serializedUnicode = QString::fromUtf8( serialized );
QRegExp expected( expectedRegExp );
QVERIFY( expected.isValid() );
QVERIFY2( expected.exactMatch( serializedUnicode ),
qPrintable( QString( QLatin1String( "Expected regexp \"%1\" but got \"%2\"." ) )
.arg( expectedRegExp ).arg( serializedUnicode ) ) );
}
void TestSerializer::testValueNull()
{
valueTest( QVariant(), QLatin1String( "\\s*null\\s*" ) );
QVariantMap map;
map[QLatin1String("value")] = QVariant();
valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:\\s*null\\s*\\}\\s*" ) );
}
void TestSerializer::testValueString()
{
QFETCH( QVariant, value );
QFETCH( QString, expected );
valueTest( value, expected );
QVariantMap map;
map[QLatin1String("value")] = value;
valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ) );
}
void TestSerializer::testValueString_data()
{
QTest::addColumn<QVariant>( "value" );
QTest::addColumn<QString>( "expected" );
// QTest::newRow( "null string" ) << QVariant( QString() ) << QString( QLatin1String( "\\s*\"\"\\s*" ) );
// QTest::newRow( "empty string" ) << QVariant( QString( QLatin1String( "" ) ) ) << QString( QLatin1String( "\\s*\"\"\\s*" ) );
// QTest::newRow( "Simple String" ) << QVariant( QString( QLatin1String( "simpleString" ) ) ) << QString( QLatin1String( "\\s*\"simpleString\"\\s*" ) );
// QTest::newRow( "string with tab" ) << QVariant( QString( QLatin1String( "string\tstring" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\tstring\"\\s*" ) );
// QTest::newRow( "string with newline" ) << QVariant( QString( QLatin1String( "string\nstring" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\nstring\"\\s*" ) );
// QTest::newRow( "string with bell" ) << QVariant( QString( QLatin1String( "string\bstring" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\bstring\"\\s*" ) );
// QTest::newRow( "string with return" ) << QVariant( QString( QLatin1String( "string\rstring" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\rstring\"\\s*" ) );
// QTest::newRow( "string with double quote" ) << QVariant( QString( QLatin1String( "string\"string" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\\"string\"\\s*" ) );
// QTest::newRow( "string with backslash" ) << QVariant( QString( QLatin1String( "string\\string" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\\\\\string\"\\s*" ) );
QString testStringWithUnicode = QString( QLatin1String( "string" ) ) + QChar( 0x2665 ) + QLatin1String( "string" );
QString testEscapedString = QString( QLatin1String( "string" ) ) + QLatin1String("\\\\u2665") + QLatin1String( "string" );
QTest::newRow( "string with unicode" ) << QVariant( testStringWithUnicode ) << QLatin1String( "\\s*\"" ) + testEscapedString + QLatin1String( "\"\\s*" );
}
void TestSerializer::testValueInteger()
{
QFETCH( QVariant, value );
QFETCH( QString, expected );
valueTest( value, expected );
QVariantMap map;
map[QLatin1String("value")] = value;
valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ) );
}
void TestSerializer::testValueInteger_data()
{
QTest::addColumn<QVariant>( "value" );
QTest::addColumn<QString>( "expected" );
QTest::newRow( "int 0" ) << QVariant( static_cast<int>( 0 ) ) << QString( QLatin1String( "\\s*0\\s*" ) );
QTest::newRow( "uint 0" ) << QVariant( static_cast<uint>( 0 ) ) << QString( QLatin1String( "\\s*0\\s*" ) );
QTest::newRow( "int -1" ) << QVariant( static_cast<int>( -1 ) ) << QString( QLatin1String( "\\s*-1\\s*" ) );
QTest::newRow( "int 2133149800" ) << QVariant( static_cast<int>(2133149800) ) << QString( QLatin1String( "\\s*2133149800\\s*" ) );
QTest::newRow( "uint 4133149800" ) << QVariant( static_cast<uint>(4133149800u) ) << QString( QLatin1String( "\\s*4133149800\\s*" ) );
QTest::newRow( "uint64 932838457459459" ) << QVariant( Q_UINT64_C(932838457459459) ) << QString( QLatin1String( "\\s*932838457459459\\s*" ) );
QTest::newRow( "max unsigned long long" ) << QVariant( std::numeric_limits<unsigned long long>::max() ) << QString( QLatin1String( "\\s*%1\\s*" ) ).arg(std::numeric_limits<unsigned long long>::max());
}
void TestSerializer::testValueDouble()
{
QFETCH( QVariant, value );
QFETCH( QString, expected );
valueTest( value, expected );
QVariantMap map;
map[QLatin1String("value")] = value;
valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ) );
}
void TestSerializer::testValueDouble_data()
{
QTest::addColumn<QVariant>( "value" );
QTest::addColumn<QString>( "expected" );
QTest::newRow( "double 0" ) << QVariant( 0.0 ) << QString( QLatin1String( "\\s*0.0\\s*" ) );
QTest::newRow( "double -1" ) << QVariant( -1.0 ) << QString( QLatin1String( "\\s*-1.0\\s*" ) );
QTest::newRow( "double 1.5E-20" ) << QVariant( 1.5e-20 ) << QString( QLatin1String( "\\s*1.5[Ee]-20\\s*" ) );
QTest::newRow( "double -1.5E-20" ) << QVariant( -1.5e-20 ) << QString( QLatin1String( "\\s*-1.5[Ee]-20\\s*" ) );
QTest::newRow( "double 2.0E-20" ) << QVariant( 2.0e-20 ) << QString( QLatin1String( "\\s*2(?:.0)?[Ee]-20\\s*" ) );
}
void TestSerializer::testValueBoolean()
{
QFETCH( QVariant, value );
QFETCH( QString, expected );
valueTest( value, expected );
QVariantMap map;
map[QLatin1String("value")] = value;
valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ) );
}
void TestSerializer::testValueBoolean_data()
{
QTest::addColumn<QVariant>( "value" );
QTest::addColumn<QString>( "expected" );
QTest::newRow( "bool false" ) << QVariant( false ) << QString( QLatin1String( "\\s*false\\s*" ) );
QTest::newRow( "bool true" ) << QVariant( true ) << QString( QLatin1String( "\\s*true\\s*" ) );
}
QTEST_MAIN(TestSerializer)
#include "moc_testserializer.cxx"
<|endoftext|>
|
<commit_before>#include "rethink_db.hpp"
namespace com {
namespace rethinkdb {
connection::connection(const std::string& host, const std::string& port, const std::string& database, const std::string& auth_key) : resolver_(io_service), socket_(io_service) {
this->host = host;
this->port = port;
this->database = database;
this->auth_key = auth_key;
this->is_connected = false;
}
void connection::connect() {
try {
boost::asio::ip::tcp::resolver::query query(this->host, this->port);
boost::asio::ip::tcp::resolver::iterator iterator = resolver_.resolve(query);
boost::asio::connect(socket_, iterator);
std::ostream request_stream(&request_);
// send magic version number
request_stream.write((char*)&(com::rethinkdb::VersionDummy::V0_2), sizeof (com::rethinkdb::VersionDummy::V0_2));
// send auth_key length
u_int auth_key_length = auth_key.length();
request_stream.write((char*)&auth_key_length, sizeof (u_int));
// send auth_key
request_stream.write(auth_key.c_str(), auth_key.length());
boost::asio::write(socket_, request_);
boost::asio::read_until(socket_, response_, 0);
std::istream response_stream(&response_);
std::string response;
std::getline(response_stream, response);
if (response.substr(0, 7) == "SUCCESS") {
std::cout << "Successfully connected." << std::endl;
std::cout << "Response: '" << response << "'\n";
this->is_connected = true;
}
else {
this->is_connected = false;
std::cout << "Error in handle_read_connect_response: '" << response << "'\n";
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
}
void connection::create_db(std::string db_name) {
com::rethinkdb::Query q = com::rethinkdb::Query();
q.set_type(com::rethinkdb::Query::QueryType::Query_QueryType_START);
q.set_token(1);
com::rethinkdb::Term *t;
t = q.mutable_query();
t->set_type(com::rethinkdb::Term::TermType::Term_TermType_DB_CREATE);
com::rethinkdb::Term *t_name;
t_name = t->add_args();
t_name->set_type(com::rethinkdb::Term::TermType::Term_TermType_DATUM);
com::rethinkdb::Datum *datum;
datum = t_name->mutable_datum();
datum->set_type(com::rethinkdb::Datum::DatumType::Datum_DatumType_R_STR);
datum->set_r_str(db_name);
std::ostream request_stream(&request_);
std::string blob = q.SerializeAsString();
u_int blob_length = blob.length();
request_stream.write((char*)&blob_length, sizeof (u_int));
request_stream.write(blob.c_str(), blob.length());
try {
boost::asio::write(socket_, request_);
//
// read response
//
// read response length
u_int response_length;
size_t read_length = boost::asio::read(socket_,
boost::asio::buffer(&response_length, sizeof(u_int)));
// read protobuf
std::cout << "read_length: " << response_length << std::endl;
//read_length = 37;
char* reply = new char[response_length];
size_t reply_length = boost::asio::read(socket_,
boost::asio::buffer(reply, response_length));
std::cout << "reply_length: " << reply_length << std::endl;
com::rethinkdb::Response response = com::rethinkdb::Response();
response.ParseFromArray(reply, response_length);
delete[] reply;
response.PrintDebugString();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
}
}
}<commit_msg>Addition of exceptions.<commit_after>#include "rethink_db.hpp"
#include <exception>
namespace com {
namespace rethinkdb {
//
// definitions of exceptions
//
class connection_exception : public std::exception
{
virtual const char* what() const throw()
{
return "RethinkDB connection exception occurred.";
}
} connection_ex;
class runtime_exception : public std::exception
{
virtual const char* what() const throw()
{
return "RethinkDB runtime exception occurred.";
}
} runtime_ex;
class compile_error_exception : public std::exception
{
virtual const char* what() const throw()
{
return "RethinkDB compile error exception occurred.";
}
} compile_ex;
class client_error_exception : public std::exception
{
virtual const char* what() const throw()
{
return "RethinkDB client error exception occurred.";
}
} client_ex;
//
// implementation of connection class
//
connection::connection(const std::string& host, const std::string& port, const std::string& database, const std::string& auth_key) : resolver_(io_service), socket_(io_service) {
this->host = host;
this->port = port;
this->database = database;
this->auth_key = auth_key;
this->is_connected = false;
}
void connection::connect() {
try {
boost::asio::ip::tcp::resolver::query query(this->host, this->port);
boost::asio::ip::tcp::resolver::iterator iterator = resolver_.resolve(query);
boost::asio::connect(socket_, iterator);
std::ostream request_stream(&request_);
// send magic version number
request_stream.write((char*)&(com::rethinkdb::VersionDummy::V0_2), sizeof (com::rethinkdb::VersionDummy::V0_2));
// send auth_key length
u_int auth_key_length = auth_key.length();
request_stream.write((char*)&auth_key_length, sizeof (u_int));
// send auth_key
request_stream.write(auth_key.c_str(), auth_key.length());
boost::asio::write(socket_, request_);
boost::asio::read_until(socket_, response_, 0);
std::istream response_stream(&response_);
std::string response;
std::getline(response_stream, response);
if (response.substr(0, 7) == "SUCCESS") {
std::cout << "Successfully connected." << std::endl;
std::cout << "Response: '" << response << "'\n";
this->is_connected = true;
}
else {
this->is_connected = false;
std::cout << "Error in handle_read_connect_response: '" << response << "'\n";
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
}
void connection::create_db(std::string db_name) {
com::rethinkdb::Query q = com::rethinkdb::Query();
q.set_type(com::rethinkdb::Query::QueryType::Query_QueryType_START);
q.set_token(1);
com::rethinkdb::Term *t;
t = q.mutable_query();
t->set_type(com::rethinkdb::Term::TermType::Term_TermType_DB_CREATE);
com::rethinkdb::Term *t_name;
t_name = t->add_args();
t_name->set_type(com::rethinkdb::Term::TermType::Term_TermType_DATUM);
com::rethinkdb::Datum *datum;
datum = t_name->mutable_datum();
datum->set_type(com::rethinkdb::Datum::DatumType::Datum_DatumType_R_STR);
datum->set_r_str(db_name);
std::ostream request_stream(&request_);
std::string blob = q.SerializeAsString();
u_int blob_length = blob.length();
request_stream.write((char*)&blob_length, sizeof (u_int));
request_stream.write(blob.c_str(), blob.length());
try {
boost::asio::write(socket_, request_);
//
// read response
//
// read response length
u_int response_length;
size_t read_length = boost::asio::read(socket_,
boost::asio::buffer(&response_length, sizeof(u_int)));
// read protobuf
std::cout << "read_length: " << response_length << std::endl;
//read_length = 37;
char* reply = new char[response_length];
size_t reply_length = boost::asio::read(socket_,
boost::asio::buffer(reply, response_length));
std::cout << "reply_length: " << reply_length << std::endl;
com::rethinkdb::Response response = com::rethinkdb::Response();
response.ParseFromArray(reply, response_length);
delete[] reply;
response.PrintDebugString();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
}
}
}<|endoftext|>
|
<commit_before>/*** Copyright (c), The Regents of the University of California ***
*** For more information please refer to files in the COPYRIGHT directory ***/
/* definitions for rodsLog routines */
#include "rodsError.hpp"
#define LOG_SQL 11
/* This is for logging SQL statements. These are only logged when
specifically requested and so are a high priority at this level. */
#define LOG_DEBUG1 10
#define LOG_DEBUG2 9
#define LOG_DEBUG3 8
#define LOG_DEBUG 7
/*
The DEBUG messages are for the software engineer to analyze and
debug operations. These are typically added during development and
debug of the code, but can be left in place for possible future
use. In many cases, one would be able start seeing these messages
via a command-line argument to adjust the rodsLog verbosity level.
*/
#define LOG_NOTICE 5
#define LOG_STATUS 5
/* This is informational only, part of the normal operation but will
often be of interest. */
#define LOG_ERROR 3
/* This means that the function cannot complete what it was asked to
do, probably because of bad input from the user (an invalid host
name, for example). */
#define LOG_SYS_WARNING 2
/* This means a system-level problem occurred that is not fatal to the
whole system (it can continue to run), but does indicate an internal
inconsistency of some kind. An example is a file with a physical
size that is different than that recorded in the database.
*/
#define LOG_SYS_FATAL 1
/* This is used of errors that mean that the system (not just one
server, client, or user) cannot continue. An example is when the
server is unable to talk to the database. */
extern "C" {
void rodsLog( int level, const char *formatStr, ... );
void rodsLogAndErrorMsg( int level, rError_t *myError, int status,
char *formatStr, ... );
void rodsLogLevel( int level );
void rodsLogSqlReq( int onOrOff );
void rodsLogSql( const char *sql );
void rodsLogSqlResult( char *stat );
char *rodsErrorName( int errorValue, char **subName );
void rodsLogErrorOld( int level, int errCode, char *textStr );
void rodsLogError( int level, int errCode, char *formatStr, ... );
int getRodsLogLevel();
void generateLogTimestamp( char *ts, int tsLen );
}
<commit_msg>[#717] Make rodsLogAndErrorMsg take a const string for format.<commit_after>/*** Copyright (c), The Regents of the University of California ***
*** For more information please refer to files in the COPYRIGHT directory ***/
/* definitions for rodsLog routines */
#include "rodsError.hpp"
#define LOG_SQL 11
/* This is for logging SQL statements. These are only logged when
specifically requested and so are a high priority at this level. */
#define LOG_DEBUG1 10
#define LOG_DEBUG2 9
#define LOG_DEBUG3 8
#define LOG_DEBUG 7
/*
The DEBUG messages are for the software engineer to analyze and
debug operations. These are typically added during development and
debug of the code, but can be left in place for possible future
use. In many cases, one would be able start seeing these messages
via a command-line argument to adjust the rodsLog verbosity level.
*/
#define LOG_NOTICE 5
#define LOG_STATUS 5
/* This is informational only, part of the normal operation but will
often be of interest. */
#define LOG_ERROR 3
/* This means that the function cannot complete what it was asked to
do, probably because of bad input from the user (an invalid host
name, for example). */
#define LOG_SYS_WARNING 2
/* This means a system-level problem occurred that is not fatal to the
whole system (it can continue to run), but does indicate an internal
inconsistency of some kind. An example is a file with a physical
size that is different than that recorded in the database.
*/
#define LOG_SYS_FATAL 1
/* This is used of errors that mean that the system (not just one
server, client, or user) cannot continue. An example is when the
server is unable to talk to the database. */
extern "C" {
void rodsLog( int level, const char *formatStr, ... );
void rodsLogAndErrorMsg( int level, rError_t *myError, int status,
const char *formatStr, ... );
void rodsLogLevel( int level );
void rodsLogSqlReq( int onOrOff );
void rodsLogSql( const char *sql );
void rodsLogSqlResult( char *stat );
char *rodsErrorName( int errorValue, char **subName );
void rodsLogErrorOld( int level, int errCode, char *textStr );
void rodsLogError( int level, int errCode, char *formatStr, ... );
int getRodsLogLevel();
void generateLogTimestamp( char *ts, int tsLen );
}
<|endoftext|>
|
<commit_before>#include <aleph/math/Bootstrap.hh>
#include <aleph/math/PiecewiseLinearFunction.hh>
#include <aleph/utilities/String.hh>
#include <fstream>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <sstream>
#include <string>
#include <vector>
#include <getopt.h>
#include <cmath>
using DataType = double;
using Function = aleph::math::PiecewiseLinearFunction<DataType>;
Function load( const std::string& filename )
{
std::ifstream in( filename );
if( !in )
throw std::runtime_error( "Unable to open file for reading" );
std::string line;
std::vector< std::pair<DataType, DataType> > data;
while( std::getline( in, line ) )
{
line = aleph::utilities::trim( line );
if( line.empty() || line.front() == '#' )
continue;
DataType x = DataType();
DataType y = DataType();
std::istringstream converter( line );
converter >> x >> y;
if( !converter )
throw std::runtime_error( "Conversion failed" );
data.push_back( std::make_pair(x,y) );
}
return Function( data.begin(), data.end() );
}
auto meanCalculation = [] ( auto begin, auto end )
{
using T = typename std::iterator_traits<decltype(begin)>::value_type;
auto sum = std::accumulate( begin, end, T() );
return sum / static_cast<double>( std::distance(begin, end) );
};
int main( int argc, char** argv )
{
DataType alpha = 0.05;
unsigned numBootstrapSamples = 10;
{
static option commandLineOptions[] =
{
{ "alpha", required_argument, nullptr, 'a' },
{ "n" , required_argument, nullptr, 'n' },
{ nullptr, 0 , nullptr, 0 }
};
int option = 0;
while( ( option = getopt_long( argc, argv, "a:", commandLineOptions, nullptr ) ) != - 1 )
{
switch( option )
{
case 'a':
alpha = DataType( std::stod( optarg ) );
break;
case 'n':
numBootstrapSamples = unsigned( std::stoull( optarg ) );
break;
default:
break;
}
}
}
if( argc - optind <= 1 )
return -1;
// Load functions ----------------------------------------------------
std::vector<Function> functions;
for( int i = optind; i < argc; i++ )
functions.push_back( load( argv[i] ) );
// Calculate mean ----------------------------------------------------
// This is the empirical mean that we obtain directly from the input
// data. We do *not* make any assumptions about its distribution.
auto empiricalMean = meanCalculation( functions.begin(), functions.end() );
// These are the bootstrap replicates of the mean function. There's
// one for every bootstrap sample.
std::vector<Function> meanReplicates;
meanReplicates.reserve( numBootstrapSamples );
aleph::math::Bootstrap bootstrap;
bootstrap.makeReplicates( numBootstrapSamples,
functions.begin(), functions.end(),
meanCalculation,
std::back_inserter( meanReplicates ) );
// This contains the population parameter of the corresponding
// empirical process, viz. the *supremum* of the difference in
// empirical mean and bootstrapped mean.
std::vector<DataType> theta;
theta.reserve( numBootstrapSamples );
for( auto&& meanReplicate : meanReplicates )
{
auto n = functions.size();
auto f = std::sqrt( n ) * ( meanReplicate - empiricalMean );
f = f.abs();
theta.push_back( f.sup() );
}
std::sort( theta.begin(), theta.end() );
auto quantile = theta.at( index( numBootstrapSamples, alpha / 2 ) );
auto fLower = empiricalMean - quantile / std::sqrt( functions.size() );
auto fUpper = empiricalMean + quantile / std::sqrt( functions.size() );
std::cout << empiricalMean << "\n\n"
<< fUpper << "\n\n"
<< fLower << "\n";
}
<commit_msg>Fixed index calculation<commit_after>#include <aleph/math/Bootstrap.hh>
#include <aleph/math/PiecewiseLinearFunction.hh>
#include <aleph/utilities/String.hh>
#include <fstream>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <sstream>
#include <string>
#include <vector>
#include <getopt.h>
#include <cmath>
using DataType = double;
using Function = aleph::math::PiecewiseLinearFunction<DataType>;
Function load( const std::string& filename )
{
std::ifstream in( filename );
if( !in )
throw std::runtime_error( "Unable to open file for reading" );
std::string line;
std::vector< std::pair<DataType, DataType> > data;
while( std::getline( in, line ) )
{
line = aleph::utilities::trim( line );
if( line.empty() || line.front() == '#' )
continue;
DataType x = DataType();
DataType y = DataType();
std::istringstream converter( line );
converter >> x >> y;
if( !converter )
throw std::runtime_error( "Conversion failed" );
data.push_back( std::make_pair(x,y) );
}
return Function( data.begin(), data.end() );
}
auto meanCalculation = [] ( auto begin, auto end )
{
using T = typename std::iterator_traits<decltype(begin)>::value_type;
auto sum = std::accumulate( begin, end, T() );
return sum / static_cast<double>( std::distance(begin, end) );
};
int main( int argc, char** argv )
{
DataType alpha = 0.05;
unsigned numBootstrapSamples = 10;
{
static option commandLineOptions[] =
{
{ "alpha", required_argument, nullptr, 'a' },
{ "n" , required_argument, nullptr, 'n' },
{ nullptr, 0 , nullptr, 0 }
};
int option = 0;
while( ( option = getopt_long( argc, argv, "a:", commandLineOptions, nullptr ) ) != - 1 )
{
switch( option )
{
case 'a':
alpha = DataType( std::stod( optarg ) );
break;
case 'n':
numBootstrapSamples = unsigned( std::stoull( optarg ) );
break;
default:
break;
}
}
}
if( argc - optind <= 1 )
return -1;
// Load functions ----------------------------------------------------
std::vector<Function> functions;
for( int i = optind; i < argc; i++ )
functions.push_back( load( argv[i] ) );
// Calculate mean ----------------------------------------------------
// This is the empirical mean that we obtain directly from the input
// data. We do *not* make any assumptions about its distribution.
auto empiricalMean = meanCalculation( functions.begin(), functions.end() );
// These are the bootstrap replicates of the mean function. There's
// one for every bootstrap sample.
std::vector<Function> meanReplicates;
meanReplicates.reserve( numBootstrapSamples );
aleph::math::Bootstrap bootstrap;
bootstrap.makeReplicates( numBootstrapSamples,
functions.begin(), functions.end(),
meanCalculation,
std::back_inserter( meanReplicates ) );
// This contains the population parameter of the corresponding
// empirical process, viz. the *supremum* of the difference in
// empirical mean and bootstrapped mean.
std::vector<DataType> theta;
theta.reserve( numBootstrapSamples );
for( auto&& meanReplicate : meanReplicates )
{
auto n = functions.size();
auto f = std::sqrt( n ) * ( meanReplicate - empiricalMean );
f = f.abs();
theta.push_back( f.sup() );
}
std::sort( theta.begin(), theta.end() );
auto quantile = theta.at( bootstrap.index( numBootstrapSamples, alpha / 2 ) );
auto fLower = empiricalMean - quantile / std::sqrt( functions.size() );
auto fUpper = empiricalMean + quantile / std::sqrt( functions.size() );
std::cout << empiricalMean << "\n\n"
<< fUpper << "\n\n"
<< fLower << "\n";
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* 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 Hobu, Inc. or Flaxen Geo Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#ifndef INCLUDED_APPSUPPORT_HPP
#define INCLUDED_APPSUPPORT_HPP
#include <string>
#include <pdal/Options.hpp>
#include <pdal/Stage.hpp>
#include <pdal/Writer.hpp>
#include "Application.hpp"
// this is a static class with some helper functions the cmd line apps need
class AppSupport
{
public:
// makes a reader/stage, from just the filename and some other options
static pdal::Stage& AppSupport::makeReader(pdal::Options& options);
// makes a writer, from just the filename and some other options (and the input stage)
static pdal::Writer& AppSupport::makeWriter(pdal::Options& options, pdal::Stage& stage);
private:
// infer the driver to use based on filename extension
// returns "" if no driver found
//
// this may also add on an option to pass to the driver, such as the filename
static std::string inferReaderDriver(const std::string& filename, pdal::Options& options);
// infer the driver to use based on filename extension
// returns "" if no driver found
//
// this may also add on an option to pass to the driver, such as the filename
// (or something inferred from the extension, such as .laz means we need to use compress=true)
static std::string inferWriterDriver(const std::string& filename, pdal::Options& options);
AppSupport& operator=(const AppSupport&); // not implemented
AppSupport(const AppSupport&); // not implemented
};
#endif
<commit_msg>gcc fix<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* 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 Hobu, Inc. or Flaxen Geo Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#ifndef INCLUDED_APPSUPPORT_HPP
#define INCLUDED_APPSUPPORT_HPP
#include <string>
#include <pdal/Options.hpp>
#include <pdal/Stage.hpp>
#include <pdal/Writer.hpp>
#include "Application.hpp"
// this is a static class with some helper functions the cmd line apps need
class AppSupport
{
public:
// makes a reader/stage, from just the filename and some other options
static pdal::Stage& makeReader(pdal::Options& options);
// makes a writer, from just the filename and some other options (and the input stage)
static pdal::Writer& makeWriter(pdal::Options& options, pdal::Stage& stage);
private:
// infer the driver to use based on filename extension
// returns "" if no driver found
//
// this may also add on an option to pass to the driver, such as the filename
static std::string inferReaderDriver(const std::string& filename, pdal::Options& options);
// infer the driver to use based on filename extension
// returns "" if no driver found
//
// this may also add on an option to pass to the driver, such as the filename
// (or something inferred from the extension, such as .laz means we need to use compress=true)
static std::string inferWriterDriver(const std::string& filename, pdal::Options& options);
AppSupport& operator=(const AppSupport&); // not implemented
AppSupport(const AppSupport&); // not implemented
};
#endif
<|endoftext|>
|
<commit_before>/*******************************************************************************
* c7a/data/channel_sink.hpp
*
* Part of Project c7a.
*
* Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef C7A_DATA_CHANNEL_SINK_HEADER
#define C7A_DATA_CHANNEL_SINK_HEADER
#include <c7a/net/buffer.hpp>
#include <c7a/data/stream_block_header.hpp>
#include <c7a/net/dispatcher_thread.hpp>
#include <c7a/data/block.hpp>
#include <c7a/data/block_sink.hpp>
#include <c7a/common/logger.hpp>
namespace c7a {
namespace data {
//! ChannelSink is an BlockSink that sends data via a network socket to the
//! Channel object on a different worker.
template <size_t BlockSize>
class ChannelSink : public BlockSink<BlockSize>
{
public:
using Block = data::Block<BlockSize>;
using BlockCPtr = std::shared_ptr<const Block>;
using VirtualBlock = data::VirtualBlock<BlockSize>;
using ChannelId = size_t;
//! invalid ChannelSink, needed for placeholders in sinks arrays where
//! Blocks are directly sent to local workers.
ChannelSink()
{ }
//! ChannelSink sending out to network.
ChannelSink(net::DispatcherThread* dispatcher,
net::Connection* connection,
ChannelId channel_id, size_t own_rank)
: dispatcher_(dispatcher),
connection_(connection),
id_(channel_id),
own_rank_(own_rank)
{ }
ChannelSink(ChannelSink&&) = default;
//! Appends data to the ChannelSink. Data may be sent but may be delayed.
void Append(VirtualBlock&& vb) override {
if (vb.bytes_used == 0) return;
StreamBlockHeader header;
header.channel_id = id_;
header.expected_bytes = vb.bytes_used;
header.expected_elements = vb.nitems;
header.sender_rank = own_rank_;
sLOG1 << "sending block"
<< common::hexdump(vb.block->begin(), vb.bytes_used);
// TODO(tb): this copies data!
net::Buffer payload_buf(vb.block->begin(), vb.bytes_used);
dispatcher_->AsyncWrite(
*connection_,
// send out two Buffer, guaranteed to be successive
header.Serialize(), std::move(payload_buf));
}
// //! Sends bare data via the socket
// //! \param data base address of the data
// //! \param len of data to be sent in bytes
// //! \param num_elements number of elements in the send-range
// void Pipe(const void* data, size_t len, size_t num_elements) {
// if (len == 0) {
// return;
// }
// SendHeader(len, num_elements);
// //TODO(ts) this copies the data.
// net::Buffer payload_buf = net::Buffer(data, len);
// dispatcher_->AsyncWrite(*connection_, std::move(payload_buf));
// }
//! Closes the connection
void Close() override {
assert(!closed_);
closed_ = true;
sLOG << "sending 'close channel' from worker" << own_rank_ << "on" << id_;
SendHeader(0, 0);
}
protected:
static const bool debug = false;
net::DispatcherThread* dispatcher_ = nullptr;
net::Connection* connection_ = nullptr;
size_t id_ = -1;
size_t own_rank_ = -1;
bool closed_ = false;
};
} // namespace data
} // namespace c7a
#endif // !C7A_DATA_CHANNEL_SINK_HEADER
/******************************************************************************/
<commit_msg>Fixing SendHeader() replacement which got lost in translation.<commit_after>/*******************************************************************************
* c7a/data/channel_sink.hpp
*
* Part of Project c7a.
*
* Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef C7A_DATA_CHANNEL_SINK_HEADER
#define C7A_DATA_CHANNEL_SINK_HEADER
#include <c7a/net/buffer.hpp>
#include <c7a/data/stream_block_header.hpp>
#include <c7a/net/dispatcher_thread.hpp>
#include <c7a/data/block.hpp>
#include <c7a/data/block_sink.hpp>
#include <c7a/common/logger.hpp>
namespace c7a {
namespace data {
//! ChannelSink is an BlockSink that sends data via a network socket to the
//! Channel object on a different worker.
template <size_t BlockSize>
class ChannelSink : public BlockSink<BlockSize>
{
public:
using Block = data::Block<BlockSize>;
using BlockCPtr = std::shared_ptr<const Block>;
using VirtualBlock = data::VirtualBlock<BlockSize>;
using ChannelId = size_t;
//! invalid ChannelSink, needed for placeholders in sinks arrays where
//! Blocks are directly sent to local workers.
ChannelSink() : closed_(true) { }
//! ChannelSink sending out to network.
ChannelSink(net::DispatcherThread* dispatcher,
net::Connection* connection,
ChannelId channel_id, size_t own_rank)
: dispatcher_(dispatcher),
connection_(connection),
id_(channel_id),
own_rank_(own_rank)
{ }
ChannelSink(ChannelSink&&) = default;
//! Appends data to the ChannelSink. Data may be sent but may be delayed.
void Append(VirtualBlock&& vb) override {
if (vb.bytes_used == 0) return;
StreamBlockHeader header;
header.channel_id = id_;
header.expected_bytes = vb.bytes_used;
header.expected_elements = vb.nitems;
header.sender_rank = own_rank_;
sLOG1 << "sending block"
<< common::hexdump(vb.block->begin(), vb.bytes_used);
// TODO(tb): this copies data!
net::Buffer payload_buf(vb.block->begin(), vb.bytes_used);
dispatcher_->AsyncWrite(
*connection_,
// send out two Buffer, guaranteed to be successive
header.Serialize(), std::move(payload_buf));
}
// //! Sends bare data via the socket
// //! \param data base address of the data
// //! \param len of data to be sent in bytes
// //! \param num_elements number of elements in the send-range
// void Pipe(const void* data, size_t len, size_t num_elements) {
// if (len == 0) {
// return;
// }
// SendHeader(len, num_elements);
// //TODO(ts) this copies the data.
// net::Buffer payload_buf = net::Buffer(data, len);
// dispatcher_->AsyncWrite(*connection_, std::move(payload_buf));
// }
//! Closes the connection
void Close() override {
assert(!closed_);
closed_ = true;
sLOG << "sending 'close channel' from worker" << own_rank_ << "on" << id_;
StreamBlockHeader header;
header.channel_id = id_;
header.expected_bytes = 0;
header.expected_elements = 0;
header.sender_rank = own_rank_;
dispatcher_->AsyncWrite(*connection_, header.Serialize());
}
//! return close flag
bool closed() const { return closed_; }
protected:
static const bool debug = false;
net::DispatcherThread* dispatcher_ = nullptr;
net::Connection* connection_ = nullptr;
size_t id_ = -1;
size_t own_rank_ = -1;
bool closed_ = false;
};
} // namespace data
} // namespace c7a
#endif // !C7A_DATA_CHANNEL_SINK_HEADER
/******************************************************************************/
<|endoftext|>
|
<commit_before>#include "Lexer.h"
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <sstream>
using namespace garter;
enum CharType {
LOWER_CASE = 0x01,
UPPER_CASE = 0x02,
UNDERSCORE = 0x04,
NUMBER = 0x08,
};
static const uint8_t CharTab[256] = {
['a' ... 'z'] = LOWER_CASE,
['A' ... 'Z'] = UPPER_CASE,
['_'] = UNDERSCORE,
['0' ... '9'] = NUMBER,
};
void Lexer::reportError(const char *format, ...)
{
va_list va;
va_start(va, format);
fprintf(stderr, "Error near line %lu: ", CurrentLineNumber);
vfprintf(stderr, format, va);
putc('\n', stderr);
va_end(va);
}
void Lexer::nextChar()
{
CurrentChar = 0;
(*InputStream) >> CurrentChar;
}
std::unique_ptr<Token> Lexer::lexIdentifierOrKeyword()
{
std::string name;
do {
name.push_back(CurrentChar);
nextChar();
} while (CharTab[(uint8_t)CurrentChar] & (LOWER_CASE | UPPER_CASE |
UNDERSCORE | NUMBER));
auto it_kw = Keywords.find(name);
if (it_kw != Keywords.end()) {
return std::unique_ptr<Token>(new Token(it_kw->second));
} else {
char *nameptr = new char[name.length() + 1];
memcpy(nameptr, name.c_str(), name.length() + 1);
return std::unique_ptr<Token>(new Token(Token::Identifier, nameptr));
}
}
std::unique_ptr<Token> Lexer::lexNumber()
{
int32_t n = 0;
do {
int32_t next_digit = (CurrentChar - '0');
if (n > INT32_MAX / 10)
goto too_large;
n *= 10;
if (n > INT32_MAX - next_digit)
goto too_large;
n += next_digit;
nextChar();
} while (CurrentChar >= '0' && CurrentChar <= '9');
return std::unique_ptr<Token>(new Token(Token::Number, n));
too_large:
reportError("integer constant too large");
return std::unique_ptr<Token>(new Token(Token::Error));
}
std::unique_ptr<Token> Lexer::getNextToken()
{
next_char:
switch (CurrentChar) {
case '\n':
CurrentLineNumber++;
// Fall through
case ' ':
case '\t':
case '\v':
// Skip whitespace character
nextChar();
goto next_char;
case '#':
// Skip comment
do {
nextChar();
} while (CurrentChar != '\n' && CurrentChar != '\0');
goto next_char;
case 'a' ... 'z':
case 'A' ... 'Z':
case '_':
return lexIdentifierOrKeyword();
case '0' ... '9':
return lexNumber();
case '(':
nextChar();
return std::unique_ptr<Token>(new Token(Token::LeftParenthesis));
case ')':
nextChar();
return std::unique_ptr<Token>(new Token(Token::RightParenthesis));
case ':':
nextChar();
return std::unique_ptr<Token>(new Token(Token::Colon));
case ';':
nextChar();
return std::unique_ptr<Token>(new Token(Token::Semicolon));
case ',':
nextChar();
return std::unique_ptr<Token>(new Token(Token::Comma));
case '[':
nextChar();
return std::unique_ptr<Token>(new Token(Token::LeftSquareBracket));
case ']':
nextChar();
return std::unique_ptr<Token>(new Token(Token::RightSquareBracket));
case '=':
nextChar();
if (CurrentChar == '=') {
// Double equals (equality predicate)
nextChar();
return std::unique_ptr<Token>(new Token(Token::DoubleEquals));
} else {
// Equals (assignment)
return std::unique_ptr<Token>(new Token(Token::Equals));
}
break;
case '+':
nextChar();
return std::unique_ptr<Token>(new Token(Token::Plus));
case '-':
nextChar();
return std::unique_ptr<Token>(new Token(Token::Minus));
case '*':
nextChar();
if (CurrentChar == '*') {
nextChar();
return std::unique_ptr<Token>(new Token(Token::DoubleAsterisk));
} else {
return std::unique_ptr<Token>(new Token(Token::Asterisk));
}
break;
case '/':
nextChar();
return std::unique_ptr<Token>(new Token(Token::ForwardSlash));
case '%':
nextChar();
return std::unique_ptr<Token>(new Token(Token::Percent));
case '<':
nextChar();
if (CurrentChar == '=') {
nextChar();
return std::unique_ptr<Token>(new Token(Token::LessThanOrEqualTo));
} else {
return std::unique_ptr<Token>(new Token(Token::LessThan));
}
case '>':
nextChar();
if (CurrentChar == '=') {
nextChar();
return std::unique_ptr<Token>(new Token(Token::GreaterThanOrEqualTo));
} else {
return std::unique_ptr<Token>(new Token(Token::GreaterThan));
}
case '!':
nextChar();
if (CurrentChar == '=') {
// "Not equal to" symbol
nextChar();
return std::unique_ptr<Token>(new Token(Token::NotEqualTo));
} else {
// '!' followed by something else--- not valid
reportError("unexpected character '%c' after '!'");
return std::unique_ptr<Token>(new Token(Token::Error));
}
case '\0':
if (InputStream->eof()) {
return std::unique_ptr<Token>(new Token(Token::EndOfFile));
} else {
reportError("error reading input");
return std::unique_ptr<Token>(new Token(Token::Error));
}
default:
reportError("unexpected character '%c'", CurrentChar);
return std::unique_ptr<Token>(new Token(Token::Error));
}
}
void Lexer::init()
{
CurrentLineNumber = 1;
CurrentChar = 0;
InputStream->unsetf(std::ios_base::skipws);
Keywords.insert(std::make_pair("and", Token::And));
Keywords.insert(std::make_pair("def", Token::Def));
Keywords.insert(std::make_pair("else", Token::Else));
Keywords.insert(std::make_pair("elif", Token::Elif));
Keywords.insert(std::make_pair("enddef", Token::EndDef));
Keywords.insert(std::make_pair("endfor", Token::EndFor));
Keywords.insert(std::make_pair("endif", Token::EndIf));
Keywords.insert(std::make_pair("endwhile", Token::EndWhile));
Keywords.insert(std::make_pair("extern", Token::Extern));
Keywords.insert(std::make_pair("for", Token::For));
Keywords.insert(std::make_pair("if", Token::If));
Keywords.insert(std::make_pair("in", Token::In));
Keywords.insert(std::make_pair("not", Token::Not));
Keywords.insert(std::make_pair("or", Token::Or));
Keywords.insert(std::make_pair("pass", Token::Pass));
Keywords.insert(std::make_pair("print", Token::Print));
Keywords.insert(std::make_pair("return", Token::Return));
Keywords.insert(std::make_pair("while", Token::While));
nextChar();
}
Lexer::Lexer(const char *str)
{
StringStream = new std::istringstream(str, std::ios_base::in);
InputStream = StringStream;
init();
}
Lexer::Lexer(std::istream & is)
{
StringStream = nullptr;
InputStream = &is;
init();
}
Lexer::~Lexer()
{
delete StringStream;
}
<commit_msg>Treat carriage returns as whitespace<commit_after>#include "Lexer.h"
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <sstream>
using namespace garter;
enum CharType {
LOWER_CASE = 0x01,
UPPER_CASE = 0x02,
UNDERSCORE = 0x04,
NUMBER = 0x08,
};
static const uint8_t CharTab[256] = {
['a' ... 'z'] = LOWER_CASE,
['A' ... 'Z'] = UPPER_CASE,
['_'] = UNDERSCORE,
['0' ... '9'] = NUMBER,
};
void Lexer::reportError(const char *format, ...)
{
va_list va;
va_start(va, format);
fprintf(stderr, "Error near line %lu: ", CurrentLineNumber);
vfprintf(stderr, format, va);
putc('\n', stderr);
va_end(va);
}
void Lexer::nextChar()
{
CurrentChar = 0;
(*InputStream) >> CurrentChar;
}
std::unique_ptr<Token> Lexer::lexIdentifierOrKeyword()
{
std::string name;
do {
name.push_back(CurrentChar);
nextChar();
} while (CharTab[(uint8_t)CurrentChar] & (LOWER_CASE | UPPER_CASE |
UNDERSCORE | NUMBER));
auto it_kw = Keywords.find(name);
if (it_kw != Keywords.end()) {
return std::unique_ptr<Token>(new Token(it_kw->second));
} else {
char *nameptr = new char[name.length() + 1];
memcpy(nameptr, name.c_str(), name.length() + 1);
return std::unique_ptr<Token>(new Token(Token::Identifier, nameptr));
}
}
std::unique_ptr<Token> Lexer::lexNumber()
{
int32_t n = 0;
do {
int32_t next_digit = (CurrentChar - '0');
if (n > INT32_MAX / 10)
goto too_large;
n *= 10;
if (n > INT32_MAX - next_digit)
goto too_large;
n += next_digit;
nextChar();
} while (CurrentChar >= '0' && CurrentChar <= '9');
return std::unique_ptr<Token>(new Token(Token::Number, n));
too_large:
reportError("integer constant too large");
return std::unique_ptr<Token>(new Token(Token::Error));
}
std::unique_ptr<Token> Lexer::getNextToken()
{
next_char:
switch (CurrentChar) {
case '\n':
CurrentLineNumber++;
// Fall through
case ' ':
case '\t':
case '\v':
case '\r':
// Skip whitespace character
nextChar();
goto next_char;
case '#':
// Skip comment
do {
nextChar();
} while (CurrentChar != '\n' && CurrentChar != '\0');
goto next_char;
case 'a' ... 'z':
case 'A' ... 'Z':
case '_':
return lexIdentifierOrKeyword();
case '0' ... '9':
return lexNumber();
case '(':
nextChar();
return std::unique_ptr<Token>(new Token(Token::LeftParenthesis));
case ')':
nextChar();
return std::unique_ptr<Token>(new Token(Token::RightParenthesis));
case ':':
nextChar();
return std::unique_ptr<Token>(new Token(Token::Colon));
case ';':
nextChar();
return std::unique_ptr<Token>(new Token(Token::Semicolon));
case ',':
nextChar();
return std::unique_ptr<Token>(new Token(Token::Comma));
case '[':
nextChar();
return std::unique_ptr<Token>(new Token(Token::LeftSquareBracket));
case ']':
nextChar();
return std::unique_ptr<Token>(new Token(Token::RightSquareBracket));
case '=':
nextChar();
if (CurrentChar == '=') {
// Double equals (equality predicate)
nextChar();
return std::unique_ptr<Token>(new Token(Token::DoubleEquals));
} else {
// Equals (assignment)
return std::unique_ptr<Token>(new Token(Token::Equals));
}
break;
case '+':
nextChar();
return std::unique_ptr<Token>(new Token(Token::Plus));
case '-':
nextChar();
return std::unique_ptr<Token>(new Token(Token::Minus));
case '*':
nextChar();
if (CurrentChar == '*') {
nextChar();
return std::unique_ptr<Token>(new Token(Token::DoubleAsterisk));
} else {
return std::unique_ptr<Token>(new Token(Token::Asterisk));
}
break;
case '/':
nextChar();
return std::unique_ptr<Token>(new Token(Token::ForwardSlash));
case '%':
nextChar();
return std::unique_ptr<Token>(new Token(Token::Percent));
case '<':
nextChar();
if (CurrentChar == '=') {
nextChar();
return std::unique_ptr<Token>(new Token(Token::LessThanOrEqualTo));
} else {
return std::unique_ptr<Token>(new Token(Token::LessThan));
}
case '>':
nextChar();
if (CurrentChar == '=') {
nextChar();
return std::unique_ptr<Token>(new Token(Token::GreaterThanOrEqualTo));
} else {
return std::unique_ptr<Token>(new Token(Token::GreaterThan));
}
case '!':
nextChar();
if (CurrentChar == '=') {
// "Not equal to" symbol
nextChar();
return std::unique_ptr<Token>(new Token(Token::NotEqualTo));
} else {
// '!' followed by something else--- not valid
reportError("unexpected character '%c' after '!'");
return std::unique_ptr<Token>(new Token(Token::Error));
}
case '\0':
if (InputStream->eof()) {
return std::unique_ptr<Token>(new Token(Token::EndOfFile));
} else {
reportError("error reading input");
return std::unique_ptr<Token>(new Token(Token::Error));
}
default:
reportError("unexpected character '%c'", CurrentChar);
return std::unique_ptr<Token>(new Token(Token::Error));
}
}
void Lexer::init()
{
CurrentLineNumber = 1;
CurrentChar = 0;
InputStream->unsetf(std::ios_base::skipws);
Keywords.insert(std::make_pair("and", Token::And));
Keywords.insert(std::make_pair("def", Token::Def));
Keywords.insert(std::make_pair("else", Token::Else));
Keywords.insert(std::make_pair("elif", Token::Elif));
Keywords.insert(std::make_pair("enddef", Token::EndDef));
Keywords.insert(std::make_pair("endfor", Token::EndFor));
Keywords.insert(std::make_pair("endif", Token::EndIf));
Keywords.insert(std::make_pair("endwhile", Token::EndWhile));
Keywords.insert(std::make_pair("extern", Token::Extern));
Keywords.insert(std::make_pair("for", Token::For));
Keywords.insert(std::make_pair("if", Token::If));
Keywords.insert(std::make_pair("in", Token::In));
Keywords.insert(std::make_pair("not", Token::Not));
Keywords.insert(std::make_pair("or", Token::Or));
Keywords.insert(std::make_pair("pass", Token::Pass));
Keywords.insert(std::make_pair("print", Token::Print));
Keywords.insert(std::make_pair("return", Token::Return));
Keywords.insert(std::make_pair("while", Token::While));
nextChar();
}
Lexer::Lexer(const char *str)
{
StringStream = new std::istringstream(str, std::ios_base::in);
InputStream = StringStream;
init();
}
Lexer::Lexer(std::istream & is)
{
StringStream = nullptr;
InputStream = &is;
init();
}
Lexer::~Lexer()
{
delete StringStream;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: flushcode.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: kz $ $Date: 2005-07-01 12:17:17 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "sal/config.h"
#include "flushcode.hxx"
extern "C" void doFlushCode(unsigned long address, unsigned long count);
namespace bridges { namespace cpp_uno { namespace cc50_solaris_sparc {
void flushCode(void const * begin, void const * end) {
unsigned long n =
static_cast< char const * >(end) - static_cast< char const * >(begin);
if (n != 0) {
unsigned long adr = reinterpret_cast< unsigned long >(begin);
unsigned long off = adr & 7;
doFlushCode(adr - off, (n + off + 7) >> 3);
}
}
} } }
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.8); FILE MERGED 2005/09/05 17:07:11 rt 1.2.8.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: flushcode.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 22:18:51 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "sal/config.h"
#include "flushcode.hxx"
extern "C" void doFlushCode(unsigned long address, unsigned long count);
namespace bridges { namespace cpp_uno { namespace cc50_solaris_sparc {
void flushCode(void const * begin, void const * end) {
unsigned long n =
static_cast< char const * >(end) - static_cast< char const * >(begin);
if (n != 0) {
unsigned long adr = reinterpret_cast< unsigned long >(begin);
unsigned long off = adr & 7;
doFlushCode(adr - off, (n + off + 7) >> 3);
}
}
} } }
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: Ken Zangelin
*/
#include "gtest/gtest.h"
#include "serviceRoutines/exitTreat.h"
#include "rest/RestService.h"
/* ****************************************************************************
*
* rs -
*/
static RestService rs[] =
{
{ "GET ExitRequest", "GET", ExitRequest, 2, { "exit", "*" }, "", exitTreat },
{ "GET ExitRequest", "GET", ExitRequest, 1, { "exit" }, "", exitTreat },
{ "* *", "", InvalidRequest, 0, { }, "", NULL }
};
/* ****************************************************************************
*
* error -
*/
TEST(exitTreat, error)
{
ConnectionInfo ci1("/exit", "GET", "1.1");
ConnectionInfo ci2("/exit/nadadenada", "GET", "1.1");
ConnectionInfo ci3("/exit/harakiri", "GET", "1.1");
std::string expected1 = "<orionError>\n <code>400</code>\n <reasonPhrase>Bad request</reasonPhrase>\n <details>Password requested</details>\n</orionError>\n";
std::string expected2 = "<orionError>\n <code>400</code>\n <reasonPhrase>Bad request</reasonPhrase>\n <details>Request denied - password erroneous</details>\n</orionError>\n";
std::string out1 = restService(&ci1, rs);
std::string out2 = restService(&ci2, rs);
EXPECT_STREQ(expected1.c_str(), out1.c_str());
EXPECT_STREQ(expected2.c_str(), out2.c_str());
extern bool harakiri;
harakiri = false;
std::string expected3 = "<orionError>\n <code>400</code>\n <reasonPhrase>Bad request</reasonPhrase>\n <details>no such service</details>\n</orionError>\n";
std::string out3 = restService(&ci3, rs);
EXPECT_STREQ(expected3.c_str(), out3.c_str());
}
<commit_msg>initializing 'harakiri' before the unit test<commit_after>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: Ken Zangelin
*/
#include "gtest/gtest.h"
#include "serviceRoutines/exitTreat.h"
#include "rest/RestService.h"
/* ****************************************************************************
*
* harakiri -
*/
extern bool harakiri;
/* ****************************************************************************
*
* rs -
*/
static RestService rs[] =
{
{ "GET ExitRequest", "GET", ExitRequest, 2, { "exit", "*" }, "", exitTreat },
{ "GET ExitRequest", "GET", ExitRequest, 1, { "exit" }, "", exitTreat },
{ "* *", "", InvalidRequest, 0, { }, "", NULL }
};
/* ****************************************************************************
*
* error -
*/
TEST(exitTreat, error)
{
ConnectionInfo ci1("/exit", "GET", "1.1");
ConnectionInfo ci2("/exit/nadadenada", "GET", "1.1");
ConnectionInfo ci3("/exit/harakiri", "GET", "1.1");
std::string expected1 = "<orionError>\n <code>400</code>\n <reasonPhrase>Bad request</reasonPhrase>\n <details>Password requested</details>\n</orionError>\n";
std::string expected2 = "<orionError>\n <code>400</code>\n <reasonPhrase>Bad request</reasonPhrase>\n <details>Request denied - password erroneous</details>\n</orionError>\n";
std::string expected3 = "<orionError>\n <code>400</code>\n <reasonPhrase>Bad request</reasonPhrase>\n <details>no such service</details>\n</orionError>\n";
std::string out;
harakiri = true;
out = restService(&ci1, rs);
EXPECT_EQ(expected1, out);
out =restService(&ci2, rs);
EXPECT_EQ(expected2, out);
harakiri = false;
out = restService(&ci3, rs);
EXPECT_EQ(expected3, out);
}
<|endoftext|>
|
<commit_before>#include <spv_utils.h>
#include <cassert>
namespace sut {
static const size_t kSpvIndexMagicNumber = 0;
static const size_t kSpvIndexVersionNumber = 1;
static const size_t kSpvIndexGeneratorNumber = 2;
static const size_t kSpvIndexBound = 3;
static const size_t kSpvIndexSchema = 4;
static const size_t kSpvIndexInstruction = 5;
struct OpcodeHeader {
uint16_t words_count;
uint16_t opcode;
}; // struct OpCodeHeader
static OpcodeHeader SplitSpvOpCode(uint32_t word) {
return{
static_cast<uint16_t>((0xFFFF0000 & word) >> 16U),
static_cast<uint16_t>(0x0000FFFF & word) };
}
static uint32_t MergeSpvOpCode(const OpcodeHeader &header) {
return (
(static_cast<uint32_t>(header.words_count) << 16U) |
(static_cast<uint32_t>(header.opcode)));
}
OpcodeStream::OpcodeStream()
: module_stream_(),
parse_result_(Result::SPV_ERROR_INTERNAL),
offsets_table_() {}
OpcodeStream::OpcodeStream(const void *module_stream, size_t binary_size)
: module_stream_(),
parse_result_(Result::SPV_ERROR_INTERNAL),
offsets_table_() {
parse_result_ = ParseModule(module_stream, binary_size);
}
Result OpcodeStream::ParseModuleInternal() {
const size_t words_count = module_stream_.size();
if (words_count < kSpvIndexInstruction) {
return Result::SPV_ERROR_INTERNAL;
}
// Set tokens for theader; these always take the same amount of words
InsertOffsetInTable(kSpvIndexMagicNumber);
InsertOffsetInTable(kSpvIndexVersionNumber);
InsertOffsetInTable(kSpvIndexGeneratorNumber);
InsertOffsetInTable(kSpvIndexBound);
InsertOffsetInTable(kSpvIndexSchema);
size_t word_index = kSpvIndexInstruction;
// Once the loop is finished, the offsets table will contain one entry
// per instruction
while (word_index < words_count) {
size_t inst_word_count = 0;
if (ParseInstruction(word_index, &inst_word_count)
!= Result::SPV_SUCCESS) {
return Result::SPV_ERROR_INTERNAL;
}
// Insert offset for the current instruction
InsertOffsetInTable(word_index);
// Advance the word index by the size of the instruction
word_index += inst_word_count;
}
// Append end terminator to table
InsertOffsetInTable(words_count);
// Append end terminator word to original words stream
InsertWordHeaderInOriginalStream({0U, static_cast<uint16_t>(spv::Op::OpNop)});
return Result::SPV_SUCCESS;
}
void OpcodeStream::InsertWordHeaderInOriginalStream(const OpcodeHeader &header) {
module_stream_.push_back(
MergeSpvOpCode(header));
}
void OpcodeStream::InsertOffsetInTable(size_t offset) {
offsets_table_.push_back(OpcodeOffset(offset, *this));
}
bool OpcodeStream::IsValid() const {
switch (parse_result_) {
case Result::SPV_SUCCESS: {
return true;
}
default: {
return false;
}
}
}
OpcodeStream::operator bool() const {
return IsValid();
}
Result OpcodeStream::ParseInstruction(
size_t start_index,
size_t *words_count) {
// Read the first word of the instruction, which
// contains the word count
uint32_t first_word = PeekAt(start_index);
// Decompose and read the word count
OpcodeHeader header = SplitSpvOpCode(first_word);
if (header.words_count < 1U) {
return Result::SPV_ERROR_INTERNAL;
}
*words_count = static_cast<size_t>(header.words_count);
return Result::SPV_SUCCESS;
}
void OpcodeStream::Reset() {
module_stream_.clear();
offsets_table_.clear();
parse_result_ = Result::SPV_ERROR_INTERNAL;
}
Result OpcodeStream::ParseModule(const void *module_stream, size_t binary_size) {
assert(binary_size && module_stream);
// Make a copy of the data
const uint32_t *stream = static_cast<const uint32_t *>(module_stream);
module_stream_.assign(stream, stream + (binary_size / 4));
return ParseModuleInternal();
}
uint32_t OpcodeStream::PeekAt(size_t index) {
return module_stream_[index];
}
std::vector<uint32_t> OpcodeStream::EmitFilteredStream() const {
std::vector<uint32_t> new_stream;
for (std::vector<OpcodeOffset>::const_iterator oi = offsets_table_.begin();
oi != (offsets_table_.end() - 1);
oi++) {
// If there are pending Insert Before operations, emit those ones first
if (!oi->words_before_.empty()) {
new_stream.insert(new_stream.end(), oi->words_before_.begin(),
oi->words_before_.end());
}
// If the original instruction is not to be removed, emit it
if (!oi->remove_) {
new_stream.insert(
new_stream.end(),
module_stream_.begin() + oi->offset_,
module_stream_.begin() + ((oi + 1)->offset_));
}
// If there are pending Insert After operations, emit them at the end
if (!oi->words_after_.empty()) {
new_stream.insert(new_stream.end(), oi->words_after_.begin(),
oi->words_after_.end());
}
}
return new_stream;
}
OpcodeStream::iterator OpcodeStream::begin() {
return offsets_table_.begin();
}
OpcodeStream::iterator OpcodeStream::end() {
return offsets_table_.end();
}
OpcodeOffset::OpcodeOffset(size_t offset, const OpcodeStream &opcode_stream)
: offset_(offset),
words_before_(),
words_after_(),
remove_(false),
opcode_stream_(opcode_stream) {}
spv::Op OpcodeOffset::GetOpcode() const {
uint32_t header_word = opcode_stream_.module_stream()[offset_];
return static_cast<spv::Op>(SplitSpvOpCode(header_word).opcode);
}
void OpcodeOffset::InsertBefore(const uint32_t *instructions,
size_t words_count) {
assert(instructions && words_count);
words_before_.insert(
words_before_.begin(),
instructions,
instructions + words_count);
}
void OpcodeOffset::InsertAfter(const uint32_t *instructions,
size_t words_count) {
assert(instructions && words_count);
words_after_.insert(
words_after_.begin(),
instructions,
instructions + words_count);
}
void OpcodeOffset::Remove() {
remove_ = true;
}
} // namespace sut<commit_msg>Improve perf. of EmitFilteredStream<commit_after>#include <spv_utils.h>
#include <cassert>
namespace sut {
static const size_t kSpvIndexMagicNumber = 0;
static const size_t kSpvIndexVersionNumber = 1;
static const size_t kSpvIndexGeneratorNumber = 2;
static const size_t kSpvIndexBound = 3;
static const size_t kSpvIndexSchema = 4;
static const size_t kSpvIndexInstruction = 5;
struct OpcodeHeader {
uint16_t words_count;
uint16_t opcode;
}; // struct OpCodeHeader
static OpcodeHeader SplitSpvOpCode(uint32_t word) {
return{
static_cast<uint16_t>((0xFFFF0000 & word) >> 16U),
static_cast<uint16_t>(0x0000FFFF & word) };
}
static uint32_t MergeSpvOpCode(const OpcodeHeader &header) {
return (
(static_cast<uint32_t>(header.words_count) << 16U) |
(static_cast<uint32_t>(header.opcode)));
}
OpcodeStream::OpcodeStream()
: module_stream_(),
parse_result_(Result::SPV_ERROR_INTERNAL),
offsets_table_() {}
OpcodeStream::OpcodeStream(const void *module_stream, size_t binary_size)
: module_stream_(),
parse_result_(Result::SPV_ERROR_INTERNAL),
offsets_table_() {
parse_result_ = ParseModule(module_stream, binary_size);
}
Result OpcodeStream::ParseModuleInternal() {
const size_t words_count = module_stream_.size();
if (words_count < kSpvIndexInstruction) {
return Result::SPV_ERROR_INTERNAL;
}
// Set tokens for theader; these always take the same amount of words
InsertOffsetInTable(kSpvIndexMagicNumber);
InsertOffsetInTable(kSpvIndexVersionNumber);
InsertOffsetInTable(kSpvIndexGeneratorNumber);
InsertOffsetInTable(kSpvIndexBound);
InsertOffsetInTable(kSpvIndexSchema);
size_t word_index = kSpvIndexInstruction;
// Once the loop is finished, the offsets table will contain one entry
// per instruction
while (word_index < words_count) {
size_t inst_word_count = 0;
if (ParseInstruction(word_index, &inst_word_count)
!= Result::SPV_SUCCESS) {
return Result::SPV_ERROR_INTERNAL;
}
// Insert offset for the current instruction
InsertOffsetInTable(word_index);
// Advance the word index by the size of the instruction
word_index += inst_word_count;
}
// Append end terminator to table
InsertOffsetInTable(words_count);
// Append end terminator word to original words stream
InsertWordHeaderInOriginalStream({0U, static_cast<uint16_t>(spv::Op::OpNop)});
return Result::SPV_SUCCESS;
}
void OpcodeStream::InsertWordHeaderInOriginalStream(const OpcodeHeader &header) {
module_stream_.push_back(
MergeSpvOpCode(header));
}
void OpcodeStream::InsertOffsetInTable(size_t offset) {
offsets_table_.push_back(OpcodeOffset(offset, *this));
}
bool OpcodeStream::IsValid() const {
switch (parse_result_) {
case Result::SPV_SUCCESS: {
return true;
}
default: {
return false;
}
}
}
OpcodeStream::operator bool() const {
return IsValid();
}
Result OpcodeStream::ParseInstruction(
size_t start_index,
size_t *words_count) {
// Read the first word of the instruction, which
// contains the word count
uint32_t first_word = PeekAt(start_index);
// Decompose and read the word count
OpcodeHeader header = SplitSpvOpCode(first_word);
if (header.words_count < 1U) {
return Result::SPV_ERROR_INTERNAL;
}
*words_count = static_cast<size_t>(header.words_count);
return Result::SPV_SUCCESS;
}
void OpcodeStream::Reset() {
module_stream_.clear();
offsets_table_.clear();
parse_result_ = Result::SPV_ERROR_INTERNAL;
}
Result OpcodeStream::ParseModule(const void *module_stream, size_t binary_size) {
assert(binary_size && module_stream);
// Make a copy of the data
const uint32_t *stream = static_cast<const uint32_t *>(module_stream);
module_stream_.assign(stream, stream + (binary_size / 4));
return ParseModuleInternal();
}
uint32_t OpcodeStream::PeekAt(size_t index) {
return module_stream_[index];
}
std::vector<uint32_t> OpcodeStream::EmitFilteredStream() const {
std::vector<uint32_t> new_stream;
// The new stream will roughly be the same size as the original one
new_stream.reserve(module_stream_.size());
for (std::vector<OpcodeOffset>::const_iterator oi = offsets_table_.begin();
oi != (offsets_table_.end() - 1);
oi++) {
// If there are pending Insert Before operations, emit those ones first
if (!oi->words_before_.empty()) {
new_stream.insert(new_stream.end(), oi->words_before_.begin(),
oi->words_before_.end());
}
// If the original instruction is not to be removed, emit it
if (!oi->remove_) {
new_stream.insert(
new_stream.end(),
module_stream_.begin() + oi->offset_,
module_stream_.begin() + ((oi + 1)->offset_));
}
// If there are pending Insert After operations, emit them at the end
if (!oi->words_after_.empty()) {
new_stream.insert(new_stream.end(), oi->words_after_.begin(),
oi->words_after_.end());
}
}
return new_stream;
}
OpcodeStream::iterator OpcodeStream::begin() {
return offsets_table_.begin();
}
OpcodeStream::iterator OpcodeStream::end() {
return offsets_table_.end();
}
OpcodeOffset::OpcodeOffset(size_t offset, const OpcodeStream &opcode_stream)
: offset_(offset),
words_before_(),
words_after_(),
remove_(false),
opcode_stream_(opcode_stream) {}
spv::Op OpcodeOffset::GetOpcode() const {
uint32_t header_word = opcode_stream_.module_stream()[offset_];
return static_cast<spv::Op>(SplitSpvOpCode(header_word).opcode);
}
void OpcodeOffset::InsertBefore(const uint32_t *instructions,
size_t words_count) {
assert(instructions && words_count);
words_before_.insert(
words_before_.begin(),
instructions,
instructions + words_count);
}
void OpcodeOffset::InsertAfter(const uint32_t *instructions,
size_t words_count) {
assert(instructions && words_count);
words_after_.insert(
words_after_.begin(),
instructions,
instructions + words_count);
}
void OpcodeOffset::Remove() {
remove_ = true;
}
} // namespace sut<|endoftext|>
|
<commit_before>/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001 Russell L. Smith. *
* *
* 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 (see the file LICENSE.TXT); if not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA. *
* *
*************************************************************************/
#include <stdio.h>
#include "ode/ode.h"
#include "drawstuff/drawstuff.h"
// select correct drawing functions
#ifdef dDOUBLE
#define dsDrawBox dsDrawBoxD
#define dsDrawSphere dsDrawSphereD
#define dsDrawCylinder dsDrawCylinderD
#define dsDrawCappedCylinder dsDrawCappedCylinderD
#endif
// some constants
#define LENGTH 0.7 // chassis length
#define WIDTH 0.5 // chassis width
#define HEIGHT 0.2 // chassis height
#define RADIUS 0.18 // wheel radius
#define STARTZ 0.5 // starting height of chassis
#define CMASS 1 // chassis mass
#define WMASS 0.2 // wheel mass
// dynamics and collision objects (chassis, 3 wheels, environment)
static dWorldID world;
static dSpaceID space;
static dBodyID body[4];
static dJointID joint[3]; // joint[0] is the front wheel
static dJointID dmotor,smotor; // front wheel drive & steering motors
static dJointGroupID contactgroup;
static dGeomID ground;
static dGeomID box[1];
static dGeomID sphere[3];
static dGeomID ground_box;
// things that the user controls
static dReal speed=0,steer=0; // user commands
// this is called by dSpaceCollide when two objects in space are
// potentially colliding.
static void nearCallback (void *data, dGeomID o1, dGeomID o2)
{
// only collide things with the ground
int g1 = (o1 == ground || o1 == ground_box);
int g2 = (o2 == ground || o2 == ground_box);
if (!(g1 ^ g2)) return;
dContact contact;
contact.surface.mode = 0;
contact.surface.mu = dInfinity;
if (dCollide (o1,o2,0,&contact.geom,sizeof(dContactGeom))) {
// if (o1==ground_box) printf ("foo 1\n");
// if (o2==ground_box) printf ("foo 2\n");
dJointID c = dJointCreateContact (world,contactgroup,&contact);
dJointAttach (c,dGeomGetBody(o1),dGeomGetBody(o2));
}
}
// start simulation - set viewpoint
static void start()
{
static float xyz[3] = {0.8317,-0.9817,0.8000};
static float hpr[3] = {121.0000,-27.5000,0.0000};
dsSetViewpoint (xyz,hpr);
}
// called when a key pressed
static void command (int cmd)
{
switch (cmd) {
case 'a': case 'A':
speed += 0.3;
break;
case 'z': case 'Z':
speed -= 0.3;
break;
case ',':
steer -= 0.2;
break;
case '.':
steer += 0.2;
break;
case ' ':
speed = 0;
steer = 0;
break;
}
}
// simulation loop
static void simLoop (int pause)
{
int i;
if (!pause) {
//dJointSetRMotorVel (dmotor,speed);
//dJointSetRMotorTmax (dmotor,0.1);
dJointSetHingeVel (joint[2],speed);
dJointSetHingeTmax (joint[2],0.1);
dJointSetRMotorVel (smotor,steer);
dJointSetRMotorTmax (smotor,0.1);
dSpaceCollide (space,0,&nearCallback);
dWorldStep (world,0.05);
// remove all contact joints
dJointGroupEmpty (contactgroup);
}
dsSetColor (0,1,1);
dsSetTexture (DS_WOOD);
dReal sides[3] = {LENGTH,WIDTH,HEIGHT};
dsDrawBox (dBodyGetPosition(body[0]),dBodyGetRotation(body[0]),sides);
dsSetColor (1,1,1);
for (i=1; i<=3; i++) dsDrawCylinder (dBodyGetPosition(body[i]),
dBodyGetRotation(body[i]),0.02,RADIUS);
/*
dVector3 ss;
dGeomBoxGetLengths (ground_box,ss);
dsDrawBox (dGeomGetPosition(ground_box),dGeomGetRotation(ground_box),ss);
*/
printf ("%.10f %.10f %.10f %.10f\n",
dJointGetHingeAngle (joint[1]),
dJointGetHingeAngle (joint[2]),
dJointGetHingeAngleRate (joint[1]),
dJointGetHingeAngleRate (joint[2]));
}
int main (int argc, char **argv)
{
int i;
dMass m;
// setup pointers to drawstuff callback functions
dsFunctions fn;
fn.version = DS_VERSION;
fn.start = &start;
fn.step = &simLoop;
fn.command = &command;
fn.stop = 0;
fn.path_to_textures = "../../drawstuff/textures";
// create world
world = dWorldCreate();
space = dSpaceCreate();
contactgroup = dJointGroupCreate (1000000);
dWorldSetGravity (world,0,0,-0.5);
ground = dCreatePlane (space,0,0,1,0);
// chassis body
body[0] = dBodyCreate (world);
dBodySetPosition (body[0],0,0,STARTZ);
dMassSetBox (&m,1,LENGTH,WIDTH,HEIGHT);
dMassAdjust (&m,CMASS);
dBodySetMass (body[0],&m);
box[0] = dCreateBox (space,LENGTH,WIDTH,HEIGHT);
dGeomSetBody (box[0],body[0]);
// wheel bodies
for (i=1; i<=3; i++) {
body[i] = dBodyCreate (world);
dQuaternion q;
dQFromAxisAndAngle (q,1,0,0,M_PI*0.5);
dBodySetQuaternion (body[i],q);
dMassSetSphere (&m,1,RADIUS);
dMassAdjust (&m,WMASS);
dBodySetMass (body[i],&m);
sphere[i-1] = dCreateSphere (space,RADIUS);
dGeomSetBody (sphere[i-1],body[i]);
}
dBodySetPosition (body[1],0.5*LENGTH,0,STARTZ-HEIGHT*0.5);
dBodySetPosition (body[2],-0.5*LENGTH, WIDTH*0.5,STARTZ-HEIGHT*0.5);
dBodySetPosition (body[3],-0.5*LENGTH,-WIDTH*0.5,STARTZ-HEIGHT*0.5);
// front wheel hinge
joint[0] = dJointCreateHinge2 (world,0);
dJointAttach (joint[0],body[0],body[1]);
const dReal *a = dBodyGetPosition (body[1]);
dJointSetHinge2Anchor (joint[0],a[0],a[1],a[2]);
dJointSetHinge2Axis1 (joint[0],0,0,1);
dJointSetHinge2Axis2 (joint[0],0,1,0);
// back wheel hinges
for (i=1; i<3; i++) {
joint[i] = dJointCreateHinge (world,0);
dJointAttach (joint[i],body[0],body[i+1]);
const dReal *a = dBodyGetPosition (body[i+1]);
dJointSetHingeAnchor (joint[i],a[0],a[1],a[2]);
dJointSetHingeAxis (joint[i],0,1,0);
}
// front wheel motors
//dmotor = dJointCreateRMotor (world,0);
//dJointAttach (dmotor,body[1],body[0]);
//dJointSetRMotorAxis (dmotor,0,1,0); // motor axis rel to 1st body
smotor = dJointCreateRMotor (world,0);
dJointAttach (smotor,body[0],body[1]);
dJointSetRMotorAxis (smotor,0,0,1); // motor axis rel to 1st body
// environment
/*
ground_box = dCreateBox (space,2,1.5,1);
dMatrix3 R;
dRFromAxisAndAngle (R,0,1,0,-0.15);
dGeomSetPosition (ground_box,2,0,-0.34);
dGeomSetRotation (ground_box,R);
*/
// run simulation
dsSimulationLoop (argc,argv,352,288,&fn);
dJointGroupDestroy (contactgroup);
dSpaceDestroy (space);
dWorldDestroy (world);
return 0;
}
<commit_msg>hmmmm.<commit_after>/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001 Russell L. Smith. *
* *
* 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 (see the file LICENSE.TXT); if not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA. *
* *
*************************************************************************/
#include <stdio.h>
#include "ode/ode.h"
#include "drawstuff/drawstuff.h"
// select correct drawing functions
#ifdef dDOUBLE
#define dsDrawBox dsDrawBoxD
#define dsDrawSphere dsDrawSphereD
#define dsDrawCylinder dsDrawCylinderD
#define dsDrawCappedCylinder dsDrawCappedCylinderD
#endif
// some constants
#define LENGTH 0.7 // chassis length
#define WIDTH 0.5 // chassis width
#define HEIGHT 0.2 // chassis height
#define RADIUS 0.18 // wheel radius
#define STARTZ 0.5 // starting height of chassis
#define CMASS 1 // chassis mass
#define WMASS 0.2 // wheel mass
// dynamics and collision objects (chassis, 3 wheels, environment)
static dWorldID world;
static dSpaceID space;
static dBodyID body[4];
static dJointID joint[3]; // joint[0] is the front wheel
static dJointGroupID contactgroup;
static dGeomID ground;
static dGeomID box[1];
static dGeomID sphere[3];
static dGeomID ground_box;
// things that the user controls
static dReal speed=0,steer=0; // user commands
// this is called by dSpaceCollide when two objects in space are
// potentially colliding.
static void nearCallback (void *data, dGeomID o1, dGeomID o2)
{
// only collide things with the ground
int g1 = (o1 == ground || o1 == ground_box);
int g2 = (o2 == ground || o2 == ground_box);
if (!(g1 ^ g2)) return;
dContact contact;
contact.surface.mode = 0;
contact.surface.mu = dInfinity;
if (dCollide (o1,o2,0,&contact.geom,sizeof(dContactGeom))) {
// if (o1==ground_box) printf ("foo 1\n");
// if (o2==ground_box) printf ("foo 2\n");
dJointID c = dJointCreateContact (world,contactgroup,&contact);
dJointAttach (c,dGeomGetBody(o1),dGeomGetBody(o2));
}
}
// start simulation - set viewpoint
static void start()
{
static float xyz[3] = {0.8317,-0.9817,0.8000};
static float hpr[3] = {121.0000,-27.5000,0.0000};
dsSetViewpoint (xyz,hpr);
}
// called when a key pressed
static void command (int cmd)
{
switch (cmd) {
case 'a': case 'A':
speed += 0.3;
break;
case 'z': case 'Z':
speed -= 0.3;
break;
case ',':
steer += 0.5;
break;
case '.':
steer -= 0.5;
break;
case ' ':
speed = 0;
steer = 0;
break;
}
}
// simulation loop
static void simLoop (int pause)
{
int i;
if (!pause) {
// motor
dJointSetHingeParam (joint[2],dParamVel,speed);
dJointSetHingeParam (joint[2],dParamFMax,0.1);
// steering
printf ("%.4f\n",dJointGetHinge2Angle1 (joint[0]));
dReal v = steer - dJointGetHinge2Angle1 (joint[0]);
if (v > 0.1) v = 0.1;
if (v < -0.1) v = -0.1;
v *= 10.0;
dJointSetHinge2Param1 (joint[0],dParamVel,v);
dJointSetHinge2Param1 (joint[0],dParamFMax,0.2);
dJointSetHinge2Param1 (joint[0],dParamLoStop,-0.75);
dJointSetHinge2Param1 (joint[0],dParamHiStop,0.75);
dJointSetHinge2Param1 (joint[0],dParamFudgeFactor,0.1);
dSpaceCollide (space,0,&nearCallback);
dWorldStep (world,0.05);
// remove all contact joints
dJointGroupEmpty (contactgroup);
}
dsSetColor (0,1,1);
dsSetTexture (DS_WOOD);
dReal sides[3] = {LENGTH,WIDTH,HEIGHT};
dsDrawBox (dBodyGetPosition(body[0]),dBodyGetRotation(body[0]),sides);
dsSetColor (1,1,1);
for (i=1; i<=3; i++) dsDrawCylinder (dBodyGetPosition(body[i]),
dBodyGetRotation(body[i]),0.02,RADIUS);
/*
dVector3 ss;
dGeomBoxGetLengths (ground_box,ss);
dsDrawBox (dGeomGetPosition(ground_box),dGeomGetRotation(ground_box),ss);
*/
/*
printf ("%.10f %.10f %.10f %.10f\n",
dJointGetHingeAngle (joint[1]),
dJointGetHingeAngle (joint[2]),
dJointGetHingeAngleRate (joint[1]),
dJointGetHingeAngleRate (joint[2]));
*/
}
int main (int argc, char **argv)
{
int i;
dMass m;
// setup pointers to drawstuff callback functions
dsFunctions fn;
fn.version = DS_VERSION;
fn.start = &start;
fn.step = &simLoop;
fn.command = &command;
fn.stop = 0;
fn.path_to_textures = "../../drawstuff/textures";
// create world
world = dWorldCreate();
space = dSpaceCreate();
contactgroup = dJointGroupCreate (1000000);
dWorldSetGravity (world,0,0,-0.5);
ground = dCreatePlane (space,0,0,1,0);
// chassis body
body[0] = dBodyCreate (world);
dBodySetPosition (body[0],0,0,STARTZ);
dMassSetBox (&m,1,LENGTH,WIDTH,HEIGHT);
dMassAdjust (&m,CMASS);
dBodySetMass (body[0],&m);
box[0] = dCreateBox (space,LENGTH,WIDTH,HEIGHT);
dGeomSetBody (box[0],body[0]);
// wheel bodies
for (i=1; i<=3; i++) {
body[i] = dBodyCreate (world);
dQuaternion q;
dQFromAxisAndAngle (q,1,0,0,M_PI*0.5);
dBodySetQuaternion (body[i],q);
dMassSetSphere (&m,1,RADIUS);
dMassAdjust (&m,WMASS);
dBodySetMass (body[i],&m);
sphere[i-1] = dCreateSphere (space,RADIUS);
dGeomSetBody (sphere[i-1],body[i]);
}
dBodySetPosition (body[1],0.5*LENGTH,0,STARTZ-HEIGHT*0.5);
dBodySetPosition (body[2],-0.5*LENGTH, WIDTH*0.5,STARTZ-HEIGHT*0.5);
dBodySetPosition (body[3],-0.5*LENGTH,-WIDTH*0.5,STARTZ-HEIGHT*0.5);
// front wheel hinge
joint[0] = dJointCreateHinge2 (world,0);
dJointAttach (joint[0],body[0],body[1]);
const dReal *a = dBodyGetPosition (body[1]);
dJointSetHinge2Anchor (joint[0],a[0],a[1],a[2]);
dJointSetHinge2Axis1 (joint[0],0,0,1);
dJointSetHinge2Axis2 (joint[0],0,1,0);
// back wheel hinges
for (i=1; i<3; i++) {
joint[i] = dJointCreateHinge (world,0);
dJointAttach (joint[i],body[0],body[i+1]);
const dReal *a = dBodyGetPosition (body[i+1]);
dJointSetHingeAnchor (joint[i],a[0],a[1],a[2]);
dJointSetHingeAxis (joint[i],0,1,0);
}
// environment
/*
ground_box = dCreateBox (space,2,1.5,1);
dMatrix3 R;
dRFromAxisAndAngle (R,0,1,0,-0.15);
dGeomSetPosition (ground_box,2,0,-0.34);
dGeomSetRotation (ground_box,R);
*/
// run simulation
dsSimulationLoop (argc,argv,352,288,&fn);
dJointGroupDestroy (contactgroup);
dSpaceDestroy (space);
dWorldDestroy (world);
return 0;
}
<|endoftext|>
|
<commit_before>// compilation
// $ g++ -std=c++11 main.cpp
// or
// $ clang++ -std=c++11 main.cpp
#include <iostream>
#include <fstream>
#include <array>
#include <vector>
#include <string>
#include <chrono>
#include <thread>
#include "pipeline.hpp"
typedef std::array<int, 4> Vector;
typedef std::array<std::array<int, 4>, 4> Matrix;
typedef std::vector<Vector> Vectors;
typedef std::vector<Matrix> Matrices;
Matrices readMatrices(const std::string& filename)
{
Matrices M;
std::ifstream input(filename);
unsigned int linTransCount;
input >> linTransCount;
for (size_t i = 0; i < linTransCount; i++)
{
Matrix m;
for (size_t i = 0; i < 4; i++) {
input >> m[i][0] >> m[i][1] >> m[i][2] >> m[i][3];
}
M.push_back(m);
}
input.close();
return M;
}
Vectors readVectors(const std::string& filename)
{
Vectors V;
std::ifstream input(filename);
unsigned int vectorCount;
input >> vectorCount;
for (size_t i = 0; i < vectorCount; i++)
{
Vector v;
input >> v[0] >> v[1] >> v[2];
v[3] = 1;
V.push_back(v);
}
input.close();
return V;
}
void writeVectors(const std::string& filename, Vectors& V)
{
std::ofstream output(filename);
for (auto const& v : V)
{
for (size_t i = 0; i < v.size() - 1; i++) {
output << v[i] << " ";
}
output << std::endl;
}
output.close();
}
Vector linTransform(const Matrix& m, const Vector& v)
{
Vector result;
for (size_t i = 0; i < v.size(); i++) {
result[i] = 0;
for (size_t j = 0; j < v.size(); j++) {
result[i] += m[i][j] * v[j];
}
}
return result;
}
void threadHandler(Pipeline<Vector>& input, Pipeline<Vector>& output, const Matrix& m, int vectorCount)
{
for (size_t i = 0; i < vectorCount; i++)
{
Vector v = input.pop();
std::cout << v[0] << v[1] << v[2];
Vector result = linTransform(m,v);
output.push(result);
}
}
void calculate(Vectors& V, Matrices& M)
{
std::vector<std::thread> threads;
std::vector<std::reference_wrapper<Pipeline<Vector>>> pipes;
Pipeline<Vector> firstPipe;
for (auto& v : V)
{
firstPipe.push(v);
}
pipes.push_back(std::ref(firstPipe));
for (size_t i = 0; i < M.size(); i++) {
Pipeline<Vector> p;
pipes.push_back(std::ref(p));
}
for (size_t i = 0; i < M.size(); i++) {
threads.push_back(std::thread(threadHandler, pipes[i], pipes[i + 1], M[i], V.size()));
}
for (auto& t : threads)
{
if (t.joinable())
{
t.join();
}
}
for (auto& v : V)
{
Vector result = pipes[pipes.size() - 1].get().pop();
v = result;
}
}
int main()
{
using namespace std::chrono;
Matrices M = readMatrices("tests/0/input_matrices.txt");
Vectors V = readVectors("tests/0/input_points.txt");
time_point<system_clock> t0, t1;
t0 = system_clock::now();
calculate(V, M);
t1 = system_clock::now();
std::cout << duration_cast<milliseconds>(t1 - t0).count() << "ms\n";
writeVectors("output.txt", V);
return 0;
}
<commit_msg>bead3: working prototype<commit_after>// compilation
// $ g++ -std=c++11 main.cpp
// or
// $ clang++ -std=c++11 main.cpp
#include <iostream>
#include <fstream>
#include <array>
#include <vector>
#include <string>
#include <chrono>
#include <thread>
#include "pipeline.hpp"
typedef std::array<int, 4> Vector;
typedef std::array<std::array<int, 4>, 4> Matrix;
typedef std::vector<Vector> Vectors;
typedef std::vector<Matrix> Matrices;
Matrices readMatrices(const std::string& filename)
{
Matrices M;
std::ifstream input(filename);
unsigned int linTransCount;
input >> linTransCount;
for (size_t i = 0; i < linTransCount; i++)
{
Matrix m;
for (size_t i = 0; i < 4; i++) {
input >> m[i][0] >> m[i][1] >> m[i][2] >> m[i][3];
}
M.push_back(m);
}
input.close();
return M;
}
Vectors readVectors(const std::string& filename)
{
Vectors V;
std::ifstream input(filename);
unsigned int vectorCount;
input >> vectorCount;
for (size_t i = 0; i < vectorCount; i++)
{
Vector v;
input >> v[0] >> v[1] >> v[2];
v[3] = 1;
V.push_back(v);
}
input.close();
return V;
}
void writeVectors(const std::string& filename, Vectors& V)
{
std::ofstream output(filename);
for (auto const& v : V)
{
for (size_t i = 0; i < v.size() - 1; i++) {
output << v[i] << " ";
}
output << std::endl;
}
output.close();
}
Vector linTransform(const Matrix& m, const Vector& v)
{
Vector result;
for (size_t i = 0; i < v.size(); i++) {
result[i] = 0;
for (size_t j = 0; j < v.size(); j++) {
result[i] += m[i][j] * v[j];
}
}
return result;
}
void threadHandler(Pipeline<Vector>& input, Pipeline<Vector>& output, const Matrix& m, int vectorCount)
{
for (size_t i = 0; i < vectorCount; i++)
{
Vector v = input.pop();
Vector result = linTransform(m,v);
output.push(result);
}
}
void calculate(Vectors& V, Matrices& M)
{
std::vector<std::thread> threads;
std::vector<Pipeline<Vector>> pipes(M.size() + 1);
for (size_t i = 0; i < M.size(); i++) {
threads.push_back(std::thread(threadHandler, std::ref(pipes[i]), std::ref(pipes[i + 1]), M[i], V.size()));
}
for (auto& v : V)
{
pipes[0].push(v);
}
for (auto& t : threads)
{
t.join();
}
for (auto& v : V)
{
Vector result = pipes[pipes.size() - 1].pop();
v = result;
}
}
int main()
{
using namespace std::chrono;
Matrices M = readMatrices("tests/0/input_matrices.txt");
Vectors V = readVectors("tests/0/input_points.txt");
time_point<system_clock> start, end;
start = system_clock::now();
calculate(V, M);
end = system_clock::now();
std::cout << duration_cast<milliseconds>(end - start).count() << "ms\n";
writeVectors("output.txt", V);
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Mihalcea.cc
*
* Implements the Rada Mihalcea word-sense disambiguation algorithm.
*
* Copyright (c) 2008 Linas Vepstas <linas@linas.org>
*/
#include "Mihalcea.h"
#include <stdio.h>
#include <opencog/atomspace/ForeachChaseLink.h>
#include <opencog/util/platform.h>
#include <opencog/nlp/wsd/MihalceaEdge.h>
#include <opencog/nlp/wsd/MihalceaLabel.h>
#include <opencog/nlp/wsd/ParseRank.h>
#include <opencog/nlp/wsd/SenseRank.h>
#include <opencog/nlp/wsd/ReportRank.h>
using namespace opencog;
#define DEBUG
Mihalcea::Mihalcea(void)
{
atom_space = NULL;
previous_parse = Handle::UNDEFINED;
}
Mihalcea::~Mihalcea()
{
atom_space = NULL;
}
void Mihalcea::set_atom_space(AtomSpace *as)
{
atom_space = as;
labeller.set_atom_space(as);
edger.set_atom_space(as);
thinner.set_atom_space(as);
}
bool Mihalcea::process_sentence(Handle h)
{
Handle top_parse = parse_ranker.get_top_ranked_parse(h);
parse_list.push_back(top_parse);
#ifdef DEBUG
printf("; Mihalcea::process_sentence parse %lx for sentence %lx\n", top_parse.value(), h.value());
#endif
// Attach senses to word instances
labeller.annotate_parse(top_parse);
// Create edges between sense pairs
edger.annotate_parse(top_parse);
// Tweak, based on parser markup
// nn_adjuster.adjust_parse(top_parse);
// Link sentences together, since presumably the next
// sentence deals with topics similar to the previous one.
if (Handle::UNDEFINED != previous_parse)
{
edger.annotate_parse_pair(previous_parse, top_parse);
// If there are any senses that are not attached to anything,
// get rid of them now.
thinner.prune_parse(previous_parse);
}
previous_parse = top_parse;
#define WINDOW_SIZE 3
// Create a short list of the last 3 sentences
// This is a sliding window of related words.
short_list.push_back(top_parse);
if (WINDOW_SIZE < short_list.size())
{
Handle earliest = short_list.front();
short_list.pop_front();
thinner.thin_parse(earliest, 0);
}
// THICKNESS is the number of senses that we leave attached to a
// given word. We don't want to make this too thin, since the
// graph algorithm will suck probability from the least likely
// and give it to the most likely. Getting this too thin can
// result in taking away too much from an otherwise decent
// alternative.
#define THICKNESS 4
if (WINDOW_SIZE == short_list.size())
{
// Solve the page-rank equations for the short list.
sense_ranker.rank_document(short_list);
Handle first = short_list.front();
thinner.thin_parse(first, THICKNESS);
}
return false;
}
bool Mihalcea::process_sentence_list(Handle h)
{
foreach_outgoing_handle(h, &Mihalcea::process_sentence, this);
// Solve the page-rank equations for the whole set of sentences.
// sense_ranker.rank_document(parse_list);
// No .. don't. Use the sliding-window mechanism, above.
// Finish up the sliding window processing.
// Treat the tail-end of the document in much the same way as the
// start or middle; we don't want to give undue weight to the tail.
while (0 < short_list.size())
{
Handle earliest = short_list.front();
short_list.pop_front();
// double-pass -- first with thickness, to thin senses,
// then with no thickness, to remove sim links.
thinner.thin_parse(earliest, THICKNESS);
// Solve the page-rank equations for the short list.
sense_ranker.rank_document(short_list);
thinner.thin_parse(earliest, 0);
}
// Report the results.
reporter.report_document(parse_list);
return false;
}
void Mihalcea::process_document(Handle h)
{
foreach_binary_link(h, REFERENCE_LINK, &Mihalcea::process_sentence_list, this);
}
<commit_msg>network solution bug fixes.<commit_after>/*
* Mihalcea.cc
*
* Implements the Rada Mihalcea word-sense disambiguation algorithm.
*
* Copyright (c) 2008 Linas Vepstas <linas@linas.org>
*/
#include "Mihalcea.h"
#include <stdio.h>
#include <opencog/atomspace/ForeachChaseLink.h>
#include <opencog/util/platform.h>
#include <opencog/nlp/wsd/MihalceaEdge.h>
#include <opencog/nlp/wsd/MihalceaLabel.h>
#include <opencog/nlp/wsd/ParseRank.h>
#include <opencog/nlp/wsd/SenseRank.h>
#include <opencog/nlp/wsd/ReportRank.h>
using namespace opencog;
#define DEBUG
Mihalcea::Mihalcea(void)
{
atom_space = NULL;
previous_parse = Handle::UNDEFINED;
}
Mihalcea::~Mihalcea()
{
atom_space = NULL;
}
void Mihalcea::set_atom_space(AtomSpace *as)
{
atom_space = as;
labeller.set_atom_space(as);
edger.set_atom_space(as);
thinner.set_atom_space(as);
}
bool Mihalcea::process_sentence(Handle h)
{
Handle top_parse = parse_ranker.get_top_ranked_parse(h);
parse_list.push_back(top_parse);
#ifdef DEBUG
printf("; Mihalcea::process_sentence parse %lx for sentence %lx\n", top_parse.value(), h.value());
#endif
// Attach senses to word instances
labeller.annotate_parse(top_parse);
// Create edges between sense pairs
edger.annotate_parse(top_parse);
// Tweak, based on parser markup
// nn_adjuster.adjust_parse(top_parse);
// Link sentences together, since presumably the next
// sentence deals with topics similar to the previous one.
if (Handle::UNDEFINED != previous_parse)
{
edger.annotate_parse_pair(previous_parse, top_parse);
// If there are any senses that are not attached to anything,
// get rid of them now.
thinner.prune_parse(previous_parse);
}
previous_parse = top_parse;
#define WINDOW_SIZE 3
// Create a short list of the last 3 sentences
// This is a sliding window of related words.
short_list.push_back(top_parse);
if (WINDOW_SIZE < short_list.size())
{
Handle earliest = short_list.front();
short_list.pop_front();
thinner.thin_parse(earliest, 0);
}
// THICKNESS is the number of senses that we leave attached to a
// given word. We don't want to make this too thin, since the
// graph algorithm will suck probability from the least likely
// and give it to the most likely. Getting this too thin can
// result in taking away too much from an otherwise decent
// alternative.
#define THICKNESS 4
if (WINDOW_SIZE-1 == short_list.size())
{
// Solve the page-rank equations for the short list.
sense_ranker.rank_document(short_list);
}
if (WINDOW_SIZE == short_list.size())
{
Handle first = short_list.front();
thinner.thin_parse(first, THICKNESS);
// Solve the page-rank equations for the short list.
sense_ranker.rank_document(short_list);
}
return false;
}
bool Mihalcea::process_sentence_list(Handle h)
{
short_list.clear();
foreach_outgoing_handle(h, &Mihalcea::process_sentence, this);
// Solve the page-rank equations for the whole set of sentences.
// sense_ranker.rank_document(parse_list);
// No .. don't. Use the sliding-window mechanism, above.
// Finish up the sliding window processing.
// Treat the tail-end of the document in much the same way as the
// start or middle; we don't want to give undue weight to the tail.
if (0 < short_list.size())
{
Handle earliest = short_list.front();
short_list.pop_front();
thinner.thin_parse(earliest, 0);
}
while (0 < short_list.size())
{
Handle earliest = short_list.front();
thinner.thin_parse(earliest, THICKNESS);
// Solve the page-rank equations for the short list.
sense_ranker.rank_document(short_list);
short_list.pop_front();
thinner.thin_parse(earliest, 0);
}
// Report the results.
reporter.report_document(parse_list);
return false;
}
void Mihalcea::process_document(Handle h)
{
foreach_binary_link(h, REFERENCE_LINK, &Mihalcea::process_sentence_list, this);
}
<|endoftext|>
|
<commit_before><commit_msg>use std::<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2011 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 "webkit/plugins/npapi/plugin_lib.h"
#include <dlfcn.h>
#if defined(OS_OPENBSD)
#include <sys/exec_elf.h>
#else
#include <elf.h>
#endif
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "base/eintr_wrapper.h"
#include "base/file_util.h"
#include "base/string_split.h"
#include "base/string_util.h"
#include "base/sys_string_conversions.h"
#include "base/utf_string_conversions.h"
#include "webkit/plugins/npapi/plugin_list.h"
// These headers must be included in this order to make the declaration gods
// happy.
#include "base/third_party/nspr/prcpucfg_linux.h"
namespace webkit {
namespace npapi {
namespace {
// Copied from nsplugindefs.h instead of including the file since it has a bunch
// of dependencies.
enum nsPluginVariable {
nsPluginVariable_NameString = 1,
nsPluginVariable_DescriptionString = 2
};
// Read the ELF header and return true if it is usable on
// the current architecture (e.g. 32-bit ELF on 32-bit build).
// Returns false on other errors as well.
bool ELFMatchesCurrentArchitecture(const FilePath& filename) {
// First make sure we can open the file and it is in fact, a regular file.
struct stat stat_buf;
// Open with O_NONBLOCK so we don't block on pipes.
int fd = open(filename.value().c_str(), O_RDONLY|O_NONBLOCK);
if (fd < 0)
return false;
bool ret = (fstat(fd, &stat_buf) >= 0 && S_ISREG(stat_buf.st_mode));
if (HANDLE_EINTR(close(fd)) < 0)
return false;
if (!ret)
return false;
const size_t kELFBufferSize = 5;
char buffer[kELFBufferSize];
if (!file_util::ReadFile(filename, buffer, kELFBufferSize))
return false;
if (buffer[0] != ELFMAG0 ||
buffer[1] != ELFMAG1 ||
buffer[2] != ELFMAG2 ||
buffer[3] != ELFMAG3) {
// Not an ELF file, perhaps?
return false;
}
int elf_class = buffer[EI_CLASS];
#if defined(ARCH_CPU_32_BITS)
if (elf_class == ELFCLASS32)
return true;
#elif defined(ARCH_CPU_64_BITS)
if (elf_class == ELFCLASS64)
return true;
#endif
return false;
}
// This structure matches enough of nspluginwrapper's NPW_PluginInfo
// for us to extract the real plugin path.
struct __attribute__((packed)) NSPluginWrapperInfo {
char ident[32]; // NSPluginWrapper magic identifier (includes version).
char path[PATH_MAX]; // Path to wrapped plugin.
};
// Test a plugin for whether it's been wrapped by NSPluginWrapper, and
// if so attempt to unwrap it. Pass in an opened plugin handle; on
// success, |dl| and |unwrapped_path| will be filled in with the newly
// opened plugin. On failure, params are left unmodified.
void UnwrapNSPluginWrapper(void **dl, FilePath* unwrapped_path) {
NSPluginWrapperInfo* info =
reinterpret_cast<NSPluginWrapperInfo*>(dlsym(*dl, "NPW_Plugin"));
if (!info)
return; // Not a NSPW plugin.
// Here we could check the NSPW ident field for the versioning
// information, but the path field is available in all versions
// anyway.
// Grab the path to the wrapped plugin. Just in case the structure
// format changes, protect against the path not being null-terminated.
char* path_end = static_cast<char*>(memchr(info->path, '\0',
sizeof(info->path)));
if (!path_end)
path_end = info->path + sizeof(info->path);
FilePath path = FilePath(std::string(info->path, path_end - info->path));
if (!ELFMatchesCurrentArchitecture(path)) {
LOG(WARNING) << path.value() << " is nspluginwrapper wrapping a "
<< "plugin for a different architecture; it will "
<< "work better if you instead use a native plugin.";
return;
}
std::string error;
void* newdl = base::LoadNativeLibrary(path, &error);
if (!newdl) {
// We couldn't load the unwrapped plugin for some reason, despite
// being able to load the wrapped one. Just use the wrapped one.
LOG_IF(ERROR, PluginList::DebugPluginLoading())
<< "Could not use unwrapped nspluginwrapper plugin "
<< unwrapped_path->value() << " (" << error << "), "
<< "using the wrapped one.";
return;
}
// Unload the wrapped plugin, and use the wrapped plugin instead.
LOG_IF(ERROR, PluginList::DebugPluginLoading())
<< "Using unwrapped version " << unwrapped_path->value()
<< " of nspluginwrapper-wrapped plugin.";
base::UnloadNativeLibrary(*dl);
*dl = newdl;
*unwrapped_path = path;
}
} // namespace
bool PluginLib::ReadWebPluginInfo(const FilePath& filename,
WebPluginInfo* info) {
// The file to reference is:
// http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginsDirUnix.cpp
// Skip files that aren't appropriate for our architecture.
if (!ELFMatchesCurrentArchitecture(filename)) {
LOG_IF(ERROR, PluginList::DebugPluginLoading())
<< "Skipping plugin " << filename.value()
<< " because it doesn't match the current architecture.";
return false;
}
std::string error;
void* dl = base::LoadNativeLibrary(filename, &error);
if (!dl) {
LOG_IF(ERROR, PluginList::DebugPluginLoading())
<< "While reading plugin info, unable to load library "
<< filename.value() << " (" << error << "), skipping.";
return false;
}
info->path = filename;
// Attempt to swap in the wrapped plugin if this is nspluginwrapper.
UnwrapNSPluginWrapper(&dl, &info->path);
// See comments in plugin_lib_mac regarding this symbol.
typedef const char* (*NP_GetMimeDescriptionType)();
NP_GetMimeDescriptionType NP_GetMIMEDescription =
reinterpret_cast<NP_GetMimeDescriptionType>(
dlsym(dl, "NP_GetMIMEDescription"));
const char* mime_description = NULL;
if (NP_GetMIMEDescription)
mime_description = NP_GetMIMEDescription();
if (mime_description)
ParseMIMEDescription(mime_description, &info->mime_types);
// The plugin name and description live behind NP_GetValue calls.
typedef NPError (*NP_GetValueType)(void* unused,
nsPluginVariable variable,
void* value_out);
NP_GetValueType NP_GetValue =
reinterpret_cast<NP_GetValueType>(dlsym(dl, "NP_GetValue"));
if (NP_GetValue) {
const char* name = NULL;
NP_GetValue(NULL, nsPluginVariable_NameString, &name);
if (name) {
info->name = UTF8ToUTF16(name);
ExtractVersionString(name, info);
}
const char* description = NULL;
NP_GetValue(NULL, nsPluginVariable_DescriptionString, &description);
if (description) {
info->desc = UTF8ToUTF16(description);
if (info->version.empty())
ExtractVersionString(description, info);
}
LOG_IF(ERROR, PluginList::DebugPluginLoading())
<< "Got info for plugin " << filename.value()
<< " Name = \"" << UTF16ToUTF8(info->name)
<< "\", Description = \"" << UTF16ToUTF8(info->desc)
<< "\", Version = \"" << UTF16ToUTF8(info->version)
<< "\".";
} else {
LOG_IF(ERROR, PluginList::DebugPluginLoading())
<< "Plugin " << filename.value()
<< " has no GetValue() and probably won't work.";
}
// Intentionally not unloading the plugin here, it can lead to crashes.
return true;
}
// static
void PluginLib::ParseMIMEDescription(
const std::string& description,
std::vector<WebPluginMimeType>* mime_types) {
// We parse the description here into WebPluginMimeType structures.
// Naively from the NPAPI docs you'd think you could use
// string-splitting, but the Firefox parser turns out to do something
// different: find the first colon, then the second, then a semi.
//
// See ParsePluginMimeDescription near
// http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginsDirUtils.h#53
std::string::size_type ofs = 0;
for (;;) {
WebPluginMimeType mime_type;
std::string::size_type end = description.find(':', ofs);
if (end == std::string::npos)
break;
mime_type.mime_type = description.substr(ofs, end - ofs);
ofs = end + 1;
end = description.find(':', ofs);
if (end == std::string::npos)
break;
const std::string extensions = description.substr(ofs, end - ofs);
base::SplitString(extensions, ',', &mime_type.file_extensions);
ofs = end + 1;
end = description.find(';', ofs);
// It's ok for end to run off the string here. If there's no
// trailing semicolon we consume the remainder of the string.
if (end != std::string::npos) {
mime_type.description = UTF8ToUTF16(description.substr(ofs, end - ofs));
} else {
mime_type.description = UTF8ToUTF16(description.substr(ofs));
}
mime_types->push_back(mime_type);
if (end == std::string::npos)
break;
ofs = end + 1;
}
}
// static
void PluginLib::ExtractVersionString(const std::string& desc,
WebPluginInfo* info) {
// This matching works by extracting a version substring, along the lines of:
// No postfix: second match in .*<prefix>.*$
// With postfix: second match .*<prefix>.*<postfix>
static const struct {
const char* kPrefix;
const char* kPostfix;
} kPrePostFixes[] = {
{ "Shockwave Flash ", 0 },
{ "Java(TM) Plug-in ", 0 },
{ "(using IcedTea-Web ", " " },
{ 0, 0 }
};
std::string version;
for (size_t i = 0; kPrePostFixes[i].kPrefix; ++i) {
size_t pos;
if ((pos = desc.find(kPrePostFixes[i].kPrefix)) != std::string::npos) {
version = desc.substr(pos + strlen(kPrePostFixes[i].kPrefix));
pos = std::string::npos;
if (kPrePostFixes[i].kPostfix)
pos = version.find(kPrePostFixes[i].kPostfix);
if (pos != std::string::npos)
version = version.substr(0, pos);
break;
}
}
if (!version.empty()) {
info->version = UTF8ToUTF16(version);
}
}
} // namespace npapi
} // namespace webkit
<commit_msg>Don't load plug-ins with no MIME description on Linux.<commit_after>// Copyright (c) 2011 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 "webkit/plugins/npapi/plugin_lib.h"
#include <dlfcn.h>
#if defined(OS_OPENBSD)
#include <sys/exec_elf.h>
#else
#include <elf.h>
#endif
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "base/eintr_wrapper.h"
#include "base/file_util.h"
#include "base/string_split.h"
#include "base/string_util.h"
#include "base/sys_string_conversions.h"
#include "base/utf_string_conversions.h"
#include "webkit/plugins/npapi/plugin_list.h"
// These headers must be included in this order to make the declaration gods
// happy.
#include "base/third_party/nspr/prcpucfg_linux.h"
namespace webkit {
namespace npapi {
namespace {
// Copied from nsplugindefs.h instead of including the file since it has a bunch
// of dependencies.
enum nsPluginVariable {
nsPluginVariable_NameString = 1,
nsPluginVariable_DescriptionString = 2
};
// Read the ELF header and return true if it is usable on
// the current architecture (e.g. 32-bit ELF on 32-bit build).
// Returns false on other errors as well.
bool ELFMatchesCurrentArchitecture(const FilePath& filename) {
// First make sure we can open the file and it is in fact, a regular file.
struct stat stat_buf;
// Open with O_NONBLOCK so we don't block on pipes.
int fd = open(filename.value().c_str(), O_RDONLY|O_NONBLOCK);
if (fd < 0)
return false;
bool ret = (fstat(fd, &stat_buf) >= 0 && S_ISREG(stat_buf.st_mode));
if (HANDLE_EINTR(close(fd)) < 0)
return false;
if (!ret)
return false;
const size_t kELFBufferSize = 5;
char buffer[kELFBufferSize];
if (!file_util::ReadFile(filename, buffer, kELFBufferSize))
return false;
if (buffer[0] != ELFMAG0 ||
buffer[1] != ELFMAG1 ||
buffer[2] != ELFMAG2 ||
buffer[3] != ELFMAG3) {
// Not an ELF file, perhaps?
return false;
}
int elf_class = buffer[EI_CLASS];
#if defined(ARCH_CPU_32_BITS)
if (elf_class == ELFCLASS32)
return true;
#elif defined(ARCH_CPU_64_BITS)
if (elf_class == ELFCLASS64)
return true;
#endif
return false;
}
// This structure matches enough of nspluginwrapper's NPW_PluginInfo
// for us to extract the real plugin path.
struct __attribute__((packed)) NSPluginWrapperInfo {
char ident[32]; // NSPluginWrapper magic identifier (includes version).
char path[PATH_MAX]; // Path to wrapped plugin.
};
// Test a plugin for whether it's been wrapped by NSPluginWrapper, and
// if so attempt to unwrap it. Pass in an opened plugin handle; on
// success, |dl| and |unwrapped_path| will be filled in with the newly
// opened plugin. On failure, params are left unmodified.
void UnwrapNSPluginWrapper(void **dl, FilePath* unwrapped_path) {
NSPluginWrapperInfo* info =
reinterpret_cast<NSPluginWrapperInfo*>(dlsym(*dl, "NPW_Plugin"));
if (!info)
return; // Not a NSPW plugin.
// Here we could check the NSPW ident field for the versioning
// information, but the path field is available in all versions
// anyway.
// Grab the path to the wrapped plugin. Just in case the structure
// format changes, protect against the path not being null-terminated.
char* path_end = static_cast<char*>(memchr(info->path, '\0',
sizeof(info->path)));
if (!path_end)
path_end = info->path + sizeof(info->path);
FilePath path = FilePath(std::string(info->path, path_end - info->path));
if (!ELFMatchesCurrentArchitecture(path)) {
LOG(WARNING) << path.value() << " is nspluginwrapper wrapping a "
<< "plugin for a different architecture; it will "
<< "work better if you instead use a native plugin.";
return;
}
std::string error;
void* newdl = base::LoadNativeLibrary(path, &error);
if (!newdl) {
// We couldn't load the unwrapped plugin for some reason, despite
// being able to load the wrapped one. Just use the wrapped one.
LOG_IF(ERROR, PluginList::DebugPluginLoading())
<< "Could not use unwrapped nspluginwrapper plugin "
<< unwrapped_path->value() << " (" << error << "), "
<< "using the wrapped one.";
return;
}
// Unload the wrapped plugin, and use the wrapped plugin instead.
LOG_IF(ERROR, PluginList::DebugPluginLoading())
<< "Using unwrapped version " << unwrapped_path->value()
<< " of nspluginwrapper-wrapped plugin.";
base::UnloadNativeLibrary(*dl);
*dl = newdl;
*unwrapped_path = path;
}
} // namespace
bool PluginLib::ReadWebPluginInfo(const FilePath& filename,
WebPluginInfo* info) {
// The file to reference is:
// http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginsDirUnix.cpp
// Skip files that aren't appropriate for our architecture.
if (!ELFMatchesCurrentArchitecture(filename)) {
LOG_IF(ERROR, PluginList::DebugPluginLoading())
<< "Skipping plugin " << filename.value()
<< " because it doesn't match the current architecture.";
return false;
}
std::string error;
void* dl = base::LoadNativeLibrary(filename, &error);
if (!dl) {
LOG_IF(ERROR, PluginList::DebugPluginLoading())
<< "While reading plugin info, unable to load library "
<< filename.value() << " (" << error << "), skipping.";
return false;
}
info->path = filename;
// Attempt to swap in the wrapped plugin if this is nspluginwrapper.
UnwrapNSPluginWrapper(&dl, &info->path);
// See comments in plugin_lib_mac regarding this symbol.
typedef const char* (*NP_GetMimeDescriptionType)();
NP_GetMimeDescriptionType NP_GetMIMEDescription =
reinterpret_cast<NP_GetMimeDescriptionType>(
dlsym(dl, "NP_GetMIMEDescription"));
const char* mime_description = NULL;
if (!NP_GetMIMEDescription) {
LOG_IF(ERROR, PluginList::DebugPluginLoading())
<< "Plugin " << filename.value() << " doesn't have a "
<< "NP_GetMIMEDescription symbol";
return false;
}
mime_description = NP_GetMIMEDescription();
if (!mime_description) {
LOG_IF(ERROR, PluginList::DebugPluginLoading())
<< "MIME description for " << filename.value() << " is empty";
return false;
}
ParseMIMEDescription(mime_description, &info->mime_types);
// The plugin name and description live behind NP_GetValue calls.
typedef NPError (*NP_GetValueType)(void* unused,
nsPluginVariable variable,
void* value_out);
NP_GetValueType NP_GetValue =
reinterpret_cast<NP_GetValueType>(dlsym(dl, "NP_GetValue"));
if (NP_GetValue) {
const char* name = NULL;
NP_GetValue(NULL, nsPluginVariable_NameString, &name);
if (name) {
info->name = UTF8ToUTF16(name);
ExtractVersionString(name, info);
}
const char* description = NULL;
NP_GetValue(NULL, nsPluginVariable_DescriptionString, &description);
if (description) {
info->desc = UTF8ToUTF16(description);
if (info->version.empty())
ExtractVersionString(description, info);
}
LOG_IF(ERROR, PluginList::DebugPluginLoading())
<< "Got info for plugin " << filename.value()
<< " Name = \"" << UTF16ToUTF8(info->name)
<< "\", Description = \"" << UTF16ToUTF8(info->desc)
<< "\", Version = \"" << UTF16ToUTF8(info->version)
<< "\".";
} else {
LOG_IF(ERROR, PluginList::DebugPluginLoading())
<< "Plugin " << filename.value()
<< " has no GetValue() and probably won't work.";
}
// Intentionally not unloading the plugin here, it can lead to crashes.
return true;
}
// static
void PluginLib::ParseMIMEDescription(
const std::string& description,
std::vector<WebPluginMimeType>* mime_types) {
// We parse the description here into WebPluginMimeType structures.
// Naively from the NPAPI docs you'd think you could use
// string-splitting, but the Firefox parser turns out to do something
// different: find the first colon, then the second, then a semi.
//
// See ParsePluginMimeDescription near
// http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginsDirUtils.h#53
std::string::size_type ofs = 0;
for (;;) {
WebPluginMimeType mime_type;
std::string::size_type end = description.find(':', ofs);
if (end == std::string::npos)
break;
mime_type.mime_type = description.substr(ofs, end - ofs);
ofs = end + 1;
end = description.find(':', ofs);
if (end == std::string::npos)
break;
const std::string extensions = description.substr(ofs, end - ofs);
base::SplitString(extensions, ',', &mime_type.file_extensions);
ofs = end + 1;
end = description.find(';', ofs);
// It's ok for end to run off the string here. If there's no
// trailing semicolon we consume the remainder of the string.
if (end != std::string::npos) {
mime_type.description = UTF8ToUTF16(description.substr(ofs, end - ofs));
} else {
mime_type.description = UTF8ToUTF16(description.substr(ofs));
}
mime_types->push_back(mime_type);
if (end == std::string::npos)
break;
ofs = end + 1;
}
}
// static
void PluginLib::ExtractVersionString(const std::string& desc,
WebPluginInfo* info) {
// This matching works by extracting a version substring, along the lines of:
// No postfix: second match in .*<prefix>.*$
// With postfix: second match .*<prefix>.*<postfix>
static const struct {
const char* kPrefix;
const char* kPostfix;
} kPrePostFixes[] = {
{ "Shockwave Flash ", 0 },
{ "Java(TM) Plug-in ", 0 },
{ "(using IcedTea-Web ", " " },
{ 0, 0 }
};
std::string version;
for (size_t i = 0; kPrePostFixes[i].kPrefix; ++i) {
size_t pos;
if ((pos = desc.find(kPrePostFixes[i].kPrefix)) != std::string::npos) {
version = desc.substr(pos + strlen(kPrePostFixes[i].kPrefix));
pos = std::string::npos;
if (kPrePostFixes[i].kPostfix)
pos = version.find(kPrePostFixes[i].kPostfix);
if (pos != std::string::npos)
version = version.substr(0, pos);
break;
}
}
if (!version.empty()) {
info->version = UTF8ToUTF16(version);
}
}
} // namespace npapi
} // namespace webkit
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////
//
// DAGON - An Adventure Game Engine
// Copyright (c) 2011-2013 Senscape s.r.l.
// All rights reserved.
//
// 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/.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <cstdarg>
#include <cstdio>
#include "Config.h"
#include "Font.h"
#include "Log.h"
////////////////////////////////////////////////////////////
// Implementation - Constructor
////////////////////////////////////////////////////////////
Font::Font() :
config(Config::instance()),
log(Log::instance())
{
this->setType(DGObjectFont);
}
////////////////////////////////////////////////////////////
// Implementation
////////////////////////////////////////////////////////////
void Font::clear() {
if (_isLoaded)
glDeleteTextures(kMaxChars, _textures);
}
bool Font::isLoaded() {
return _isLoaded;
}
void Font::print(int x, int y, const std::string &text, ...) {
if (!text.empty() && _isLoaded) {
char buffer[kMaxFeedLength];
va_list ap;
va_start(ap, text);
int length = vsnprintf(buffer, kMaxFeedLength, text.c_str(), ap);
va_end(ap);
glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TRANSFORM_BIT);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPushMatrix();
glTranslatef(x, y, 0);
for (const char* c = buffer; length > 0; c++, length--) {
int ch = *c;
GLfloat texCoords[] = { 0, 0, 0, _glyph[ch].y,
_glyph[ch].x, _glyph[ch].y, _glyph[ch].x, 0 };
GLshort coords[] = { 0, 0, 0, _glyph[ch].rows,
_glyph[ch].width, _glyph[ch].rows, _glyph[ch].width, 0 };
glBindTexture(GL_TEXTURE_2D, _textures[ch]);
glTranslatef(static_cast<GLfloat>(_glyph[ch].left), 0, 0);
glPushMatrix();
glTranslatef(0, -static_cast<GLfloat>(_glyph[ch].top) + _height, 0);
glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
glVertexPointer(2, GL_SHORT, 0, coords);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glPopMatrix();
glTranslatef(static_cast<GLfloat>(_glyph[ch].advance >> 6), 0, 0);
}
glPopMatrix();
glPopAttrib();
}
}
// FIXME: This is a repeated method from RenderManager --
// it would be best to avoid this.
void Font::setColor(int color) {
uint32_t aux = color;
uint8_t b = (aux & 0x000000ff);
uint8_t g = (aux & 0x0000ff00) >> 8;
uint8_t r = (aux & 0x00ff0000) >> 16;
uint8_t a = (aux & 0xff000000) >> 24;
glColor4f(r/255.0, g/255.0, b/255.0, a/255.0);
}
void Font::setDefault(unsigned int heightOfFont) {
FT_Face face;
if (FT_New_Memory_Face(*_library, kFontData, kSizeOfFontData, 0, &face)) {
log.error(kModFont, "%s", kString15005);
return;
}
_height = heightOfFont;
_loadFont(face);
FT_Done_Face(face);
}
void Font::setLibrary(FT_Library* library) {
_library = library;
}
void Font::setResource(const std::string &fromFileName,
unsigned int heightOfFont) {
FT_Face face;
if (FT_New_Face(*_library,
config.path(kPathResources, fromFileName,
DGObjectFont).c_str(),
0, &face)) {
log.error(kModFont, "%s: %s", kString15004, fromFileName.c_str());
return;
}
_height = heightOfFont;
_loadFont(face);
FT_Done_Face(face);
}
////////////////////////////////////////////////////////////
// Implementation - Private methods
////////////////////////////////////////////////////////////
void Font::_loadFont(FT_Face &face) {
FT_Set_Char_Size(face, _height << 6, _height << 6, 96, 96);
glGenTextures(kMaxChars, _textures);
for (unsigned char ch = 0; ch < kMaxChars; ch++) {
if (FT_Load_Glyph(face, FT_Get_Char_Index(face, ch), FT_LOAD_DEFAULT)) {
log.error(kModFont, "%s: %c", kString15006, ch);
return;
}
FT_Glyph glyph;
if (FT_Get_Glyph(face->glyph, &glyph)) {
log.error(kModFont, "%s: %c", kString15007, ch);
return;
}
FT_Glyph_To_Bitmap(&glyph, ft_render_mode_normal, 0, 1);
FT_BitmapGlyph bitmapGlyph = (FT_BitmapGlyph)glyph;
FT_Bitmap bitmap = bitmapGlyph->bitmap;
int width = _next(bitmap.width);
int height = _next(bitmap.rows);
// FIXME: Is there a sizeof() missing here?
GLubyte* expandedData = (GLubyte*)malloc(2 * width * height);
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
expandedData[2 * (i + j * width)] =
expandedData[2 * (i + j * width) + 1] =
(i >= bitmap.width || j >= bitmap.rows) ?
0 : bitmap.buffer[i + bitmap.width * j];
}
}
_glyph[ch].x = static_cast<float>(bitmap.width) / static_cast<float>(width);
_glyph[ch].y = static_cast<float>(bitmap.rows) / static_cast<float>(height);
_glyph[ch].width = bitmap.width;
_glyph[ch].rows = bitmap.rows;
_glyph[ch].left = bitmapGlyph->left;
_glyph[ch].top = bitmapGlyph->top;
_glyph[ch].advance = face->glyph->advance.x;
glBindTexture(GL_TEXTURE_2D, _textures[ch]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height,
0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, expandedData);
free(expandedData);
}
_isLoaded = true;
}
int Font::_next(int a) {
int rval = 1;
while (rval < a) rval <<= 1;
return rval;
}
<commit_msg>Safer loading of fonts.<commit_after>////////////////////////////////////////////////////////////
//
// DAGON - An Adventure Game Engine
// Copyright (c) 2011-2013 Senscape s.r.l.
// All rights reserved.
//
// 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/.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <cstdarg>
#include <cstdio>
#include "Config.h"
#include "Font.h"
#include "Log.h"
////////////////////////////////////////////////////////////
// Implementation - Constructor
////////////////////////////////////////////////////////////
Font::Font() :
config(Config::instance()),
log(Log::instance())
{
this->setType(DGObjectFont);
}
////////////////////////////////////////////////////////////
// Implementation
////////////////////////////////////////////////////////////
void Font::clear() {
if (_isLoaded)
glDeleteTextures(kMaxChars, _textures);
}
bool Font::isLoaded() {
return _isLoaded;
}
void Font::print(int x, int y, const std::string &text, ...) {
if (!text.empty() && _isLoaded) {
char buffer[kMaxFeedLength];
va_list ap;
va_start(ap, text);
int length = vsnprintf(buffer, kMaxFeedLength, text.c_str(), ap);
va_end(ap);
glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TRANSFORM_BIT);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPushMatrix();
glTranslatef(x, y, 0);
for (const char* c = buffer; length > 0; c++, length--) {
int ch = *c;
GLfloat texCoords[] = { 0, 0, 0, _glyph[ch].y,
_glyph[ch].x, _glyph[ch].y, _glyph[ch].x, 0 };
GLshort coords[] = { 0, 0, 0, _glyph[ch].rows,
_glyph[ch].width, _glyph[ch].rows, _glyph[ch].width, 0 };
glBindTexture(GL_TEXTURE_2D, _textures[ch]);
glTranslatef(static_cast<GLfloat>(_glyph[ch].left), 0, 0);
glPushMatrix();
glTranslatef(0, -static_cast<GLfloat>(_glyph[ch].top) + _height, 0);
glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
glVertexPointer(2, GL_SHORT, 0, coords);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glPopMatrix();
glTranslatef(static_cast<GLfloat>(_glyph[ch].advance >> 6), 0, 0);
}
glPopMatrix();
glPopAttrib();
}
}
// FIXME: This is a repeated method from RenderManager --
// it would be best to avoid this.
void Font::setColor(int color) {
uint32_t aux = color;
uint8_t b = (aux & 0x000000ff);
uint8_t g = (aux & 0x0000ff00) >> 8;
uint8_t r = (aux & 0x00ff0000) >> 16;
uint8_t a = (aux & 0xff000000) >> 24;
glColor4f(r/255.0, g/255.0, b/255.0, a/255.0);
}
void Font::setDefault(unsigned int heightOfFont) {
FT_Face face;
if (FT_New_Memory_Face(*_library, kFontData, kSizeOfFontData, 0, &face)) {
log.error(kModFont, "%s", kString15005);
return;
}
_height = heightOfFont;
_loadFont(face);
FT_Done_Face(face);
}
void Font::setLibrary(FT_Library* library) {
_library = library;
}
void Font::setResource(const std::string &fromFileName,
unsigned int heightOfFont) {
FT_Face face;
if (FT_New_Face(*_library,
config.path(kPathResources, fromFileName,
DGObjectFont).c_str(),
0, &face)) {
log.error(kModFont, "%s: %s", kString15004, fromFileName.c_str());
return;
}
_height = heightOfFont;
_loadFont(face);
FT_Done_Face(face);
}
////////////////////////////////////////////////////////////
// Implementation - Private methods
////////////////////////////////////////////////////////////
void Font::_loadFont(FT_Face &face) {
FT_Set_Char_Size(face, _height << 6, _height << 6, 96, 96);
glGenTextures(kMaxChars, _textures);
for (unsigned char ch = 0; ch < kMaxChars; ch++) {
if (FT_Load_Glyph(face, FT_Get_Char_Index(face, ch), FT_LOAD_DEFAULT)) {
log.error(kModFont, "%s: %c", kString15006, ch);
return;
}
FT_Glyph glyph;
if (FT_Get_Glyph(face->glyph, &glyph)) {
log.error(kModFont, "%s: %c", kString15007, ch);
return;
}
FT_Glyph_To_Bitmap(&glyph, ft_render_mode_normal, 0, 1);
FT_BitmapGlyph bitmapGlyph = (FT_BitmapGlyph)glyph;
FT_Bitmap bitmap = bitmapGlyph->bitmap;
int width = _next(bitmap.width);
int height = _next(bitmap.rows);
GLubyte expandedData[2 * width * height];
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
expandedData[2 * (i + j * width)] =
expandedData[2 * (i + j * width) + 1] =
(i >= bitmap.width || j >= bitmap.rows) ?
0 : bitmap.buffer[i + bitmap.width * j];
}
}
_glyph[ch].x = static_cast<float>(bitmap.width) / static_cast<float>(width);
_glyph[ch].y = static_cast<float>(bitmap.rows) / static_cast<float>(height);
_glyph[ch].width = bitmap.width;
_glyph[ch].rows = bitmap.rows;
_glyph[ch].left = bitmapGlyph->left;
_glyph[ch].top = bitmapGlyph->top;
_glyph[ch].advance = face->glyph->advance.x;
glBindTexture(GL_TEXTURE_2D, _textures[ch]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, 2, width, height, 0,
GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, expandedData);
}
_isLoaded = true;
}
int Font::_next(int a) {
int rval = 1;
while (rval < a) rval <<= 1;
return rval;
}
<|endoftext|>
|
<commit_before>#include "Bubblewrap/Base/Game.hpp"
#include "Bubblewrap/Managers/Container.hpp"
#include "Bubblewrap/Render/Window.hpp"
#include "Bubblewrap/Render/Types.hpp"
#include "GaPaddle.hpp"
#include "GaPong.hpp"
#include "GaTextController.hpp"
#include "GaLevel.hpp"
#include "Bubblewrap/Events/Event.hpp"
#include "Bubblewrap/Registers/BubblewrapSfmlGraphicsRegister.hpp"
#include "Bubblewrap/Registers/BubblewrapSfmlSoundRegister.hpp"
#include "Bubblewrap/Math/Bounds1.hpp"
#include "Bubblewrap/Math/Bounds2.hpp"
#include "Bubblewrap/Math/Bounds3.hpp"
int main()
{
Bubblewrap::Math::Bounds1f test( 0.0f, 1.0f );
Bubblewrap::Math::Bounds2f test1( 0.0f, 1.0f, 1.0f, 3.0f );
Bubblewrap::Math::Bounds3f test2( 0.0f, 1.0f, 1.0f, 2.0f, -1.0f, 0.0f );
Bubblewrap::Render::Colour Colour("255 255 255 128");
Bubblewrap::Game::GameSettings settings;
settings.WindowCount_ = 1;
settings.WindowSettings_ = new Bubblewrap::Render::Window::WindowSettings[ 2 ];
settings.WindowSettings_[ 0 ].Width_ = 800;
settings.WindowSettings_[ 0 ].Height_ = 600;
settings.WindowSettings_[ 0 ].Title_ = "POTATO";
settings.WindowSettings_[ 0 ].Name_ = "Main";
settings.Registers_.push_back( Bubblewrap::Registers::SfmlGraphicsRegister::Register );
settings.Registers_.push_back( Bubblewrap::Registers::SfmlSoundRegister::Register );
settings.Resources_.push_back( "textures" );
settings.TypeRegistration_ = ( [ ]( Bubblewrap::Base::ObjectRegister* Register )
{
Register->RegisterCreator( "GaPaddle", GaPaddle::Create, GaPaddle::CopyDef );
Register->RegisterCreator( "GaPong", GaPong::Create, GaPong::CopyDef );
Register->RegisterCreator( "GaLevel", GaLevel::Create, GaLevel::CopyDef );
Register->RegisterCreator( "GaTextController", GaTextController::Create, GaTextController::CopyDef );
} );
settings.Packages_.push_back( "basics.json" );
settings.BaseObject_ = "basics:LevelEntity";
Bubblewrap::Game::Game Game;
Game.Run( settings );
}<commit_msg>Updated to cover some refactoring of the register functions in bubblewrap_sfml<commit_after>#include "Bubblewrap/Base/Game.hpp"
#include "Bubblewrap/Managers/Container.hpp"
#include "Bubblewrap/Render/Window.hpp"
#include "Bubblewrap/Render/Types.hpp"
#include "GaPaddle.hpp"
#include "GaPong.hpp"
#include "GaTextController.hpp"
#include "GaLevel.hpp"
#include "Bubblewrap/Events/Event.hpp"
#include "Bubblewrap/Registers/SfmlRegisters.hpp"
#include "Bubblewrap/Math/Bounds1.hpp"
#include "Bubblewrap/Math/Bounds2.hpp"
#include "Bubblewrap/Math/Bounds3.hpp"
int main()
{
Bubblewrap::Math::Bounds1f test( 0.0f, 1.0f );
Bubblewrap::Math::Bounds2f test1( 0.0f, 1.0f, 1.0f, 3.0f );
Bubblewrap::Math::Bounds3f test2( 0.0f, 1.0f, 1.0f, 2.0f, -1.0f, 0.0f );
Bubblewrap::Render::Colour Colour("255 255 255 128");
Bubblewrap::Game::GameSettings settings;
settings.WindowCount_ = 1;
settings.WindowSettings_ = new Bubblewrap::Render::Window::WindowSettings[ 2 ];
settings.WindowSettings_[ 0 ].Width_ = 800;
settings.WindowSettings_[ 0 ].Height_ = 600;
settings.WindowSettings_[ 0 ].Title_ = "POTATO";
settings.WindowSettings_[ 0 ].Name_ = "Main";
settings.Registers_.push_back( Bubblewrap::Registers::SfmlRegisters::RegisterGraphics );
settings.Registers_.push_back( Bubblewrap::Registers::SfmlRegisters::RegisterAudio );
settings.Resources_.push_back( "textures" );
settings.TypeRegistration_ = ( [ ]( Bubblewrap::Base::ObjectRegister* Register )
{
Register->RegisterCreator( "GaPaddle", GaPaddle::Create, GaPaddle::CopyDef );
Register->RegisterCreator( "GaPong", GaPong::Create, GaPong::CopyDef );
Register->RegisterCreator( "GaLevel", GaLevel::Create, GaLevel::CopyDef );
Register->RegisterCreator( "GaTextController", GaTextController::Create, GaTextController::CopyDef );
} );
settings.Packages_.push_back( "basics.json" );
settings.BaseObject_ = "basics:LevelEntity";
Bubblewrap::Game::Game Game;
Game.Run( settings );
}<|endoftext|>
|
<commit_before>// @(#)root/g3d:$Name: $:$Id: TTUBS.cxx,v 1.4 2004/09/14 15:15:46 brun Exp $
// Author: Nenad Buncic 18/09/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 "TTUBS.h"
#include "TNode.h"
#include "TVirtualPad.h"
#include "TBuffer3D.h"
#include "TGeometry.h"
ClassImp(TTUBS)
//______________________________________________________________________________
// Begin_Html <P ALIGN=CENTER> <IMG SRC="gif/tubs.gif"> </P> End_Html
// TUBS is a segment of a tube. It has 8 parameters:
//
// - name name of the shape
// - title shape's title
// - material (see TMaterial)
// - rmin inside radius
// - rmax outside radius
// - dz half length in z
// - phi1 starting angle of the segment
// - phi2 ending angle of the segment
//
//
// NOTE: phi1 should be smaller than phi2. If this is not the case,
// the system adds 360 degrees to phi2.
//______________________________________________________________________________
TTUBS::TTUBS()
{
// TUBS shape default constructor
}
//______________________________________________________________________________
TTUBS::TTUBS(const char *name, const char *title, const char *material, Float_t rmin,
Float_t rmax, Float_t dz, Float_t phi1, Float_t phi2)
: TTUBE(name,title,material,rmin,rmax,dz)
{
// TUBS shape normal constructor
fPhi1 = phi1;
fPhi2 = phi2;
MakeTableOfCoSin();
}
//______________________________________________________________________________
TTUBS::TTUBS(const char *name, const char *title, const char *material, Float_t rmax, Float_t dz,
Float_t phi1, Float_t phi2)
: TTUBE(name,title,material,rmax,dz)
{
// TUBS shape "simplified" constructor
fPhi1 = phi1;
fPhi2 = phi2;
MakeTableOfCoSin();
}
//______________________________________________________________________________
void TTUBS::MakeTableOfCoSin()
{
const Double_t PI = TMath::ATan(1) * 4.0;
const Double_t TWOPI =2*PI;
const Double_t ragrad = PI/180.0;
Int_t j;
Int_t n = GetNumberOfDivisions () + 1;
if (fCoTab)
delete [] fCoTab; // Delete the old tab if any
fCoTab = new Double_t [n];
if (!fCoTab ) return;
if (fSiTab)
delete [] fSiTab; // Delete the old tab if any
fSiTab = new Double_t [n];
if (!fSiTab ) return;
Double_t phi1 = Double_t(fPhi1 * ragrad);
Double_t phi2 = Double_t(fPhi2 * ragrad);
if (phi1 > phi2 ) phi2 += TWOPI;
Double_t range = phi2- phi1;
Double_t angstep = range/(n-1);
Double_t ph = phi1;
for (j = 0; j < n; j++) {
ph = phi1 + j*angstep;
fCoTab[j] = TMath::Cos(ph);
fSiTab[j] = TMath::Sin(ph);
}
}
//______________________________________________________________________________
TTUBS::~TTUBS()
{
// TUBS shape default destructor
}
//______________________________________________________________________________
Int_t TTUBS::DistancetoPrimitive(Int_t px, Int_t py)
{
// Compute distance from point px,py to a TUBE
//
// Compute the closest distance of approach from point px,py to each
// computed outline point of the TUBE.
Int_t n = GetNumberOfDivisions()+1;
Int_t numPoints = n*4;
return ShapeDistancetoPrimitive(numPoints,px,py);
}
//______________________________________________________________________________
void TTUBS::Paint(Option_t *option)
{
// Paint this 3-D shape with its current attributes
Int_t i, j;
const Int_t n = GetNumberOfDivisions()+1;
Int_t NbPnts = 4*n;
Int_t NbSegs = 2*NbPnts;
Int_t NbPols = NbPnts-2;
TBuffer3D *buff = gPad->AllocateBuffer3D(3*NbPnts, 3*NbSegs, 6*NbPols);
if (!buff) return;
buff->fType = TBuffer3D::kTUBS;
buff->fId = this;
// Fill gPad->fBuffer3D. Points coordinates are in Master space
buff->fNbPnts = NbPnts;
buff->fNbSegs = NbSegs;
buff->fNbPols = NbPols;
// In case of option "size" it is not necessary to fill the buffer
if (buff->fOption == TBuffer3D::kSIZE) {
buff->Paint(option);
return;
}
SetPoints(buff->fPnts);
TransformPoints(buff);
// Basic colors: 0, 1, ... 7
buff->fColor = GetLineColor();
Int_t c = (((buff->fColor) %8) -1) * 4;
if (c < 0) c = 0;
memset(buff->fSegs, 0, buff->fNbSegs*3*sizeof(Int_t));
for (i = 0; i < 4; i++) {
for (j = 1; j < n; j++) {
buff->fSegs[(i*n+j-1)*3 ] = c;
buff->fSegs[(i*n+j-1)*3+1] = i*n+j-1;
buff->fSegs[(i*n+j-1)*3+2] = i*n+j;
}
}
for (i = 4; i < 6; i++) {
for (j = 0; j < n; j++) {
buff->fSegs[(i*n+j)*3 ] = c+1;
buff->fSegs[(i*n+j)*3+1] = (i-4)*n+j;
buff->fSegs[(i*n+j)*3+2] = (i-2)*n+j;
}
}
for (i = 6; i < 8; i++) {
for (j = 0; j < n; j++) {
buff->fSegs[(i*n+j)*3 ] = c;
buff->fSegs[(i*n+j)*3+1] = 2*(i-6)*n+j;
buff->fSegs[(i*n+j)*3+2] = (2*(i-6)+1)*n+j;
}
}
Int_t indx = 0;
memset(buff->fPols, 0, buff->fNbPols*6*sizeof(Int_t));
i = 0;
for (j = 0; j < n-1; j++) {
buff->fPols[indx++] = c;
buff->fPols[indx++] = 4;
buff->fPols[indx++] = (4+i)*n+j+1;
buff->fPols[indx++] = (2+i)*n+j;
buff->fPols[indx++] = (4+i)*n+j;
buff->fPols[indx++] = i*n+j;
}
i = 1;
for (j = 0; j < n-1; j++) {
buff->fPols[indx++] = c;
buff->fPols[indx++] = 4;
buff->fPols[indx++] = i*n+j;
buff->fPols[indx++] = (4+i)*n+j;
buff->fPols[indx++] = (2+i)*n+j;
buff->fPols[indx++] = (4+i)*n+j+1;
}
i = 2;
for (j = 0; j < n-1; j++) {
buff->fPols[indx++] = c+i;
buff->fPols[indx++] = 4;
buff->fPols[indx++] = (i-2)*2*n+j;
buff->fPols[indx++] = (4+i)*n+j;
buff->fPols[indx++] = ((i-2)*2+1)*n+j;
buff->fPols[indx++] = (4+i)*n+j+1;
}
i = 3;
for (j = 0; j < n-1; j++) {
buff->fPols[indx++] = c+i;
buff->fPols[indx++] = 4;
buff->fPols[indx++] = (4+i)*n+j+1;
buff->fPols[indx++] = ((i-2)*2+1)*n+j;
buff->fPols[indx++] = (4+i)*n+j;
buff->fPols[indx++] = (i-2)*2*n+j;
}
buff->fPols[indx++] = c+2;
buff->fPols[indx++] = 4;
buff->fPols[indx++] = 6*n;
buff->fPols[indx++] = 4*n;
buff->fPols[indx++] = 7*n;
buff->fPols[indx++] = 5*n;
buff->fPols[indx++] = c+2;
buff->fPols[indx++] = 4;
buff->fPols[indx++] = 6*n-1;
buff->fPols[indx++] = 8*n-1;
buff->fPols[indx++] = 5*n-1;
buff->fPols[indx++] = 7*n-1;
// Paint gPad->fBuffer3D
buff->Paint(option);
}
//______________________________________________________________________________
void TTUBS::SetPoints(Double_t *buff)
{
// Create TUBS points
Int_t j, n;
Int_t indx = 0;
Float_t dz = TTUBE::fDz;
n = GetNumberOfDivisions()+1;
if (buff) {
if (!fCoTab) MakeTableOfCoSin();
for (j = 0; j < n; j++) {
buff[indx+6*n] = buff[indx] = fRmin * fCoTab[j];
indx++;
buff[indx+6*n] = buff[indx] = fAspectRatio*fRmin * fSiTab[j];
indx++;
buff[indx+6*n] = dz;
buff[indx] =-dz;
indx++;
}
for (j = 0; j < n; j++) {
buff[indx+6*n] = buff[indx] = fRmax * fCoTab[j];
indx++;
buff[indx+6*n] = buff[indx] = fAspectRatio*fRmax * fSiTab[j];
indx++;
buff[indx+6*n]= dz;
buff[indx] =-dz;
indx++;
}
}
}
//______________________________________________________________________________
void TTUBS::Sizeof3D() const
{
// Return total X3D needed by TNode::ls (when called with option "x")
Int_t n = GetNumberOfDivisions()+1;
gSize3D.numPoints += n*4;
gSize3D.numSegs += n*8;
gSize3D.numPolys += n*4-2;
}
<commit_msg>From Timur: Fix to get shapes.C operational.<commit_after>// @(#)root/g3d:$Name: $:$Id: TTUBS.cxx,v 1.5 2004/09/14 15:56:15 brun Exp $
// Author: Nenad Buncic 18/09/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 "TTUBS.h"
#include "TNode.h"
#include "TVirtualPad.h"
#include "TBuffer3D.h"
#include "TGeometry.h"
ClassImp(TTUBS)
//______________________________________________________________________________
// Begin_Html <P ALIGN=CENTER> <IMG SRC="gif/tubs.gif"> </P> End_Html
// TUBS is a segment of a tube. It has 8 parameters:
//
// - name name of the shape
// - title shape's title
// - material (see TMaterial)
// - rmin inside radius
// - rmax outside radius
// - dz half length in z
// - phi1 starting angle of the segment
// - phi2 ending angle of the segment
//
//
// NOTE: phi1 should be smaller than phi2. If this is not the case,
// the system adds 360 degrees to phi2.
//______________________________________________________________________________
TTUBS::TTUBS()
{
// TUBS shape default constructor
}
//______________________________________________________________________________
TTUBS::TTUBS(const char *name, const char *title, const char *material, Float_t rmin,
Float_t rmax, Float_t dz, Float_t phi1, Float_t phi2)
: TTUBE(name,title,material,rmin,rmax,dz)
{
// TUBS shape normal constructor
fPhi1 = phi1;
fPhi2 = phi2;
MakeTableOfCoSin();
}
//______________________________________________________________________________
TTUBS::TTUBS(const char *name, const char *title, const char *material, Float_t rmax, Float_t dz,
Float_t phi1, Float_t phi2)
: TTUBE(name,title,material,rmax,dz)
{
// TUBS shape "simplified" constructor
fPhi1 = phi1;
fPhi2 = phi2;
MakeTableOfCoSin();
}
//______________________________________________________________________________
void TTUBS::MakeTableOfCoSin()
{
const Double_t PI = TMath::ATan(1) * 4.0;
const Double_t TWOPI =2*PI;
const Double_t ragrad = PI/180.0;
Int_t j;
Int_t n = GetNumberOfDivisions () + 1;
if (fCoTab)
delete [] fCoTab; // Delete the old tab if any
fCoTab = new Double_t [n];
if (!fCoTab ) return;
if (fSiTab)
delete [] fSiTab; // Delete the old tab if any
fSiTab = new Double_t [n];
if (!fSiTab ) return;
Double_t phi1 = Double_t(fPhi1 * ragrad);
Double_t phi2 = Double_t(fPhi2 * ragrad);
if (phi1 > phi2 ) phi2 += TWOPI;
Double_t range = phi2- phi1;
Double_t angstep = range/(n-1);
Double_t ph = phi1;
for (j = 0; j < n; j++) {
ph = phi1 + j*angstep;
fCoTab[j] = TMath::Cos(ph);
fSiTab[j] = TMath::Sin(ph);
}
}
//______________________________________________________________________________
TTUBS::~TTUBS()
{
// TUBS shape default destructor
}
//______________________________________________________________________________
Int_t TTUBS::DistancetoPrimitive(Int_t px, Int_t py)
{
// Compute distance from point px,py to a TUBE
//
// Compute the closest distance of approach from point px,py to each
// computed outline point of the TUBE.
Int_t n = GetNumberOfDivisions()+1;
Int_t numPoints = n*4;
return ShapeDistancetoPrimitive(numPoints,px,py);
}
//______________________________________________________________________________
void TTUBS::Paint(Option_t *option)
{
// Paint this 3-D shape with its current attributes
Int_t i, j;
const Int_t n = GetNumberOfDivisions()+1;
Int_t NbPnts = 4*n;
Int_t NbSegs = 2*NbPnts;
Int_t NbPols = NbPnts-2;
TBuffer3D *buff = gPad->AllocateBuffer3D(3*NbPnts, 3*NbSegs, 6*NbPols);
if (!buff) return;
buff->fType = TBuffer3D::kANY;
buff->fId = this;
// Fill gPad->fBuffer3D. Points coordinates are in Master space
buff->fNbPnts = NbPnts;
buff->fNbSegs = NbSegs;
buff->fNbPols = NbPols;
// In case of option "size" it is not necessary to fill the buffer
if (buff->fOption == TBuffer3D::kSIZE) {
buff->Paint(option);
return;
}
SetPoints(buff->fPnts);
TransformPoints(buff);
// Basic colors: 0, 1, ... 7
buff->fColor = GetLineColor();
Int_t c = (((buff->fColor) %8) -1) * 4;
if (c < 0) c = 0;
memset(buff->fSegs, 0, buff->fNbSegs*3*sizeof(Int_t));
for (i = 0; i < 4; i++) {
for (j = 1; j < n; j++) {
buff->fSegs[(i*n+j-1)*3 ] = c;
buff->fSegs[(i*n+j-1)*3+1] = i*n+j-1;
buff->fSegs[(i*n+j-1)*3+2] = i*n+j;
}
}
for (i = 4; i < 6; i++) {
for (j = 0; j < n; j++) {
buff->fSegs[(i*n+j)*3 ] = c+1;
buff->fSegs[(i*n+j)*3+1] = (i-4)*n+j;
buff->fSegs[(i*n+j)*3+2] = (i-2)*n+j;
}
}
for (i = 6; i < 8; i++) {
for (j = 0; j < n; j++) {
buff->fSegs[(i*n+j)*3 ] = c;
buff->fSegs[(i*n+j)*3+1] = 2*(i-6)*n+j;
buff->fSegs[(i*n+j)*3+2] = (2*(i-6)+1)*n+j;
}
}
Int_t indx = 0;
memset(buff->fPols, 0, buff->fNbPols*6*sizeof(Int_t));
i = 0;
for (j = 0; j < n-1; j++) {
buff->fPols[indx++] = c;
buff->fPols[indx++] = 4;
buff->fPols[indx++] = (4+i)*n+j+1;
buff->fPols[indx++] = (2+i)*n+j;
buff->fPols[indx++] = (4+i)*n+j;
buff->fPols[indx++] = i*n+j;
}
i = 1;
for (j = 0; j < n-1; j++) {
buff->fPols[indx++] = c;
buff->fPols[indx++] = 4;
buff->fPols[indx++] = i*n+j;
buff->fPols[indx++] = (4+i)*n+j;
buff->fPols[indx++] = (2+i)*n+j;
buff->fPols[indx++] = (4+i)*n+j+1;
}
i = 2;
for (j = 0; j < n-1; j++) {
buff->fPols[indx++] = c+i;
buff->fPols[indx++] = 4;
buff->fPols[indx++] = (i-2)*2*n+j;
buff->fPols[indx++] = (4+i)*n+j;
buff->fPols[indx++] = ((i-2)*2+1)*n+j;
buff->fPols[indx++] = (4+i)*n+j+1;
}
i = 3;
for (j = 0; j < n-1; j++) {
buff->fPols[indx++] = c+i;
buff->fPols[indx++] = 4;
buff->fPols[indx++] = (4+i)*n+j+1;
buff->fPols[indx++] = ((i-2)*2+1)*n+j;
buff->fPols[indx++] = (4+i)*n+j;
buff->fPols[indx++] = (i-2)*2*n+j;
}
buff->fPols[indx++] = c+2;
buff->fPols[indx++] = 4;
buff->fPols[indx++] = 6*n;
buff->fPols[indx++] = 4*n;
buff->fPols[indx++] = 7*n;
buff->fPols[indx++] = 5*n;
buff->fPols[indx++] = c+2;
buff->fPols[indx++] = 4;
buff->fPols[indx++] = 6*n-1;
buff->fPols[indx++] = 8*n-1;
buff->fPols[indx++] = 5*n-1;
buff->fPols[indx++] = 7*n-1;
// Paint gPad->fBuffer3D
buff->Paint(option);
}
//______________________________________________________________________________
void TTUBS::SetPoints(Double_t *buff)
{
// Create TUBS points
Int_t j, n;
Int_t indx = 0;
Float_t dz = TTUBE::fDz;
n = GetNumberOfDivisions()+1;
if (buff) {
if (!fCoTab) MakeTableOfCoSin();
for (j = 0; j < n; j++) {
buff[indx+6*n] = buff[indx] = fRmin * fCoTab[j];
indx++;
buff[indx+6*n] = buff[indx] = fAspectRatio*fRmin * fSiTab[j];
indx++;
buff[indx+6*n] = dz;
buff[indx] =-dz;
indx++;
}
for (j = 0; j < n; j++) {
buff[indx+6*n] = buff[indx] = fRmax * fCoTab[j];
indx++;
buff[indx+6*n] = buff[indx] = fAspectRatio*fRmax * fSiTab[j];
indx++;
buff[indx+6*n]= dz;
buff[indx] =-dz;
indx++;
}
}
}
//______________________________________________________________________________
void TTUBS::Sizeof3D() const
{
// Return total X3D needed by TNode::ls (when called with option "x")
Int_t n = GetNumberOfDivisions()+1;
gSize3D.numPoints += n*4;
gSize3D.numSegs += n*8;
gSize3D.numPolys += n*4-2;
}
<|endoftext|>
|
<commit_before>/*
Kopete , The KDE Instant Messenger
Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org>
Viva Chile Mierda!
Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile
Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>
#include "kopete.h"
#include <dcopclient.h>
#include "kopeteiface.h"
static const char *description =
I18N_NOOP("Kopete, the KDE Instant Messenger");
#define KOPETE_VERSION "CVS>=20020908"
static KCmdLineOptions options[] =
{
{ 0, 0, 0 }
};
int main(int argc, char *argv[])
{
KAboutData aboutData( "kopete", I18N_NOOP("Kopete"),
KOPETE_VERSION, description, KAboutData::License_GPL,
"(c) 2001,2002, Duncan Mac-Vicar Prett\n(c) 2002, The Kopete Development Team", "kopete-devel@kde.org", "http://kopete.kde.org");
aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, core developer"), "duncan@kde.org", "http://www.mac-vicar.com" );
aboutData.addAuthor ( "Nick Betcher", I18N_NOOP("Core developer, fastest plugin developer on earth."), "nbetcher@kde.org", "http://www.kdedevelopers.net" );
aboutData.addAuthor ( "Ryan Cumming", I18N_NOOP("Core developer"), "bodnar42@phalynx.dhs.org" );
aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Core developer"), "klingens@kde.org" );
aboutData.addAuthor ( "Richard Stellingwerff", I18N_NOOP("Developer"), "remenic@linuxfromscratch.org");
aboutData.addAuthor ( "Daniel Stone", I18N_NOOP("Core developer, Jabber plugin"), "dstone@kde.org", "http://raging.dropbear.id.au/daniel/");
aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Core developer, Jabber plugin"), "till@tantalo.net");
aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Core developer"), "ogoffart@tiscalinet.be");
aboutData.addAuthor ( "Hendrik vom Lehn", I18N_NOOP("Developer"), "hennevl@hennevl.de", "http://www.hennevl.de");
aboutData.addAuthor ( "Stefan Gehn", I18N_NOOP("Developer"), "sgehn@gmx.net", "http://metz81.mine.nu" );
aboutData.addAuthor ( "Andres Krapf", I18N_NOOP("Random hacks and bugfixes"), "dae@chez.com" );
aboutData.addAuthor ( "Gav Wood", I18N_NOOP("Winpopup plugin"), "gjw102@york.ac.uk" );
aboutData.addCredit ( "Herwin Jan Steehouwer", I18N_NOOP("KxEngine ICQ code") );
aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") );
aboutData.addCredit ( "Neil Stevens", I18N_NOOP("TAim engine AIM code") );
aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Psi Jabber code") );
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
KUniqueApplication::addCmdLineOptions();
Kopete kopete;
kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec
kopete.exec();
}
/*
* Local variables:
* c-indentation-style: k&r
* c-basic-offset: 8
* indent-tabs-mode: t
* End:
*/
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg><commit_after>/*
Kopete , The KDE Instant Messenger
Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org>
Viva Chile Mierda!
Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile
Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>
#include "kopete.h"
#include <dcopclient.h>
#include "kopeteiface.h"
static const char *description =
I18N_NOOP("Kopete, the KDE Instant Messenger");
#define KOPETE_VERSION "CVS>=20020908"
static KCmdLineOptions options[] =
{
{ 0, 0, 0 }
};
int main(int argc, char *argv[])
{
KAboutData aboutData( "kopete", I18N_NOOP("Kopete"),
KOPETE_VERSION, description, KAboutData::License_GPL,
"(c) 2001,2002, Duncan Mac-Vicar Prett\n(c) 2002, The Kopete Development Team", "kopete-devel@kde.org", "http://kopete.kde.org");
aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, core developer"), "duncan@kde.org", "http://www.mac-vicar.com" );
aboutData.addAuthor ( "Nick Betcher", I18N_NOOP("Core developer, fastest plugin developer on earth."), "nbetcher@kde.org", "http://www.kdedevelopers.net" );
aboutData.addAuthor ( "Ryan Cumming", I18N_NOOP("Core developer"), "bodnar42@phalynx.dhs.org" );
aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Core developer"), "klingens@kde.org" );
aboutData.addAuthor ( "Richard Stellingwerff", I18N_NOOP("Developer"), "remenic@linuxfromscratch.org");
aboutData.addAuthor ( "Daniel Stone", I18N_NOOP("Core developer, Jabber plugin"), "dstone@kde.org", "http://raging.dropbear.id.au/daniel/");
aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Core developer, Jabber plugin"), "till@tantalo.net");
aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Core developer"), "ogoffart@tiscalinet.be");
aboutData.addAuthor ( "Hendrik vom Lehn", I18N_NOOP("Developer"), "hennevl@hennevl.de", "http://www.hennevl.de");
aboutData.addAuthor ( "Stefan Gehn", I18N_NOOP("Developer"), "sgehn@gmx.net", "http://metz81.mine.nu" );
aboutData.addAuthor ( "Andres Krapf", I18N_NOOP("Developer"), "dae@chez.com" );
aboutData.addAuthor ( "Gav Wood", I18N_NOOP("Winpopup plugin"), "gjw102@york.ac.uk" );
aboutData.addAuthor ( "Zack Rusin", I18N_NOOP("Core developer, Gadu plugin"), "zack@kde.org" );
aboutData.addCredit ( "Vladimir Shutoff", I18N_NOOP("SIM icq library") );
aboutData.addCredit ( "Herwin Jan Steehouwer", I18N_NOOP("KxEngine icq code") );
aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") );
aboutData.addCredit ( "Neil Stevens", I18N_NOOP("TAim engine AIM code") );
aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Psi Jabber code") );
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
KUniqueApplication::addCmdLineOptions();
Kopete kopete;
kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec
kopete.exec();
}
/*
* Local variables:
* c-indentation-style: k&r
* c-basic-offset: 8
* indent-tabs-mode: t
* End:
*/
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|>
|
<commit_before>/*
Kopete , The KDE Instant Messenger
Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org>
Viva Chile Mierda!
Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile
Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>
#include "kopeteapplication.h"
#include "kopeteversion.h"
static const char description[] =
I18N_NOOP( "Kopete, the KDE Instant Messenger" );
int main( int argc, char *argv[] )
{
KAboutData aboutData( "kopete", 0, ki18n("Kopete"),
KOPETE_VERSION_STRING, ki18n(description), KAboutData::License_GPL,
ki18n("(c) 2001-2004, Duncan Mac-Vicar Prett\n(c) 2002-2005, Kopete Development Team"), ki18n("kopete-devel@kde.org"), "http://kopete.kde.org");
aboutData.addAuthor ( ki18n("Duncan Mac-Vicar Prett"), ki18n("Developer and Project founder"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" );
aboutData.addAuthor ( ki18n("Andre Duffeck"), ki18n("Developer, Yahoo plugin maintainer"), "duffeck@kde.org" );
aboutData.addAuthor ( ki18n("Andy Goossens"), ki18n("Developer"), "andygoossens@telenet.be" );
aboutData.addAuthor ( ki18n("Chris Howells"), ki18n("Developer, Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk");
aboutData.addAuthor ( ki18n("Cláudio da Silveira Pinheiro"), ki18n("Developer, Video device support"), "taupter@gmail.com", "http://taupter.homelinux.org" );
aboutData.addAuthor ( ki18n("Gregg Edghill"), ki18n("Developer, MSN"), "gregg.edghill@gmail.com");
aboutData.addAuthor ( ki18n("Grzegorz Jaskiewicz"), ki18n("Developer, Gadu plugin maintainer"), "gj@pointblue.com.pl" );
aboutData.addAuthor ( ki18n("Gustavo Pichorim Boiko"), ki18n("Developer"), "gustavo.boiko@kdemail.net" );
aboutData.addAuthor ( ki18n("Jason Keirstead"), ki18n("Developer"), "jason@keirstead.org", "http://www.keirstead.org");
aboutData.addAuthor ( ki18n("Matt Rogers"), ki18n("Lead Developer, AIM and ICQ plugin maintainer"), "mattr@kde.org" );
aboutData.addAuthor ( ki18n("Michel Hermier"), ki18n("IRC plugin maintainer"), "michel.hermier@wanadoo.fr" );
aboutData.addAuthor ( ki18n("Michaël Larouche"), ki18n("Lead Developer, Telepathy and Messenger plugin maintainer"), "larouche@kde.org", "http://www.tehbisnatch.org/" );
aboutData.addAuthor ( ki18n("Olivier Goffart"), ki18n("Lead Developer, MSN plugin maintainer"), "ogoffart@kde.org");
aboutData.addAuthor ( ki18n("Ollivier Lapeyre Johann"), ki18n("Artist / Developer, Artwork maintainer"), "johann.ollivierlapeyre@gmail.com" );
aboutData.addAuthor ( ki18n("Richard Smith"), ki18n("Developer, UI maintainer"), "kde@metafoo.co.uk" );
aboutData.addAuthor ( ki18n("Till Gerken"), ki18n("Developer, Jabber plugin maintainer"), "till@tantalo.net");
aboutData.addAuthor ( ki18n("Will Stephenson"), ki18n("Lead Developer, GroupWise maintainer"), "wstephenson@kde.org" );
aboutData.addAuthor ( ki18n("Rafael Fernández López"), ki18n("Developer"), "ereslibre@kde.org" );
aboutData.addAuthor ( ki18n("Roman Jarosz"), ki18n("Developer, AIM and ICQ"), "kedgedev@centrum.cz" );
aboutData.addAuthor ( ki18n("Charles Connell"), ki18n("Developer"), "charles@connells.org" );
aboutData.addCredit ( ki18n("Vally8"), ki18n("Konki style author"), "vally8@gmail.com", "http://vally8.free.fr/" );
aboutData.addCredit ( ki18n("Tm_T"), ki18n("Hacker style author"), "jussi.kekkonen@gmail.com");
aboutData.addCredit ( ki18n("Luciash d' Being"), ki18n("Kopete's icon author") );
aboutData.addCredit ( ki18n("Steve Cable"), ki18n("Sounds") );
aboutData.addCredit ( ki18n("Jessica Hall"), ki18n("Kopete Docugoddess, Bug and Patch Testing.") );
aboutData.addCredit ( ki18n("Justin Karneges"), ki18n("Iris Jabber Backend Library") );
aboutData.addCredit ( ki18n("Tom Linsky"), ki18n("OscarSocket author"), "twl6@po.cwru.edu" );
aboutData.addCredit ( ki18n("Olaf Lueg"), ki18n("Kmerlin MSN code") );
aboutData.addCredit ( ki18n("Chetan Reddy"), ki18n("Former developer"), "chetan13@gmail.com" );
aboutData.addCredit ( ki18n("Nick Betcher"), ki18n("Former developer, project co-founder"), "nbetcher@kde.org");
aboutData.addCredit ( ki18n("Ryan Cumming"), ki18n("Former developer"), "ryan@kde.org" );
aboutData.addCredit ( ki18n("Stefan Gehn"), ki18n("Former developer"), "metz@gehn.net", "http://metz.gehn.net" );
aboutData.addCredit ( ki18n("Martijn Klingens"), ki18n("Former developer"), "klingens@kde.org" );
aboutData.addCredit ( ki18n("Andres Krapf"), ki18n("Former developer"), "dae@chez.com" );
aboutData.addCredit ( ki18n("Carsten Pfeiffer"), ki18n("Misc bugfixes and enhancements"), "pfeiffer@kde.org" );
aboutData.addCredit ( ki18n("Zack Rusin"), ki18n("Former developer, original Gadu plugin author"), "zack@kde.org" );
aboutData.addCredit ( ki18n("Richard Stellingwerff"), ki18n("Former developer"), "remenic@linuxfromscratch.org");
aboutData.addCredit ( ki18n("Daniel Stone"), ki18n("Former developer, Jabber plugin author"), "daniel@fooishbar.org", "http://fooishbar.org");
aboutData.addCredit ( ki18n("Chris TenHarmsel"), ki18n("Former developer, Oscar plugin"), "chris@tenharmsel.com");
aboutData.addCredit ( ki18n("Hendrik vom Lehn"), ki18n("Former developer"), "hennevl@hennevl.de", "http://www.hennevl.de");
aboutData.addCredit ( ki18n("Gav Wood"), ki18n("Former developer and WinPopup maintainer"), "gav@indigoarchive.net" );
aboutData.setTranslator( ki18nc("NAME OF TRANSLATORS","Your names"),
ki18nc("EMAIL OF TRANSLATORS","Your emails") );
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineOptions options;
options.add("noplugins", ki18n( "Do not load plugins. This option overrides all other options." ));
options.add("noconnect", ki18n( "Disable auto-connection" ));
options.add("autoconnect <accounts>", ki18n( "Auto-connect the specified accounts. Use a comma-separated list\n"
"to auto-connect multiple accounts." ));
options.add("disable <plugins>", ki18n( "Do not load the specified plugin. Use a comma-separated list\n"
"to disable multiple plugins." ));
options.add("load-plugins <plugins>", ki18n( "Load only the specified plugins. Use a comma-separated list\n"
"to load multiple plugins. This option has no effect when\n"
"--noplugins is set and overrides all other plugin related\n"
"command line options." ));
// { "url <url>", I18N_NOOP( "Load the given Kopete URL" ), 0 },
// { "!+[plugin]", I18N_NOOP( "Load specified plugins" ), 0 },
options.add("!+[URL]", ki18n("URLs to pass to kopete / emoticon themes to install"));
KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
KUniqueApplication::addCmdLineOptions();
KopeteApplication kopete;
return kopete.exec();
}
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>Update copyright year<commit_after>/*
Kopete , The KDE Instant Messenger
Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org>
Viva Chile Mierda!
Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile
Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>
#include "kopeteapplication.h"
#include "kopeteversion.h"
static const char description[] =
I18N_NOOP( "Kopete, the KDE Instant Messenger" );
int main( int argc, char *argv[] )
{
KAboutData aboutData( "kopete", 0, ki18n("Kopete"),
KOPETE_VERSION_STRING, ki18n(description), KAboutData::License_GPL,
ki18n("(c) 2001-2004, Duncan Mac-Vicar Prett\n(c) 2002-2007, Kopete Development Team"), ki18n("kopete-devel@kde.org"), "http://kopete.kde.org");
aboutData.addAuthor ( ki18n("Duncan Mac-Vicar Prett"), ki18n("Developer and Project founder"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" );
aboutData.addAuthor ( ki18n("Andre Duffeck"), ki18n("Developer, Yahoo plugin maintainer"), "duffeck@kde.org" );
aboutData.addAuthor ( ki18n("Andy Goossens"), ki18n("Developer"), "andygoossens@telenet.be" );
aboutData.addAuthor ( ki18n("Chris Howells"), ki18n("Developer, Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk");
aboutData.addAuthor ( ki18n("Cláudio da Silveira Pinheiro"), ki18n("Developer, Video device support"), "taupter@gmail.com", "http://taupter.homelinux.org" );
aboutData.addAuthor ( ki18n("Gregg Edghill"), ki18n("Developer, MSN"), "gregg.edghill@gmail.com");
aboutData.addAuthor ( ki18n("Grzegorz Jaskiewicz"), ki18n("Developer, Gadu plugin maintainer"), "gj@pointblue.com.pl" );
aboutData.addAuthor ( ki18n("Gustavo Pichorim Boiko"), ki18n("Developer"), "gustavo.boiko@kdemail.net" );
aboutData.addAuthor ( ki18n("Jason Keirstead"), ki18n("Developer"), "jason@keirstead.org", "http://www.keirstead.org");
aboutData.addAuthor ( ki18n("Matt Rogers"), ki18n("Lead Developer, AIM and ICQ plugin maintainer"), "mattr@kde.org" );
aboutData.addAuthor ( ki18n("Michel Hermier"), ki18n("IRC plugin maintainer"), "michel.hermier@wanadoo.fr" );
aboutData.addAuthor ( ki18n("Michaël Larouche"), ki18n("Lead Developer, Telepathy and Messenger plugin maintainer"), "larouche@kde.org", "http://www.tehbisnatch.org/" );
aboutData.addAuthor ( ki18n("Olivier Goffart"), ki18n("Lead Developer, MSN plugin maintainer"), "ogoffart@kde.org");
aboutData.addAuthor ( ki18n("Ollivier Lapeyre Johann"), ki18n("Artist / Developer, Artwork maintainer"), "johann.ollivierlapeyre@gmail.com" );
aboutData.addAuthor ( ki18n("Richard Smith"), ki18n("Developer, UI maintainer"), "kde@metafoo.co.uk" );
aboutData.addAuthor ( ki18n("Till Gerken"), ki18n("Developer, Jabber plugin maintainer"), "till@tantalo.net");
aboutData.addAuthor ( ki18n("Will Stephenson"), ki18n("Lead Developer, GroupWise maintainer"), "wstephenson@kde.org" );
aboutData.addAuthor ( ki18n("Rafael Fernández López"), ki18n("Developer"), "ereslibre@kde.org" );
aboutData.addAuthor ( ki18n("Roman Jarosz"), ki18n("Developer, AIM and ICQ"), "kedgedev@centrum.cz" );
aboutData.addAuthor ( ki18n("Charles Connell"), ki18n("Developer"), "charles@connells.org" );
aboutData.addCredit ( ki18n("Vally8"), ki18n("Konki style author"), "vally8@gmail.com", "http://vally8.free.fr/" );
aboutData.addCredit ( ki18n("Tm_T"), ki18n("Hacker style author"), "jussi.kekkonen@gmail.com");
aboutData.addCredit ( ki18n("Luciash d' Being"), ki18n("Kopete's icon author") );
aboutData.addCredit ( ki18n("Steve Cable"), ki18n("Sounds") );
aboutData.addCredit ( ki18n("Jessica Hall"), ki18n("Kopete Docugoddess, Bug and Patch Testing.") );
aboutData.addCredit ( ki18n("Justin Karneges"), ki18n("Iris Jabber Backend Library") );
aboutData.addCredit ( ki18n("Tom Linsky"), ki18n("OscarSocket author"), "twl6@po.cwru.edu" );
aboutData.addCredit ( ki18n("Olaf Lueg"), ki18n("Kmerlin MSN code") );
aboutData.addCredit ( ki18n("Chetan Reddy"), ki18n("Former developer"), "chetan13@gmail.com" );
aboutData.addCredit ( ki18n("Nick Betcher"), ki18n("Former developer, project co-founder"), "nbetcher@kde.org");
aboutData.addCredit ( ki18n("Ryan Cumming"), ki18n("Former developer"), "ryan@kde.org" );
aboutData.addCredit ( ki18n("Stefan Gehn"), ki18n("Former developer"), "metz@gehn.net", "http://metz.gehn.net" );
aboutData.addCredit ( ki18n("Martijn Klingens"), ki18n("Former developer"), "klingens@kde.org" );
aboutData.addCredit ( ki18n("Andres Krapf"), ki18n("Former developer"), "dae@chez.com" );
aboutData.addCredit ( ki18n("Carsten Pfeiffer"), ki18n("Misc bugfixes and enhancements"), "pfeiffer@kde.org" );
aboutData.addCredit ( ki18n("Zack Rusin"), ki18n("Former developer, original Gadu plugin author"), "zack@kde.org" );
aboutData.addCredit ( ki18n("Richard Stellingwerff"), ki18n("Former developer"), "remenic@linuxfromscratch.org");
aboutData.addCredit ( ki18n("Daniel Stone"), ki18n("Former developer, Jabber plugin author"), "daniel@fooishbar.org", "http://fooishbar.org");
aboutData.addCredit ( ki18n("Chris TenHarmsel"), ki18n("Former developer, Oscar plugin"), "chris@tenharmsel.com");
aboutData.addCredit ( ki18n("Hendrik vom Lehn"), ki18n("Former developer"), "hennevl@hennevl.de", "http://www.hennevl.de");
aboutData.addCredit ( ki18n("Gav Wood"), ki18n("Former developer and WinPopup maintainer"), "gav@indigoarchive.net" );
aboutData.setTranslator( ki18nc("NAME OF TRANSLATORS","Your names"),
ki18nc("EMAIL OF TRANSLATORS","Your emails") );
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineOptions options;
options.add("noplugins", ki18n( "Do not load plugins. This option overrides all other options." ));
options.add("noconnect", ki18n( "Disable auto-connection" ));
options.add("autoconnect <accounts>", ki18n( "Auto-connect the specified accounts. Use a comma-separated list\n"
"to auto-connect multiple accounts." ));
options.add("disable <plugins>", ki18n( "Do not load the specified plugin. Use a comma-separated list\n"
"to disable multiple plugins." ));
options.add("load-plugins <plugins>", ki18n( "Load only the specified plugins. Use a comma-separated list\n"
"to load multiple plugins. This option has no effect when\n"
"--noplugins is set and overrides all other plugin related\n"
"command line options." ));
// { "url <url>", I18N_NOOP( "Load the given Kopete URL" ), 0 },
// { "!+[plugin]", I18N_NOOP( "Load specified plugins" ), 0 },
options.add("!+[URL]", ki18n("URLs to pass to kopete / emoticon themes to install"));
KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
KUniqueApplication::addCmdLineOptions();
KopeteApplication kopete;
return kopete.exec();
}
// vim: set noet ts=4 sts=4 sw=4:
<|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 "paddle/fluid/operators/minus_op.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
namespace paddle {
namespace operators {
class MinusOp : public framework::OperatorWithKernel {
public:
MinusOp(const std::string &type, const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: OperatorWithKernel(type, inputs, outputs, attrs) {}
void InferShape(framework::InferShapeContext *ctx) const override {
PADDLE_ENFORCE_EQ(
ctx->HasInput("X"), true,
platform::errors::NotFound("Input(X) of MinusOp is not found."));
PADDLE_ENFORCE_EQ(
ctx->HasInput("Y"), true,
platform::errors::NotFound("Input(Y) of MinusOp is not found."));
PADDLE_ENFORCE_EQ(
ctx->HasOutput("Out"), true,
platform::errors::NotFound("Output(Out) of MinusOp is not found."));
auto x_dims = ctx->GetInputDim("X");
auto y_dims = ctx->GetInputDim("Y");
if (ctx->IsRuntime() ||
(framework::product(x_dims) > 0 && framework::product(y_dims) > 0)) {
PADDLE_ENFORCE_EQ(
x_dims, y_dims,
"Minus operator must take two tensor with same num of elements");
}
ctx->SetOutputDim("Out", x_dims);
ctx->ShareLoD("X", /*->*/ "Out");
}
};
class MinusOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("X", "The left tensor of minus operator.");
AddInput("Y", "The right tensor of minus operator.");
AddOutput("Out", "The output tensor of minus operator.");
AddComment(R"DOC(
Minus Operator.
Equation:
$Out = X - Y$
Both the input `X` and `Y` can carry the LoD (Level of Details) information,
or not. But the output only shares the LoD information with input `X`.
)DOC");
}
};
class MinusGradDescMaker : public framework::GradOpDescMakerBase {
public:
using framework::GradOpDescMakerBase::GradOpDescMakerBase;
std::vector<std::unique_ptr<framework::OpDesc>> operator()() const override {
std::vector<std::unique_ptr<framework::OpDesc>> ops;
auto x_g = this->InputGrad("X");
if (!x_g.empty()) {
auto *x_g_op = new framework::OpDesc();
x_g_op->SetType("scale");
x_g_op->SetInput("X", this->OutputGrad("Out"));
x_g_op->SetOutput("Out", x_g);
x_g_op->SetAttr("scale", 1.0f);
ops.emplace_back(x_g_op);
}
auto y_g = this->InputGrad("Y");
if (!y_g.empty()) {
auto *y_g_op = new framework::OpDesc();
y_g_op->SetType("scale");
y_g_op->SetInput("X", this->OutputGrad("Out"));
y_g_op->SetOutput("Out", y_g);
y_g_op->SetAttr("scale", -1.0f);
ops.emplace_back(y_g_op);
}
return ops;
}
};
class MinusGradMaker : public imperative::GradOpBaseMakerBase {
public:
using imperative::GradOpBaseMakerBase::GradOpBaseMakerBase;
std::shared_ptr<imperative::GradOpNode> operator()() const override {
auto x_g = this->InputGrad("X");
auto y_g = this->InputGrad("Y");
auto node = this->NewGradNode();
if (!x_g.empty()) {
imperative::TracedGradOp op(node);
op.SetType("scale");
op.SetInput("X", this->OutputGrad("Out"));
op.SetOutput("Out", x_g);
op.SetAttr("scale", 1.0f);
}
if (!y_g.empty()) {
imperative::TracedGradOp op(node);
op.SetType("scale");
op.SetInput("X", this->OutputGrad("Out"));
op.SetOutput("Out", y_g);
op.SetAttr("scale", -1.0f);
}
return node;
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(minus, ops::MinusOp, ops::MinusOpMaker,
ops::MinusGradDescMaker, ops::MinusGradMaker);
REGISTER_OP_CPU_KERNEL(
minus, ops::MinusKernel<paddle::platform::CPUDeviceContext, float>);
<commit_msg>OP(minus) error message enhancement. test=develop (#23621)<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 "paddle/fluid/operators/minus_op.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
namespace paddle {
namespace operators {
class MinusOp : public framework::OperatorWithKernel {
public:
MinusOp(const std::string &type, const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: OperatorWithKernel(type, inputs, outputs, attrs) {}
void InferShape(framework::InferShapeContext *ctx) const override {
PADDLE_ENFORCE_EQ(
ctx->HasInput("X"), true,
platform::errors::NotFound("Input(X) of MinusOp is not found."));
PADDLE_ENFORCE_EQ(
ctx->HasInput("Y"), true,
platform::errors::NotFound("Input(Y) of MinusOp is not found."));
PADDLE_ENFORCE_EQ(
ctx->HasOutput("Out"), true,
platform::errors::NotFound("Output(Out) of MinusOp is not found."));
auto x_dims = ctx->GetInputDim("X");
auto y_dims = ctx->GetInputDim("Y");
if (ctx->IsRuntime() ||
(framework::product(x_dims) > 0 && framework::product(y_dims) > 0)) {
PADDLE_ENFORCE_EQ(
x_dims, y_dims,
platform::errors::InvalidArgument(
"Minus operator must take two tensor with same dim, but received "
"input X dim is:[%s], Y dim is:[%s]",
x_dims, y_dims));
}
ctx->SetOutputDim("Out", x_dims);
ctx->ShareLoD("X", /*->*/ "Out");
}
};
class MinusOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("X", "The left tensor of minus operator.");
AddInput("Y", "The right tensor of minus operator.");
AddOutput("Out", "The output tensor of minus operator.");
AddComment(R"DOC(
Minus Operator.
Equation:
$Out = X - Y$
Both the input `X` and `Y` can carry the LoD (Level of Details) information,
or not. But the output only shares the LoD information with input `X`.
)DOC");
}
};
class MinusGradDescMaker : public framework::GradOpDescMakerBase {
public:
using framework::GradOpDescMakerBase::GradOpDescMakerBase;
std::vector<std::unique_ptr<framework::OpDesc>> operator()() const override {
std::vector<std::unique_ptr<framework::OpDesc>> ops;
auto x_g = this->InputGrad("X");
if (!x_g.empty()) {
auto *x_g_op = new framework::OpDesc();
x_g_op->SetType("scale");
x_g_op->SetInput("X", this->OutputGrad("Out"));
x_g_op->SetOutput("Out", x_g);
x_g_op->SetAttr("scale", 1.0f);
ops.emplace_back(x_g_op);
}
auto y_g = this->InputGrad("Y");
if (!y_g.empty()) {
auto *y_g_op = new framework::OpDesc();
y_g_op->SetType("scale");
y_g_op->SetInput("X", this->OutputGrad("Out"));
y_g_op->SetOutput("Out", y_g);
y_g_op->SetAttr("scale", -1.0f);
ops.emplace_back(y_g_op);
}
return ops;
}
};
class MinusGradMaker : public imperative::GradOpBaseMakerBase {
public:
using imperative::GradOpBaseMakerBase::GradOpBaseMakerBase;
std::shared_ptr<imperative::GradOpNode> operator()() const override {
auto x_g = this->InputGrad("X");
auto y_g = this->InputGrad("Y");
auto node = this->NewGradNode();
if (!x_g.empty()) {
imperative::TracedGradOp op(node);
op.SetType("scale");
op.SetInput("X", this->OutputGrad("Out"));
op.SetOutput("Out", x_g);
op.SetAttr("scale", 1.0f);
}
if (!y_g.empty()) {
imperative::TracedGradOp op(node);
op.SetType("scale");
op.SetInput("X", this->OutputGrad("Out"));
op.SetOutput("Out", y_g);
op.SetAttr("scale", -1.0f);
}
return node;
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(minus, ops::MinusOp, ops::MinusOpMaker,
ops::MinusGradDescMaker, ops::MinusGradMaker);
REGISTER_OP_CPU_KERNEL(
minus, ops::MinusKernel<paddle::platform::CPUDeviceContext, float>);
<|endoftext|>
|
<commit_before>#include "transactiondesc.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "base58.h"
#include "main.h"
#include "paymentserver.h"
#include "transactionrecord.h"
#include "timedata.h"
#include "ui_interface.h"
#include "wallet.h"
#include "txdb.h"
#include <string>
QString TransactionDesc::FormatTxStatus(const CWalletTx& wtx)
{
AssertLockHeld(cs_main);
if (!IsFinalTx(wtx, nBestHeight + 1))
{
if (wtx.nLockTime < LOCKTIME_THRESHOLD)
return tr("Open for %n more block(s)", "", wtx.nLockTime - nBestHeight);
else
return tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx.nLockTime));
}
else
{
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < 0)
return tr("conflicted");
else if (GetAdjustedTime() - wtx.nTimeReceived > 4.2 * 60 && wtx.GetRequestCount() == 0)
return tr("%1/offline").arg(nDepth);
else if (nDepth < 10)
return tr("%1/unconfirmed").arg(nDepth);
else
return tr("%1 confirmations").arg(nDepth);
}
}
QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionRecord *rec, int unit)
{
QString strHTML;
LOCK2(cs_main, wallet->cs_wallet);
strHTML.reserve(4000);
strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";
int64_t nTime = wtx.GetTxTime();
int64_t nCredit = wtx.GetCredit();
int64_t nDebit = wtx.GetDebit();
int64_t nNet = nCredit - nDebit;
strHTML += "<b>" + tr("Status") + ":</b> " + FormatTxStatus(wtx);
int nRequests = wtx.GetRequestCount();
if (nRequests != -1)
{
if (nRequests == 0)
strHTML += tr(", has not been successfully broadcast yet");
else if (nRequests > 0)
strHTML += tr(", broadcast through %n node(s)", "", nRequests);
}
strHTML += "<br>";
strHTML += "<b>" + tr("Date") + ":</b> " + (nTime ? GUIUtil::dateTimeStr(nTime) : "") + "<br>";
//
// From
//
if (wtx.IsCoinBase() || wtx.IsCoinStake())
{
strHTML += "<b>" + tr("Source") + ":</b> " + tr("Generated") + "<br>";
}
else if (wtx.mapValue.count("from") && !wtx.mapValue["from"].empty())
{
// Online transaction
strHTML += "<b>" + tr("From") + ":</b> " + GUIUtil::HtmlEscape(wtx.mapValue["from"]) + "<br>";
}
else
{
// Offline transaction
if (nNet > 0)
{
// Credit
if (CBitcoinAddress(rec->address).IsValid())
{
CTxDestination address = CBitcoinAddress(rec->address).Get();
if (wallet->mapAddressBook.count(address))
{
strHTML += "<b>" + tr("From") + ":</b> " + tr("unknown") + "<br>";
strHTML += "<b>" + tr("To") + ":</b> ";
strHTML += GUIUtil::HtmlEscape(rec->address);
if (!wallet->mapAddressBook[address].empty())
strHTML += " (" + tr("own address") + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + ")";
else
strHTML += " (" + tr("own address") + ")";
strHTML += "<br>";
}
}
}
}
//
// To
//
if (wtx.mapValue.count("to") && !wtx.mapValue["to"].empty())
{
// Online transaction
std::string strAddress = wtx.mapValue["to"];
strHTML += "<b>" + tr("To") + ":</b> ";
CTxDestination dest = CBitcoinAddress(strAddress).Get();
if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest]) + " ";
strHTML += GUIUtil::HtmlEscape(strAddress) + "<br>";
}
//
// Amount
//
if (wtx.IsCoinBase() && nCredit == 0)
{
//
// Coinbase
//
int64_t nUnmatured = 0;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
nUnmatured += wallet->GetCredit(txout);
strHTML += "<b>" + tr("Credit") + ":</b> ";
if (wtx.IsInMainChain())
strHTML += BitcoinUnits::formatWithUnit(unit, nUnmatured)+ " (" + tr("matures in %n more block(s)", "", wtx.GetBlocksToMaturity()) + ")";
else
strHTML += "(" + tr("not accepted") + ")";
strHTML += "<br>";
}
else if (nNet > 0)
{
//
// Credit
//
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatWithUnit(unit, nNet) + "<br>";
}
else
{
bool fAllFromMe = true;
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
fAllFromMe = fAllFromMe && wallet->IsMine(txin);
bool fAllToMe = true;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
fAllToMe = fAllToMe && wallet->IsMine(txout);
if (fAllFromMe)
{
//
// Debit
//
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
if (wallet->IsMine(txout))
continue;
if (!wtx.mapValue.count("to") || wtx.mapValue["to"].empty())
{
// Offline transaction
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address))
{
strHTML += "<b>" + tr("To") + ":</b> ";
if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + " ";
strHTML += GUIUtil::HtmlEscape(CBitcoinAddress(address).ToString());
strHTML += "<br>";
}
}
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatWithUnit(unit, -txout.nValue) + "<br>";
}
if (fAllToMe)
{
// Payment to self
int64_t nChange = wtx.GetChange();
int64_t nValue = nCredit - nChange;
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatWithUnit(unit, -nValue) + "<br>";
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatWithUnit(unit, nValue) + "<br>";
}
int64_t nTxFee = nDebit - wtx.GetValueOut();
if (nTxFee > 0)
strHTML += "<b>" + tr("Transaction fee") + ":</b> " + BitcoinUnits::formatWithUnit(unit, -nTxFee) + "<br>";
}
else
{
//
// Mixed debit transaction
//
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
if (wallet->IsMine(txin))
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatWithUnit(unit, -wallet->GetDebit(txin)) + "<br>";
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (wallet->IsMine(txout))
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatWithUnit(unit, wallet->GetCredit(txout)) + "<br>";
}
}
strHTML += "<b>" + tr("Net amount") + ":</b> " + BitcoinUnits::formatWithUnit(unit, nNet, true) + "<br>";
//
// Message
//
if (wtx.mapValue.count("message") && !wtx.mapValue["message"].empty())
strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["message"], true) + "<br>";
if (wtx.mapValue.count("comment") && !wtx.mapValue["comment"].empty())
strHTML += "<br><b>" + tr("Comment") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["comment"], true) + "<br>";
strHTML += "<b>" + tr("Transaction ID") + ":</b> " + TransactionRecord::formatSubTxId(wtx.GetHash(), rec->idx) + "<br>";
if (wtx.IsCoinBase() || wtx.IsCoinStake())
strHTML += "<br>" + tr("Generated coins must mature 188 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \"not accepted\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.") + "<br>";
//
// Debug view
//
if (fDebug)
{
strHTML += "<hr><br>" + tr("Debug information") + "<br><br>";
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
if(wallet->IsMine(txin))
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatWithUnit(unit, -wallet->GetDebit(txin)) + "<br>";
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if(wallet->IsMine(txout))
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatWithUnit(unit, wallet->GetCredit(txout)) + "<br>";
strHTML += "<br><b>" + tr("Transaction") + ":</b><br>";
strHTML += GUIUtil::HtmlEscape(wtx.ToString(), true);
CTxDB txdb("r"); // To fetch source txouts
strHTML += "<br><b>" + tr("Inputs") + ":</b>";
strHTML += "<ul>";
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
COutPoint prevout = txin.prevout;
CTransaction prev;
if(txdb.ReadDiskTx(prevout.hash, prev))
{
if (prevout.n < prev.vout.size())
{
strHTML += "<li>";
const CTxOut &vout = prev.vout[prevout.n];
CTxDestination address;
if (ExtractDestination(vout.scriptPubKey, address))
{
if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + " ";
strHTML += QString::fromStdString(CBitcoinAddress(address).ToString());
}
strHTML = strHTML + " " + tr("Amount") + "=" + BitcoinUnits::formatWithUnit(unit, vout.nValue);
strHTML = strHTML + " IsMine=" + (wallet->IsMine(vout) ? tr("true") : tr("false")) + "</li>";
}
}
}
strHTML += "</ul>";
}
strHTML += "</font></html>";
return strHTML;
}
<commit_msg>Update transactiondesc.cpp<commit_after>#include "transactiondesc.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "base58.h"
#include "main.h"
#include "paymentserver.h"
#include "transactionrecord.h"
#include "timedata.h"
#include "ui_interface.h"
#include "wallet.h"
#include "txdb.h"
#include <string>
QString TransactionDesc::FormatTxStatus(const CWalletTx& wtx)
{
AssertLockHeld(cs_main);
if (!IsFinalTx(wtx, nBestHeight + 1))
{
if (wtx.nLockTime < LOCKTIME_THRESHOLD)
return tr("Open for %n more block(s)", "", wtx.nLockTime - nBestHeight);
else
return tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx.nLockTime));
}
else
{
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < 0)
return tr("conflicted");
else if (GetAdjustedTime() - wtx.nTimeReceived > 4.2 * 60 && wtx.GetRequestCount() == 0)
return tr("%1/offline").arg(nDepth);
else if (nDepth < 10)
return tr("%1/unconfirmed").arg(nDepth);
else
return tr("%1 confirmations").arg(nDepth);
}
}
QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionRecord *rec, int unit)
{
QString strHTML;
LOCK2(cs_main, wallet->cs_wallet);
strHTML.reserve(4000);
strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";
int64_t nTime = wtx.GetTxTime();
int64_t nCredit = wtx.GetCredit();
int64_t nDebit = wtx.GetDebit();
int64_t nNet = nCredit - nDebit;
strHTML += "<b>" + tr("Status") + ":</b> " + FormatTxStatus(wtx);
int nRequests = wtx.GetRequestCount();
if (nRequests != -1)
{
if (nRequests == 0)
strHTML += tr(", has not been successfully broadcast yet");
else if (nRequests > 0)
strHTML += tr(", broadcast through %n node(s)", "", nRequests);
}
strHTML += "<br>";
strHTML += "<b>" + tr("Date") + ":</b> " + (nTime ? GUIUtil::dateTimeStr(nTime) : "") + "<br>";
//
// From
//
if (wtx.IsCoinBase() || wtx.IsCoinStake())
{
strHTML += "<b>" + tr("Source") + ":</b> " + tr("Generated") + "<br>";
}
else if (wtx.mapValue.count("from") && !wtx.mapValue["from"].empty())
{
// Online transaction
strHTML += "<b>" + tr("From") + ":</b> " + GUIUtil::HtmlEscape(wtx.mapValue["from"]) + "<br>";
}
else
{
// Offline transaction
if (nNet > 0)
{
// Credit
if (CBitcoinAddress(rec->address).IsValid())
{
CTxDestination address = CBitcoinAddress(rec->address).Get();
if (wallet->mapAddressBook.count(address))
{
strHTML += "<b>" + tr("From") + ":</b> " + tr("unknown") + "<br>";
strHTML += "<b>" + tr("To") + ":</b> ";
strHTML += GUIUtil::HtmlEscape(rec->address);
if (!wallet->mapAddressBook[address].empty())
strHTML += " (" + tr("own address") + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + ")";
else
strHTML += " (" + tr("own address") + ")";
strHTML += "<br>";
}
}
}
}
//
// To
//
if (wtx.mapValue.count("to") && !wtx.mapValue["to"].empty())
{
// Online transaction
std::string strAddress = wtx.mapValue["to"];
strHTML += "<b>" + tr("To") + ":</b> ";
CTxDestination dest = CBitcoinAddress(strAddress).Get();
if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest]) + " ";
strHTML += GUIUtil::HtmlEscape(strAddress) + "<br>";
}
//
// Amount
//
if (wtx.IsCoinBase() && nCredit == 0)
{
//
// Coinbase
//
int64_t nUnmatured = 0;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
nUnmatured += wallet->GetCredit(txout);
strHTML += "<b>" + tr("Credit") + ":</b> ";
if (wtx.IsInMainChain())
strHTML += BitcoinUnits::formatWithUnit(unit, nUnmatured)+ " (" + tr("matures in %n more block(s)", "", wtx.GetBlocksToMaturity()) + ")";
else
strHTML += "(" + tr("not accepted") + ")";
strHTML += "<br>";
}
else if (nNet > 0)
{
//
// Credit
//
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatWithUnit(unit, nNet) + "<br>";
}
else
{
bool fAllFromMe = true;
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
fAllFromMe = fAllFromMe && wallet->IsMine(txin);
bool fAllToMe = true;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
fAllToMe = fAllToMe && wallet->IsMine(txout);
if (fAllFromMe)
{
//
// Debit
//
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
if (wallet->IsMine(txout))
continue;
if (!wtx.mapValue.count("to") || wtx.mapValue["to"].empty())
{
// Offline transaction
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address))
{
strHTML += "<b>" + tr("To") + ":</b> ";
if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + " ";
strHTML += GUIUtil::HtmlEscape(CBitcoinAddress(address).ToString());
strHTML += "<br>";
}
}
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatWithUnit(unit, -txout.nValue) + "<br>";
}
if (fAllToMe)
{
// Payment to self
int64_t nChange = wtx.GetChange();
int64_t nValue = nCredit - nChange;
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatWithUnit(unit, -nValue) + "<br>";
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatWithUnit(unit, nValue) + "<br>";
}
int64_t nTxFee = nDebit - wtx.GetValueOut();
if (nTxFee > 0)
strHTML += "<b>" + tr("Transaction fee") + ":</b> " + BitcoinUnits::formatWithUnit(unit, -nTxFee) + "<br>";
}
else
{
//
// Mixed debit transaction
//
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
if (wallet->IsMine(txin))
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatWithUnit(unit, -wallet->GetDebit(txin)) + "<br>";
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (wallet->IsMine(txout))
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatWithUnit(unit, wallet->GetCredit(txout)) + "<br>";
}
}
strHTML += "<b>" + tr("Net amount") + ":</b> " + BitcoinUnits::formatWithUnit(unit, nNet, true) + "<br>";
//
// Message
//
if (wtx.mapValue.count("message") && !wtx.mapValue["message"].empty())
strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["message"], true) + "<br>";
if (wtx.mapValue.count("comment") && !wtx.mapValue["comment"].empty())
strHTML += "<br><b>" + tr("Comment") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["comment"], true) + "<br>";
strHTML += "<b>" + tr("Transaction ID") + ":</b> " + TransactionRecord::formatSubTxId(wtx.GetHash(), rec->idx) + "<br>";
if (wtx.IsCoinBase() || wtx.IsCoinStake())
strHTML += "<br>" + tr("Generated coins must mature 42 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \"not accepted\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.") + "<br>";
//
// Debug view
//
if (fDebug)
{
strHTML += "<hr><br>" + tr("Debug information") + "<br><br>";
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
if(wallet->IsMine(txin))
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatWithUnit(unit, -wallet->GetDebit(txin)) + "<br>";
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if(wallet->IsMine(txout))
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatWithUnit(unit, wallet->GetCredit(txout)) + "<br>";
strHTML += "<br><b>" + tr("Transaction") + ":</b><br>";
strHTML += GUIUtil::HtmlEscape(wtx.ToString(), true);
CTxDB txdb("r"); // To fetch source txouts
strHTML += "<br><b>" + tr("Inputs") + ":</b>";
strHTML += "<ul>";
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
COutPoint prevout = txin.prevout;
CTransaction prev;
if(txdb.ReadDiskTx(prevout.hash, prev))
{
if (prevout.n < prev.vout.size())
{
strHTML += "<li>";
const CTxOut &vout = prev.vout[prevout.n];
CTxDestination address;
if (ExtractDestination(vout.scriptPubKey, address))
{
if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + " ";
strHTML += QString::fromStdString(CBitcoinAddress(address).ToString());
}
strHTML = strHTML + " " + tr("Amount") + "=" + BitcoinUnits::formatWithUnit(unit, vout.nValue);
strHTML = strHTML + " IsMine=" + (wallet->IsMine(vout) ? tr("true") : tr("false")) + "</li>";
}
}
}
strHTML += "</ul>";
}
strHTML += "</font></html>";
return strHTML;
}
<|endoftext|>
|
<commit_before>#ifndef RDB_PROTOCOL_ERR_HPP_
#define RDB_PROTOCOL_ERR_HPP_
#include <list>
#include <string>
#include "utils.hpp"
#include "containers/archive/stl_types.hpp"
#include "rdb_protocol/ql2.pb.h"
#include "rdb_protocol/ql2_extensions.pb.h"
#include "rpc/serialize_macros.hpp"
namespace ql {
// NOTE: you usually want to inherit from `rcheckable_t` instead of calling this
// directly.
void runtime_check(const char *test, const char *file, int line,
bool pred, std::string msg, const Backtrace *bt_src,
int dummy_frames = 0);
void runtime_check(const char *test, const char *file, int line,
bool pred, std::string msg);
void runtime_sanity_check(bool test);
// Inherit from this in classes that wish to use `rcheck`. If a class is
// rcheckable, it means that you can call `rcheck` from within it or use it as a
// target for `rcheck_target`.
class rcheckable_t {
public:
virtual ~rcheckable_t() { }
virtual void runtime_check(const char *test, const char *file, int line,
bool pred, std::string msg) const = 0;
};
// This is a particular type of rcheckable. A `pb_rcheckable_t` corresponds to
// a part of the protobuf source tree, and can be used to produce a useful
// backtrace. (By contrast, a normal rcheckable might produce an error with no
// backtrace, e.g. if we some constratint that doesn't involve the user's code
// is violated.)
class pb_rcheckable_t : public rcheckable_t {
public:
explicit pb_rcheckable_t(const Term *t)
: bt_src(&t->GetExtension(ql2::extension::backtrace)) { }
explicit pb_rcheckable_t(const pb_rcheckable_t *rct)
: bt_src(rct->bt_src) { }
virtual void runtime_check(const char *test, const char *file, int line,
bool pred, std::string msg) const {
ql::runtime_check(test, file, line, pred, msg, bt_src);
}
// Propagate the associated backtrace through the rewrite term.
void propagate(Term *t) const;
private:
const Backtrace *bt_src;
};
// Use these macros to return errors to users.
#define rcheck_target(target, pred, msg) do { \
(pred) \
? (void)0 \
: (target)->runtime_check(stringify(pred), __FILE__, __LINE__, false, (msg)); \
} while (0)
#define rcheck_src(src, pred, msg) do { \
(pred) \
? (void)0 \
: ql::runtime_check(stringify(pred), __FILE__, __LINE__, false, (msg), (src)); \
} while (0)
#define rcheck(pred, msg) rcheck_target(this, pred, msg)
#define rcheck_toplevel(pred, msg) rcheck_src(0, pred, msg)
#define rfail_target(target, args...) do { \
rcheck_target(target, false, strprintf(args)); \
unreachable(); \
} while (0)
#define rfail(args...) do { \
rcheck(false, strprintf(args)); \
unreachable(); \
} while (0)
#define rfail_toplevel(args...) rcheck_toplevel(false, strprintf(args))
// r_sanity_check should be used in place of guarantee if you think the
// guarantee will almost always fail due to an error in the query logic rather
// than memory corruption.
#ifndef NDEBUG
#define r_sanity_check(test) guarantee(test)
#else
#define r_sanity_check(test) runtime_sanity_check(test)
#endif // NDEBUG
// A backtrace we return to the user. Pretty self-explanatory.
class backtrace_t {
public:
explicit backtrace_t(const Backtrace *bt) {
if (!bt) return;
for (int i = 0; i < bt->frames_size(); ++i) {
push_back(bt->frames(i));
}
}
backtrace_t() { }
class frame_t {
public:
explicit frame_t() : type(OPT), opt("UNITIALIZED") { }
explicit frame_t(int32_t _pos) : type(POS), pos(_pos) { }
explicit frame_t(const std::string &_opt) : type(OPT), opt(_opt) { }
explicit frame_t(const char *_opt) : type(OPT), opt(_opt) { }
explicit frame_t(const Frame &f);
Frame toproto() const;
static frame_t invalid() { return frame_t(INVALID); }
bool is_invalid() const { return type == POS && pos == INVALID; }
static frame_t head() { return frame_t(HEAD); }
bool is_head() const { return type == POS && pos == HEAD; }
static frame_t skip() { return frame_t(SKIP); }
bool is_skip() const { return type == POS && pos == SKIP; }
bool is_valid() { // -1 is the classic "invalid" frame
return is_head() || is_skip()
|| (type == POS && pos >= 0)
|| (type == OPT && opt != "UNINITIALIZED");
}
bool is_stream_funcall_frame() {
return type == POS && pos != 0;
}
private:
enum special_frames {
INVALID = -1,
HEAD = -2,
SKIP = -3
};
enum type_t { POS = 0, OPT = 1 };
int32_t type; // serialize macros didn't like `type_t` for some reason
int32_t pos;
std::string opt;
public:
RDB_MAKE_ME_SERIALIZABLE_3(type, pos, opt);
};
void fill_bt(Backtrace *bt) const;
// Write out the backtrace to return it to the user.
void fill_error(Response *res, Response_ResponseType type, std::string msg) const;
RDB_MAKE_ME_SERIALIZABLE_1(frames);
bool is_empty() { return frames.size() == 0; }
void delete_frames(int num_frames) {
for (int i = 0; i < num_frames; ++i) {
if (frames.size() == 0) {
rassert(false);
} else {
frames.pop_back();
}
}
}
private:
// Push a frame onto the back of the backtrace.
void push_back(frame_t f) {
r_sanity_check(f.is_valid());
frames.push_back(f);
}
template<class T>
void push_back(T t) {
push_back(frame_t(t));
}
std::list<frame_t> frames;
};
const backtrace_t::frame_t head_frame = backtrace_t::frame_t::head();
// Catch this if you want to handle either `exc_t` or `datum_exc_t`.
class base_exc_t : public std::exception {
public:
virtual ~base_exc_t() throw () { }
};
// A RQL exception.
class exc_t : public base_exc_t {
public:
// We have a default constructor because these are serialized.
exc_t() : exc_msg("UNINITIALIZED") { }
exc_t(const std::string &_exc_msg, const Backtrace *bt_src, int dummy_frames = 0)
: exc_msg(_exc_msg) {
if (bt_src) set_backtrace(bt_src);
backtrace.delete_frames(dummy_frames);
}
exc_t(const std::string &_exc_msg, const backtrace_t &_backtrace,
int dummy_frames = 0)
: backtrace(_backtrace), exc_msg(_exc_msg) {
backtrace.delete_frames(dummy_frames);
}
virtual ~exc_t() throw () { }
const char *what() const throw () { return exc_msg.c_str(); }
RDB_MAKE_ME_SERIALIZABLE_2(backtrace, exc_msg);
template<class T>
void set_backtrace(const T *t) {
r_sanity_check(backtrace.is_empty());
backtrace = backtrace_t(t);
}
backtrace_t backtrace;
private:
std::string exc_msg;
};
// A datum exception is like a normal RQL exception, except it doesn't
// correspond to part of the source tree. It's usually thrown from inside
// datum.{hpp,cc} and must be caught by the enclosing term/stream/whatever and
// turned into a normal `exc_t`.
class datum_exc_t : public base_exc_t {
public:
datum_exc_t() : exc_msg("UNINITIALIZED") { }
explicit datum_exc_t(const std::string &_exc_msg) : exc_msg(_exc_msg) { }
virtual ~datum_exc_t() throw () { }
const char *what() const throw () { return exc_msg.c_str(); }
private:
std::string exc_msg;
public:
RDB_MAKE_ME_SERIALIZABLE_1(exc_msg);
};
void fill_error(Response *res, Response_ResponseType type, std::string msg,
const backtrace_t &bt = backtrace_t());
} // namespace ql
#endif // RDB_PROTOCOL_ERR_HPP_
<commit_msg>Made pb_rcheckable_t::set_backtrace be not templatized.<commit_after>#ifndef RDB_PROTOCOL_ERR_HPP_
#define RDB_PROTOCOL_ERR_HPP_
#include <list>
#include <string>
#include "utils.hpp"
#include "containers/archive/stl_types.hpp"
#include "rdb_protocol/ql2.pb.h"
#include "rdb_protocol/ql2_extensions.pb.h"
#include "rpc/serialize_macros.hpp"
namespace ql {
// NOTE: you usually want to inherit from `rcheckable_t` instead of calling this
// directly.
void runtime_check(const char *test, const char *file, int line,
bool pred, std::string msg, const Backtrace *bt_src,
int dummy_frames = 0);
void runtime_check(const char *test, const char *file, int line,
bool pred, std::string msg);
void runtime_sanity_check(bool test);
// Inherit from this in classes that wish to use `rcheck`. If a class is
// rcheckable, it means that you can call `rcheck` from within it or use it as a
// target for `rcheck_target`.
class rcheckable_t {
public:
virtual ~rcheckable_t() { }
virtual void runtime_check(const char *test, const char *file, int line,
bool pred, std::string msg) const = 0;
};
// This is a particular type of rcheckable. A `pb_rcheckable_t` corresponds to
// a part of the protobuf source tree, and can be used to produce a useful
// backtrace. (By contrast, a normal rcheckable might produce an error with no
// backtrace, e.g. if we some constratint that doesn't involve the user's code
// is violated.)
class pb_rcheckable_t : public rcheckable_t {
public:
explicit pb_rcheckable_t(const Term *t)
: bt_src(&t->GetExtension(ql2::extension::backtrace)) { }
explicit pb_rcheckable_t(const pb_rcheckable_t *rct)
: bt_src(rct->bt_src) { }
virtual void runtime_check(const char *test, const char *file, int line,
bool pred, std::string msg) const {
ql::runtime_check(test, file, line, pred, msg, bt_src);
}
// Propagate the associated backtrace through the rewrite term.
void propagate(Term *t) const;
private:
const Backtrace *bt_src;
};
// Use these macros to return errors to users.
#define rcheck_target(target, pred, msg) do { \
(pred) \
? (void)0 \
: (target)->runtime_check(stringify(pred), __FILE__, __LINE__, false, (msg)); \
} while (0)
#define rcheck_src(src, pred, msg) do { \
(pred) \
? (void)0 \
: ql::runtime_check(stringify(pred), __FILE__, __LINE__, false, (msg), (src)); \
} while (0)
#define rcheck(pred, msg) rcheck_target(this, pred, msg)
#define rcheck_toplevel(pred, msg) rcheck_src(0, pred, msg)
#define rfail_target(target, args...) do { \
rcheck_target(target, false, strprintf(args)); \
unreachable(); \
} while (0)
#define rfail(args...) do { \
rcheck(false, strprintf(args)); \
unreachable(); \
} while (0)
#define rfail_toplevel(args...) rcheck_toplevel(false, strprintf(args))
// r_sanity_check should be used in place of guarantee if you think the
// guarantee will almost always fail due to an error in the query logic rather
// than memory corruption.
#ifndef NDEBUG
#define r_sanity_check(test) guarantee(test)
#else
#define r_sanity_check(test) runtime_sanity_check(test)
#endif // NDEBUG
// A backtrace we return to the user. Pretty self-explanatory.
class backtrace_t {
public:
explicit backtrace_t(const Backtrace *bt) {
if (!bt) return;
for (int i = 0; i < bt->frames_size(); ++i) {
push_back(bt->frames(i));
}
}
backtrace_t() { }
class frame_t {
public:
explicit frame_t() : type(OPT), opt("UNITIALIZED") { }
explicit frame_t(int32_t _pos) : type(POS), pos(_pos) { }
explicit frame_t(const std::string &_opt) : type(OPT), opt(_opt) { }
explicit frame_t(const char *_opt) : type(OPT), opt(_opt) { }
explicit frame_t(const Frame &f);
Frame toproto() const;
static frame_t invalid() { return frame_t(INVALID); }
bool is_invalid() const { return type == POS && pos == INVALID; }
static frame_t head() { return frame_t(HEAD); }
bool is_head() const { return type == POS && pos == HEAD; }
static frame_t skip() { return frame_t(SKIP); }
bool is_skip() const { return type == POS && pos == SKIP; }
bool is_valid() { // -1 is the classic "invalid" frame
return is_head() || is_skip()
|| (type == POS && pos >= 0)
|| (type == OPT && opt != "UNINITIALIZED");
}
bool is_stream_funcall_frame() {
return type == POS && pos != 0;
}
private:
enum special_frames {
INVALID = -1,
HEAD = -2,
SKIP = -3
};
enum type_t { POS = 0, OPT = 1 };
int32_t type; // serialize macros didn't like `type_t` for some reason
int32_t pos;
std::string opt;
public:
RDB_MAKE_ME_SERIALIZABLE_3(type, pos, opt);
};
void fill_bt(Backtrace *bt) const;
// Write out the backtrace to return it to the user.
void fill_error(Response *res, Response_ResponseType type, std::string msg) const;
RDB_MAKE_ME_SERIALIZABLE_1(frames);
bool is_empty() { return frames.size() == 0; }
void delete_frames(int num_frames) {
for (int i = 0; i < num_frames; ++i) {
if (frames.size() == 0) {
rassert(false);
} else {
frames.pop_back();
}
}
}
private:
// Push a frame onto the back of the backtrace.
void push_back(frame_t f) {
r_sanity_check(f.is_valid());
frames.push_back(f);
}
template<class T>
void push_back(T t) {
push_back(frame_t(t));
}
std::list<frame_t> frames;
};
const backtrace_t::frame_t head_frame = backtrace_t::frame_t::head();
// Catch this if you want to handle either `exc_t` or `datum_exc_t`.
class base_exc_t : public std::exception {
public:
virtual ~base_exc_t() throw () { }
};
// A RQL exception.
class exc_t : public base_exc_t {
public:
// We have a default constructor because these are serialized.
exc_t() : exc_msg("UNINITIALIZED") { }
exc_t(const std::string &_exc_msg, const Backtrace *bt_src, int dummy_frames = 0)
: exc_msg(_exc_msg) {
// SAMRSI: Stupid null pointer arg.
if (bt_src != NULL) {
set_backtrace(backtrace_t(bt_src));
}
backtrace.delete_frames(dummy_frames);
}
exc_t(const std::string &_exc_msg, const backtrace_t &_backtrace,
int dummy_frames = 0)
: backtrace(_backtrace), exc_msg(_exc_msg) {
backtrace.delete_frames(dummy_frames);
}
virtual ~exc_t() throw () { }
const char *what() const throw () { return exc_msg.c_str(); }
RDB_MAKE_ME_SERIALIZABLE_2(backtrace, exc_msg);
// SAMRSI: Rename to init_backtrace.
void set_backtrace(const backtrace_t &bt) {
r_sanity_check(backtrace.is_empty());
backtrace = bt;
}
backtrace_t backtrace;
private:
std::string exc_msg;
};
// A datum exception is like a normal RQL exception, except it doesn't
// correspond to part of the source tree. It's usually thrown from inside
// datum.{hpp,cc} and must be caught by the enclosing term/stream/whatever and
// turned into a normal `exc_t`.
class datum_exc_t : public base_exc_t {
public:
datum_exc_t() : exc_msg("UNINITIALIZED") { }
explicit datum_exc_t(const std::string &_exc_msg) : exc_msg(_exc_msg) { }
virtual ~datum_exc_t() throw () { }
const char *what() const throw () { return exc_msg.c_str(); }
private:
std::string exc_msg;
public:
RDB_MAKE_ME_SERIALIZABLE_1(exc_msg);
};
void fill_error(Response *res, Response_ResponseType type, std::string msg,
const backtrace_t &bt = backtrace_t());
} // namespace ql
#endif // RDB_PROTOCOL_ERR_HPP_
<|endoftext|>
|
<commit_before>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkPaint.h"
#include "SkRandom.h"
// skbug.com/1316 shows that this cubic, when slightly clipped, creates big
// (incorrect) changes to its control points.
class ClippedCubicGM : public skiagm::GM {
public:
ClippedCubicGM() {}
protected:
SkString onShortName() {
return SkString("clippedcubic");
}
SkISize onISize() { return SkISize::Make(1240, 390); }
virtual void onDraw(SkCanvas* canvas) {
SkPath path;
path.moveTo(0, 0);
path.cubicTo(140, 150, 40, 10, 170, 150);
SkPaint paint;
SkRect bounds = path.getBounds();
for (int dy = -1; dy <= 1; ++dy) {
canvas->save();
for (int dx = -1; dx <= 1; ++dx) {
canvas->save();
canvas->clipRect(bounds);
canvas->translate(dx, dy);
canvas->drawPath(path, paint);
canvas->restore();
canvas->translate(bounds.width(), 0);
}
canvas->restore();
canvas->translate(0, bounds.height());
}
}
private:
typedef skiagm::GM INHERITED;
};
class CubicPathGM : public skiagm::GM {
public:
CubicPathGM() {}
protected:
SkString onShortName() {
return SkString("cubicpath");
}
SkISize onISize() { return SkISize::Make(1240, 390); }
void drawPath(SkPath& path,SkCanvas* canvas,SkColor color,
const SkRect& clip,SkPaint::Cap cap, SkPaint::Join join,
SkPaint::Style style, SkPath::FillType fill,
SkScalar strokeWidth) {
path.setFillType(fill);
SkPaint paint;
paint.setStrokeCap(cap);
paint.setStrokeWidth(strokeWidth);
paint.setStrokeJoin(join);
paint.setColor(color);
paint.setStyle(style);
canvas->save();
canvas->clipRect(clip);
canvas->drawPath(path, paint);
canvas->restore();
}
virtual void onDraw(SkCanvas* canvas) {
struct FillAndName {
SkPath::FillType fFill;
const char* fName;
};
static const FillAndName gFills[] = {
{SkPath::kWinding_FillType, "Winding"},
{SkPath::kEvenOdd_FillType, "Even / Odd"},
{SkPath::kInverseWinding_FillType, "Inverse Winding"},
{SkPath::kInverseEvenOdd_FillType, "Inverse Even / Odd"},
};
struct StyleAndName {
SkPaint::Style fStyle;
const char* fName;
};
static const StyleAndName gStyles[] = {
{SkPaint::kFill_Style, "Fill"},
{SkPaint::kStroke_Style, "Stroke"},
{SkPaint::kStrokeAndFill_Style, "Stroke And Fill"},
};
struct CapAndName {
SkPaint::Cap fCap;
SkPaint::Join fJoin;
const char* fName;
};
static const CapAndName gCaps[] = {
{SkPaint::kButt_Cap, SkPaint::kBevel_Join, "Butt"},
{SkPaint::kRound_Cap, SkPaint::kRound_Join, "Round"},
{SkPaint::kSquare_Cap, SkPaint::kBevel_Join, "Square"}
};
struct PathAndName {
SkPath fPath;
const char* fName;
};
PathAndName path;
path.fPath.moveTo(25*SK_Scalar1, 10*SK_Scalar1);
path.fPath.cubicTo(40*SK_Scalar1, 20*SK_Scalar1,
60*SK_Scalar1, 20*SK_Scalar1,
75*SK_Scalar1, 10*SK_Scalar1);
path.fName = "moveTo-cubic";
SkPaint titlePaint;
titlePaint.setColor(SK_ColorBLACK);
titlePaint.setAntiAlias(true);
titlePaint.setLCDRenderText(true);
titlePaint.setTextSize(15 * SK_Scalar1);
const char title[] = "Cubic Drawn Into Rectangle Clips With "
"Indicated Style, Fill and Linecaps, with stroke width 10";
canvas->drawText(title, strlen(title),
20 * SK_Scalar1,
20 * SK_Scalar1,
titlePaint);
SkRandom rand;
SkRect rect = SkRect::MakeWH(100*SK_Scalar1, 30*SK_Scalar1);
canvas->save();
canvas->translate(10 * SK_Scalar1, 30 * SK_Scalar1);
canvas->save();
for (size_t cap = 0; cap < SK_ARRAY_COUNT(gCaps); ++cap) {
if (0 < cap) {
canvas->translate((rect.width() + 40 * SK_Scalar1) * SK_ARRAY_COUNT(gStyles), 0);
}
canvas->save();
for (size_t fill = 0; fill < SK_ARRAY_COUNT(gFills); ++fill) {
if (0 < fill) {
canvas->translate(0, rect.height() + 40 * SK_Scalar1);
}
canvas->save();
for (size_t style = 0; style < SK_ARRAY_COUNT(gStyles); ++style) {
if (0 < style) {
canvas->translate(rect.width() + 40 * SK_Scalar1, 0);
}
SkColor color = 0xff007000;
this->drawPath(path.fPath, canvas, color, rect,
gCaps[cap].fCap, gCaps[cap].fJoin, gStyles[style].fStyle,
gFills[fill].fFill, SK_Scalar1*10);
SkPaint rectPaint;
rectPaint.setColor(SK_ColorBLACK);
rectPaint.setStyle(SkPaint::kStroke_Style);
rectPaint.setStrokeWidth(-1);
rectPaint.setAntiAlias(true);
canvas->drawRect(rect, rectPaint);
SkPaint labelPaint;
labelPaint.setColor(color);
labelPaint.setAntiAlias(true);
labelPaint.setLCDRenderText(true);
labelPaint.setTextSize(10 * SK_Scalar1);
canvas->drawText(gStyles[style].fName,
strlen(gStyles[style].fName),
0, rect.height() + 12 * SK_Scalar1,
labelPaint);
canvas->drawText(gFills[fill].fName,
strlen(gFills[fill].fName),
0, rect.height() + 24 * SK_Scalar1,
labelPaint);
canvas->drawText(gCaps[cap].fName,
strlen(gCaps[cap].fName),
0, rect.height() + 36 * SK_Scalar1,
labelPaint);
}
canvas->restore();
}
canvas->restore();
}
canvas->restore();
canvas->restore();
}
private:
typedef skiagm::GM INHERITED;
};
class CubicClosePathGM : public skiagm::GM {
public:
CubicClosePathGM() {}
protected:
SkString onShortName() {
return SkString("cubicclosepath");
}
SkISize onISize() { return SkISize::Make(1240, 390); }
void drawPath(SkPath& path,SkCanvas* canvas,SkColor color,
const SkRect& clip,SkPaint::Cap cap, SkPaint::Join join,
SkPaint::Style style, SkPath::FillType fill,
SkScalar strokeWidth) {
path.setFillType(fill);
SkPaint paint;
paint.setStrokeCap(cap);
paint.setStrokeWidth(strokeWidth);
paint.setStrokeJoin(join);
paint.setColor(color);
paint.setStyle(style);
canvas->save();
canvas->clipRect(clip);
canvas->drawPath(path, paint);
canvas->restore();
}
virtual void onDraw(SkCanvas* canvas) {
struct FillAndName {
SkPath::FillType fFill;
const char* fName;
};
static const FillAndName gFills[] = {
{SkPath::kWinding_FillType, "Winding"},
{SkPath::kEvenOdd_FillType, "Even / Odd"},
{SkPath::kInverseWinding_FillType, "Inverse Winding"},
{SkPath::kInverseEvenOdd_FillType, "Inverse Even / Odd"},
};
struct StyleAndName {
SkPaint::Style fStyle;
const char* fName;
};
static const StyleAndName gStyles[] = {
{SkPaint::kFill_Style, "Fill"},
{SkPaint::kStroke_Style, "Stroke"},
{SkPaint::kStrokeAndFill_Style, "Stroke And Fill"},
};
struct CapAndName {
SkPaint::Cap fCap;
SkPaint::Join fJoin;
const char* fName;
};
static const CapAndName gCaps[] = {
{SkPaint::kButt_Cap, SkPaint::kBevel_Join, "Butt"},
{SkPaint::kRound_Cap, SkPaint::kRound_Join, "Round"},
{SkPaint::kSquare_Cap, SkPaint::kBevel_Join, "Square"}
};
struct PathAndName {
SkPath fPath;
const char* fName;
};
PathAndName path;
path.fPath.moveTo(25*SK_Scalar1, 10*SK_Scalar1);
path.fPath.cubicTo(40*SK_Scalar1, 20*SK_Scalar1,
60*SK_Scalar1, 20*SK_Scalar1,
75*SK_Scalar1, 10*SK_Scalar1);
path.fPath.close();
path.fName = "moveTo-cubic-close";
SkPaint titlePaint;
titlePaint.setColor(SK_ColorBLACK);
titlePaint.setAntiAlias(true);
titlePaint.setLCDRenderText(true);
titlePaint.setTextSize(15 * SK_Scalar1);
const char title[] = "Cubic Closed Drawn Into Rectangle Clips With "
"Indicated Style, Fill and Linecaps, with stroke width 10";
canvas->drawText(title, strlen(title),
20 * SK_Scalar1,
20 * SK_Scalar1,
titlePaint);
SkRandom rand;
SkRect rect = SkRect::MakeWH(100*SK_Scalar1, 30*SK_Scalar1);
canvas->save();
canvas->translate(10 * SK_Scalar1, 30 * SK_Scalar1);
canvas->save();
for (size_t cap = 0; cap < SK_ARRAY_COUNT(gCaps); ++cap) {
if (0 < cap) {
canvas->translate((rect.width() + 40 * SK_Scalar1) * SK_ARRAY_COUNT(gStyles), 0);
}
canvas->save();
for (size_t fill = 0; fill < SK_ARRAY_COUNT(gFills); ++fill) {
if (0 < fill) {
canvas->translate(0, rect.height() + 40 * SK_Scalar1);
}
canvas->save();
for (size_t style = 0; style < SK_ARRAY_COUNT(gStyles); ++style) {
if (0 < style) {
canvas->translate(rect.width() + 40 * SK_Scalar1, 0);
}
SkColor color = 0xff007000;
this->drawPath(path.fPath, canvas, color, rect,
gCaps[cap].fCap, gCaps[cap].fJoin, gStyles[style].fStyle,
gFills[fill].fFill, SK_Scalar1*10);
SkPaint rectPaint;
rectPaint.setColor(SK_ColorBLACK);
rectPaint.setStyle(SkPaint::kStroke_Style);
rectPaint.setStrokeWidth(-1);
rectPaint.setAntiAlias(true);
canvas->drawRect(rect, rectPaint);
SkPaint labelPaint;
labelPaint.setColor(color);
labelPaint.setAntiAlias(true);
labelPaint.setLCDRenderText(true);
labelPaint.setTextSize(10 * SK_Scalar1);
canvas->drawText(gStyles[style].fName,
strlen(gStyles[style].fName),
0, rect.height() + 12 * SK_Scalar1,
labelPaint);
canvas->drawText(gFills[fill].fName,
strlen(gFills[fill].fName),
0, rect.height() + 24 * SK_Scalar1,
labelPaint);
canvas->drawText(gCaps[cap].fName,
strlen(gCaps[cap].fName),
0, rect.height() + 36 * SK_Scalar1,
labelPaint);
}
canvas->restore();
}
canvas->restore();
}
canvas->restore();
canvas->restore();
}
private:
typedef skiagm::GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
DEF_GM( return new CubicPathGM; )
DEF_GM( return new CubicClosePathGM; )
DEF_GM( return new ClippedCubicGM; )
<commit_msg>use SkScalar instead of int for loops, to avoid warning in canvas->translate() calls<commit_after>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkPaint.h"
#include "SkRandom.h"
// skbug.com/1316 shows that this cubic, when slightly clipped, creates big
// (incorrect) changes to its control points.
class ClippedCubicGM : public skiagm::GM {
public:
ClippedCubicGM() {}
protected:
SkString onShortName() {
return SkString("clippedcubic");
}
SkISize onISize() { return SkISize::Make(1240, 390); }
virtual void onDraw(SkCanvas* canvas) {
SkPath path;
path.moveTo(0, 0);
path.cubicTo(140, 150, 40, 10, 170, 150);
SkPaint paint;
SkRect bounds = path.getBounds();
for (SkScalar dy = -1; dy <= 1; dy += 1) {
canvas->save();
for (SkScalar dx = -1; dx <= 1; dx += 1) {
canvas->save();
canvas->clipRect(bounds);
canvas->translate(dx, dy);
canvas->drawPath(path, paint);
canvas->restore();
canvas->translate(bounds.width(), 0);
}
canvas->restore();
canvas->translate(0, bounds.height());
}
}
private:
typedef skiagm::GM INHERITED;
};
class CubicPathGM : public skiagm::GM {
public:
CubicPathGM() {}
protected:
SkString onShortName() {
return SkString("cubicpath");
}
SkISize onISize() { return SkISize::Make(1240, 390); }
void drawPath(SkPath& path,SkCanvas* canvas,SkColor color,
const SkRect& clip,SkPaint::Cap cap, SkPaint::Join join,
SkPaint::Style style, SkPath::FillType fill,
SkScalar strokeWidth) {
path.setFillType(fill);
SkPaint paint;
paint.setStrokeCap(cap);
paint.setStrokeWidth(strokeWidth);
paint.setStrokeJoin(join);
paint.setColor(color);
paint.setStyle(style);
canvas->save();
canvas->clipRect(clip);
canvas->drawPath(path, paint);
canvas->restore();
}
virtual void onDraw(SkCanvas* canvas) {
struct FillAndName {
SkPath::FillType fFill;
const char* fName;
};
static const FillAndName gFills[] = {
{SkPath::kWinding_FillType, "Winding"},
{SkPath::kEvenOdd_FillType, "Even / Odd"},
{SkPath::kInverseWinding_FillType, "Inverse Winding"},
{SkPath::kInverseEvenOdd_FillType, "Inverse Even / Odd"},
};
struct StyleAndName {
SkPaint::Style fStyle;
const char* fName;
};
static const StyleAndName gStyles[] = {
{SkPaint::kFill_Style, "Fill"},
{SkPaint::kStroke_Style, "Stroke"},
{SkPaint::kStrokeAndFill_Style, "Stroke And Fill"},
};
struct CapAndName {
SkPaint::Cap fCap;
SkPaint::Join fJoin;
const char* fName;
};
static const CapAndName gCaps[] = {
{SkPaint::kButt_Cap, SkPaint::kBevel_Join, "Butt"},
{SkPaint::kRound_Cap, SkPaint::kRound_Join, "Round"},
{SkPaint::kSquare_Cap, SkPaint::kBevel_Join, "Square"}
};
struct PathAndName {
SkPath fPath;
const char* fName;
};
PathAndName path;
path.fPath.moveTo(25*SK_Scalar1, 10*SK_Scalar1);
path.fPath.cubicTo(40*SK_Scalar1, 20*SK_Scalar1,
60*SK_Scalar1, 20*SK_Scalar1,
75*SK_Scalar1, 10*SK_Scalar1);
path.fName = "moveTo-cubic";
SkPaint titlePaint;
titlePaint.setColor(SK_ColorBLACK);
titlePaint.setAntiAlias(true);
titlePaint.setLCDRenderText(true);
titlePaint.setTextSize(15 * SK_Scalar1);
const char title[] = "Cubic Drawn Into Rectangle Clips With "
"Indicated Style, Fill and Linecaps, with stroke width 10";
canvas->drawText(title, strlen(title),
20 * SK_Scalar1,
20 * SK_Scalar1,
titlePaint);
SkRandom rand;
SkRect rect = SkRect::MakeWH(100*SK_Scalar1, 30*SK_Scalar1);
canvas->save();
canvas->translate(10 * SK_Scalar1, 30 * SK_Scalar1);
canvas->save();
for (size_t cap = 0; cap < SK_ARRAY_COUNT(gCaps); ++cap) {
if (0 < cap) {
canvas->translate((rect.width() + 40 * SK_Scalar1) * SK_ARRAY_COUNT(gStyles), 0);
}
canvas->save();
for (size_t fill = 0; fill < SK_ARRAY_COUNT(gFills); ++fill) {
if (0 < fill) {
canvas->translate(0, rect.height() + 40 * SK_Scalar1);
}
canvas->save();
for (size_t style = 0; style < SK_ARRAY_COUNT(gStyles); ++style) {
if (0 < style) {
canvas->translate(rect.width() + 40 * SK_Scalar1, 0);
}
SkColor color = 0xff007000;
this->drawPath(path.fPath, canvas, color, rect,
gCaps[cap].fCap, gCaps[cap].fJoin, gStyles[style].fStyle,
gFills[fill].fFill, SK_Scalar1*10);
SkPaint rectPaint;
rectPaint.setColor(SK_ColorBLACK);
rectPaint.setStyle(SkPaint::kStroke_Style);
rectPaint.setStrokeWidth(-1);
rectPaint.setAntiAlias(true);
canvas->drawRect(rect, rectPaint);
SkPaint labelPaint;
labelPaint.setColor(color);
labelPaint.setAntiAlias(true);
labelPaint.setLCDRenderText(true);
labelPaint.setTextSize(10 * SK_Scalar1);
canvas->drawText(gStyles[style].fName,
strlen(gStyles[style].fName),
0, rect.height() + 12 * SK_Scalar1,
labelPaint);
canvas->drawText(gFills[fill].fName,
strlen(gFills[fill].fName),
0, rect.height() + 24 * SK_Scalar1,
labelPaint);
canvas->drawText(gCaps[cap].fName,
strlen(gCaps[cap].fName),
0, rect.height() + 36 * SK_Scalar1,
labelPaint);
}
canvas->restore();
}
canvas->restore();
}
canvas->restore();
canvas->restore();
}
private:
typedef skiagm::GM INHERITED;
};
class CubicClosePathGM : public skiagm::GM {
public:
CubicClosePathGM() {}
protected:
SkString onShortName() {
return SkString("cubicclosepath");
}
SkISize onISize() { return SkISize::Make(1240, 390); }
void drawPath(SkPath& path,SkCanvas* canvas,SkColor color,
const SkRect& clip,SkPaint::Cap cap, SkPaint::Join join,
SkPaint::Style style, SkPath::FillType fill,
SkScalar strokeWidth) {
path.setFillType(fill);
SkPaint paint;
paint.setStrokeCap(cap);
paint.setStrokeWidth(strokeWidth);
paint.setStrokeJoin(join);
paint.setColor(color);
paint.setStyle(style);
canvas->save();
canvas->clipRect(clip);
canvas->drawPath(path, paint);
canvas->restore();
}
virtual void onDraw(SkCanvas* canvas) {
struct FillAndName {
SkPath::FillType fFill;
const char* fName;
};
static const FillAndName gFills[] = {
{SkPath::kWinding_FillType, "Winding"},
{SkPath::kEvenOdd_FillType, "Even / Odd"},
{SkPath::kInverseWinding_FillType, "Inverse Winding"},
{SkPath::kInverseEvenOdd_FillType, "Inverse Even / Odd"},
};
struct StyleAndName {
SkPaint::Style fStyle;
const char* fName;
};
static const StyleAndName gStyles[] = {
{SkPaint::kFill_Style, "Fill"},
{SkPaint::kStroke_Style, "Stroke"},
{SkPaint::kStrokeAndFill_Style, "Stroke And Fill"},
};
struct CapAndName {
SkPaint::Cap fCap;
SkPaint::Join fJoin;
const char* fName;
};
static const CapAndName gCaps[] = {
{SkPaint::kButt_Cap, SkPaint::kBevel_Join, "Butt"},
{SkPaint::kRound_Cap, SkPaint::kRound_Join, "Round"},
{SkPaint::kSquare_Cap, SkPaint::kBevel_Join, "Square"}
};
struct PathAndName {
SkPath fPath;
const char* fName;
};
PathAndName path;
path.fPath.moveTo(25*SK_Scalar1, 10*SK_Scalar1);
path.fPath.cubicTo(40*SK_Scalar1, 20*SK_Scalar1,
60*SK_Scalar1, 20*SK_Scalar1,
75*SK_Scalar1, 10*SK_Scalar1);
path.fPath.close();
path.fName = "moveTo-cubic-close";
SkPaint titlePaint;
titlePaint.setColor(SK_ColorBLACK);
titlePaint.setAntiAlias(true);
titlePaint.setLCDRenderText(true);
titlePaint.setTextSize(15 * SK_Scalar1);
const char title[] = "Cubic Closed Drawn Into Rectangle Clips With "
"Indicated Style, Fill and Linecaps, with stroke width 10";
canvas->drawText(title, strlen(title),
20 * SK_Scalar1,
20 * SK_Scalar1,
titlePaint);
SkRandom rand;
SkRect rect = SkRect::MakeWH(100*SK_Scalar1, 30*SK_Scalar1);
canvas->save();
canvas->translate(10 * SK_Scalar1, 30 * SK_Scalar1);
canvas->save();
for (size_t cap = 0; cap < SK_ARRAY_COUNT(gCaps); ++cap) {
if (0 < cap) {
canvas->translate((rect.width() + 40 * SK_Scalar1) * SK_ARRAY_COUNT(gStyles), 0);
}
canvas->save();
for (size_t fill = 0; fill < SK_ARRAY_COUNT(gFills); ++fill) {
if (0 < fill) {
canvas->translate(0, rect.height() + 40 * SK_Scalar1);
}
canvas->save();
for (size_t style = 0; style < SK_ARRAY_COUNT(gStyles); ++style) {
if (0 < style) {
canvas->translate(rect.width() + 40 * SK_Scalar1, 0);
}
SkColor color = 0xff007000;
this->drawPath(path.fPath, canvas, color, rect,
gCaps[cap].fCap, gCaps[cap].fJoin, gStyles[style].fStyle,
gFills[fill].fFill, SK_Scalar1*10);
SkPaint rectPaint;
rectPaint.setColor(SK_ColorBLACK);
rectPaint.setStyle(SkPaint::kStroke_Style);
rectPaint.setStrokeWidth(-1);
rectPaint.setAntiAlias(true);
canvas->drawRect(rect, rectPaint);
SkPaint labelPaint;
labelPaint.setColor(color);
labelPaint.setAntiAlias(true);
labelPaint.setLCDRenderText(true);
labelPaint.setTextSize(10 * SK_Scalar1);
canvas->drawText(gStyles[style].fName,
strlen(gStyles[style].fName),
0, rect.height() + 12 * SK_Scalar1,
labelPaint);
canvas->drawText(gFills[fill].fName,
strlen(gFills[fill].fName),
0, rect.height() + 24 * SK_Scalar1,
labelPaint);
canvas->drawText(gCaps[cap].fName,
strlen(gCaps[cap].fName),
0, rect.height() + 36 * SK_Scalar1,
labelPaint);
}
canvas->restore();
}
canvas->restore();
}
canvas->restore();
canvas->restore();
}
private:
typedef skiagm::GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
DEF_GM( return new CubicPathGM; )
DEF_GM( return new CubicClosePathGM; )
DEF_GM( return new ClippedCubicGM; )
<|endoftext|>
|
<commit_before>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkImage.h"
#include "SkImageCacherator.h"
#include "SkPictureRecorder.h"
#include "SkSurface.h"
#if SK_SUPPORT_GPU
#include "GrContext.h"
#include "GrTexture.h"
#include "../src/image/SkImage_Gpu.h"
#endif
static void draw_something(SkCanvas* canvas, const SkRect& bounds) {
SkPaint paint;
paint.setAntiAlias(true);
paint.setColor(SK_ColorRED);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(10);
canvas->drawRect(bounds, paint);
paint.setStyle(SkPaint::kFill_Style);
paint.setColor(SK_ColorBLUE);
canvas->drawOval(bounds, paint);
}
/*
* Exercise drawing pictures inside an image, showing that the image version is pixelated
* (correctly) when it is inside an image.
*/
class ImagePictGM : public skiagm::GM {
SkAutoTUnref<SkPicture> fPicture;
SkAutoTUnref<SkImage> fImage0;
SkAutoTUnref<SkImage> fImage1;
public:
ImagePictGM() {}
protected:
SkString onShortName() override {
return SkString("image-picture");
}
SkISize onISize() override {
return SkISize::Make(850, 450);
}
void onOnceBeforeDraw() override {
const SkRect bounds = SkRect::MakeXYWH(100, 100, 100, 100);
SkPictureRecorder recorder;
draw_something(recorder.beginRecording(bounds), bounds);
fPicture.reset(recorder.endRecording());
// extract enough just for the oval.
const SkISize size = SkISize::Make(100, 100);
SkMatrix matrix;
matrix.setTranslate(-100, -100);
fImage0.reset(SkImage::NewFromPicture(fPicture, size, &matrix, nullptr));
matrix.postTranslate(-50, -50);
matrix.postRotate(45);
matrix.postTranslate(50, 50);
fImage1.reset(SkImage::NewFromPicture(fPicture, size, &matrix, nullptr));
}
void drawSet(SkCanvas* canvas) const {
SkMatrix matrix = SkMatrix::MakeTrans(-100, -100);
canvas->drawPicture(fPicture, &matrix, nullptr);
canvas->drawImage(fImage0, 150, 0);
canvas->drawImage(fImage1, 300, 0);
}
void onDraw(SkCanvas* canvas) override {
canvas->translate(20, 20);
this->drawSet(canvas);
canvas->save();
canvas->translate(0, 130);
canvas->scale(0.25f, 0.25f);
this->drawSet(canvas);
canvas->restore();
canvas->save();
canvas->translate(0, 200);
canvas->scale(2, 2);
this->drawSet(canvas);
canvas->restore();
}
private:
typedef skiagm::GM INHERITED;
};
DEF_GM( return new ImagePictGM; )
///////////////////////////////////////////////////////////////////////////////////////////////////
static SkImageGenerator* make_pic_generator(GrContext*, SkPicture* pic) {
SkMatrix matrix;
matrix.setTranslate(-100, -100);
return SkImageGenerator::NewFromPicture(SkISize::Make(100, 100), pic, &matrix, nullptr);
}
class RasterGenerator : public SkImageGenerator {
public:
RasterGenerator(const SkBitmap& bm) : SkImageGenerator(bm.info()), fBM(bm) {}
protected:
bool onGetPixels(const SkImageInfo& info, void* pixels, size_t rowBytes,
SkPMColor*, int*) override {
return fBM.readPixels(info, pixels, rowBytes, 0, 0);
}
private:
SkBitmap fBM;
};
static SkImageGenerator* make_ras_generator(GrContext*, SkPicture* pic) {
SkBitmap bm;
bm.allocN32Pixels(100, 100);
SkCanvas canvas(bm);
canvas.clear(0);
canvas.translate(-100, -100);
canvas.drawPicture(pic);
return new RasterGenerator(bm);
}
class EmptyGenerator : public SkImageGenerator {
public:
EmptyGenerator(const SkImageInfo& info) : SkImageGenerator(info) {}
};
#if SK_SUPPORT_GPU
class TextureGenerator : public SkImageGenerator {
public:
TextureGenerator(GrContext* ctx, const SkImageInfo& info, SkPicture* pic)
: SkImageGenerator(info)
, fCtx(SkRef(ctx))
{
SkAutoTUnref<SkSurface> surface(SkSurface::NewRenderTarget(ctx, SkSurface::kNo_Budgeted,
info, 0));
surface->getCanvas()->clear(0);
surface->getCanvas()->translate(-100, -100);
surface->getCanvas()->drawPicture(pic);
SkAutoTUnref<SkImage> image(surface->newImageSnapshot());
fTexture.reset(SkRef(image->getTexture()));
}
protected:
GrTexture* onGenerateTexture(GrContext* ctx, SkImageUsageType, const SkIRect* subset) override {
if (ctx) {
SkASSERT(ctx == fCtx.get());
}
if (!subset) {
return SkRef(fTexture.get());
}
// need to copy the subset into a new texture
GrSurfaceDesc desc = fTexture->desc();
desc.fWidth = subset->width();
desc.fHeight = subset->height();
GrTexture* dst = fCtx->textureProvider()->createTexture(desc, false);
fCtx->copySurface(dst, fTexture, *subset, SkIPoint::Make(0, 0));
return dst;
}
private:
SkAutoTUnref<GrContext> fCtx;
SkAutoTUnref<GrTexture> fTexture;
};
static SkImageGenerator* make_tex_generator(GrContext* ctx, SkPicture* pic) {
const SkImageInfo info = SkImageInfo::MakeN32Premul(100, 100);
if (!ctx) {
return new EmptyGenerator(info);
}
return new TextureGenerator(ctx, info, pic);
}
#endif
class ImageCacheratorGM : public skiagm::GM {
SkString fName;
SkImageGenerator* (*fFactory)(GrContext*, SkPicture*);
SkAutoTUnref<SkPicture> fPicture;
SkAutoTDelete<SkImageCacherator> fCache;
SkAutoTDelete<SkImageCacherator> fCacheSubset;
public:
ImageCacheratorGM(const char suffix[], SkImageGenerator* (*factory)(GrContext*, SkPicture*))
: fFactory(factory)
{
fName.printf("image-cacherator-from-%s", suffix);
}
protected:
SkString onShortName() override {
return fName;
}
SkISize onISize() override {
return SkISize::Make(850, 450);
}
void onOnceBeforeDraw() override {
const SkRect bounds = SkRect::MakeXYWH(100, 100, 100, 100);
SkPictureRecorder recorder;
draw_something(recorder.beginRecording(bounds), bounds);
fPicture.reset(recorder.endRecording());
}
void makeCaches(GrContext* ctx) {
auto gen = fFactory(ctx, fPicture);
SkDEBUGCODE(const uint32_t genID = gen->uniqueID();)
fCache.reset(SkImageCacherator::NewFromGenerator(gen));
const SkIRect subset = SkIRect::MakeLTRB(50, 50, 100, 100);
gen = fFactory(ctx, fPicture);
SkDEBUGCODE(const uint32_t genSubsetID = gen->uniqueID();)
fCacheSubset.reset(SkImageCacherator::NewFromGenerator(gen, &subset));
// whole caches should have the same ID as the generator. Subsets should be diff
SkASSERT(fCache->uniqueID() == genID);
SkASSERT(fCacheSubset->uniqueID() != genID);
SkASSERT(fCacheSubset->uniqueID() != genSubsetID);
SkASSERT(fCache->info().dimensions() == SkISize::Make(100, 100));
SkASSERT(fCacheSubset->info().dimensions() == SkISize::Make(50, 50));
}
static void draw_as_bitmap(SkCanvas* canvas, SkImageCacherator* cache, SkScalar x, SkScalar y) {
SkBitmap bitmap;
cache->lockAsBitmap(&bitmap);
canvas->drawBitmap(bitmap, x, y);
}
static void draw_as_tex(SkCanvas* canvas, SkImageCacherator* cache, SkScalar x, SkScalar y) {
#if SK_SUPPORT_GPU
SkAutoTUnref<GrTexture> texture(cache->lockAsTexture(canvas->getGrContext(),
kUntiled_SkImageUsageType));
if (!texture) {
return;
}
// No API to draw a GrTexture directly, so we cheat and create a private image subclass
SkAutoTUnref<SkImage> image(new SkImage_Gpu(cache->info().width(), cache->info().height(),
cache->uniqueID(), kPremul_SkAlphaType, texture,
0, SkSurface::kNo_Budgeted));
canvas->drawImage(image, x, y);
#endif
}
void drawSet(SkCanvas* canvas) const {
SkMatrix matrix = SkMatrix::MakeTrans(-100, -100);
canvas->drawPicture(fPicture, &matrix, nullptr);
// Draw the tex first, so it doesn't hit a lucky cache from the raster version. This
// way we also can force the generateTexture call.
draw_as_tex(canvas, fCache, 310, 0);
draw_as_tex(canvas, fCacheSubset, 310+101, 0);
draw_as_bitmap(canvas, fCache, 150, 0);
draw_as_bitmap(canvas, fCacheSubset, 150+101, 0);
}
void onDraw(SkCanvas* canvas) override {
this->makeCaches(canvas->getGrContext());
canvas->translate(20, 20);
this->drawSet(canvas);
canvas->save();
canvas->translate(0, 130);
canvas->scale(0.25f, 0.25f);
this->drawSet(canvas);
canvas->restore();
canvas->save();
canvas->translate(0, 200);
canvas->scale(2, 2);
this->drawSet(canvas);
canvas->restore();
}
private:
typedef skiagm::GM INHERITED;
};
DEF_GM( return new ImageCacheratorGM("picture", make_pic_generator); )
DEF_GM( return new ImageCacheratorGM("raster", make_ras_generator); )
#if SK_SUPPORT_GPU
DEF_GM( return new ImageCacheratorGM("texture", make_tex_generator); )
#endif
<commit_msg>widen gm to show entire image, add place-holder for no context<commit_after>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkImage.h"
#include "SkImageCacherator.h"
#include "SkPictureRecorder.h"
#include "SkSurface.h"
#if SK_SUPPORT_GPU
#include "GrContext.h"
#include "GrTexture.h"
#include "../src/image/SkImage_Gpu.h"
#endif
static void draw_something(SkCanvas* canvas, const SkRect& bounds) {
SkPaint paint;
paint.setAntiAlias(true);
paint.setColor(SK_ColorRED);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(10);
canvas->drawRect(bounds, paint);
paint.setStyle(SkPaint::kFill_Style);
paint.setColor(SK_ColorBLUE);
canvas->drawOval(bounds, paint);
}
/*
* Exercise drawing pictures inside an image, showing that the image version is pixelated
* (correctly) when it is inside an image.
*/
class ImagePictGM : public skiagm::GM {
SkAutoTUnref<SkPicture> fPicture;
SkAutoTUnref<SkImage> fImage0;
SkAutoTUnref<SkImage> fImage1;
public:
ImagePictGM() {}
protected:
SkString onShortName() override {
return SkString("image-picture");
}
SkISize onISize() override {
return SkISize::Make(850, 450);
}
void onOnceBeforeDraw() override {
const SkRect bounds = SkRect::MakeXYWH(100, 100, 100, 100);
SkPictureRecorder recorder;
draw_something(recorder.beginRecording(bounds), bounds);
fPicture.reset(recorder.endRecording());
// extract enough just for the oval.
const SkISize size = SkISize::Make(100, 100);
SkMatrix matrix;
matrix.setTranslate(-100, -100);
fImage0.reset(SkImage::NewFromPicture(fPicture, size, &matrix, nullptr));
matrix.postTranslate(-50, -50);
matrix.postRotate(45);
matrix.postTranslate(50, 50);
fImage1.reset(SkImage::NewFromPicture(fPicture, size, &matrix, nullptr));
}
void drawSet(SkCanvas* canvas) const {
SkMatrix matrix = SkMatrix::MakeTrans(-100, -100);
canvas->drawPicture(fPicture, &matrix, nullptr);
canvas->drawImage(fImage0, 150, 0);
canvas->drawImage(fImage1, 300, 0);
}
void onDraw(SkCanvas* canvas) override {
canvas->translate(20, 20);
this->drawSet(canvas);
canvas->save();
canvas->translate(0, 130);
canvas->scale(0.25f, 0.25f);
this->drawSet(canvas);
canvas->restore();
canvas->save();
canvas->translate(0, 200);
canvas->scale(2, 2);
this->drawSet(canvas);
canvas->restore();
}
private:
typedef skiagm::GM INHERITED;
};
DEF_GM( return new ImagePictGM; )
///////////////////////////////////////////////////////////////////////////////////////////////////
static SkImageGenerator* make_pic_generator(GrContext*, SkPicture* pic) {
SkMatrix matrix;
matrix.setTranslate(-100, -100);
return SkImageGenerator::NewFromPicture(SkISize::Make(100, 100), pic, &matrix, nullptr);
}
class RasterGenerator : public SkImageGenerator {
public:
RasterGenerator(const SkBitmap& bm) : SkImageGenerator(bm.info()), fBM(bm) {}
protected:
bool onGetPixels(const SkImageInfo& info, void* pixels, size_t rowBytes,
SkPMColor*, int*) override {
return fBM.readPixels(info, pixels, rowBytes, 0, 0);
}
private:
SkBitmap fBM;
};
static SkImageGenerator* make_ras_generator(GrContext*, SkPicture* pic) {
SkBitmap bm;
bm.allocN32Pixels(100, 100);
SkCanvas canvas(bm);
canvas.clear(0);
canvas.translate(-100, -100);
canvas.drawPicture(pic);
return new RasterGenerator(bm);
}
class EmptyGenerator : public SkImageGenerator {
public:
EmptyGenerator(const SkImageInfo& info) : SkImageGenerator(info) {}
};
#if SK_SUPPORT_GPU
class TextureGenerator : public SkImageGenerator {
public:
TextureGenerator(GrContext* ctx, const SkImageInfo& info, SkPicture* pic)
: SkImageGenerator(info)
, fCtx(SkRef(ctx))
{
SkAutoTUnref<SkSurface> surface(SkSurface::NewRenderTarget(ctx, SkSurface::kNo_Budgeted,
info, 0));
surface->getCanvas()->clear(0);
surface->getCanvas()->translate(-100, -100);
surface->getCanvas()->drawPicture(pic);
SkAutoTUnref<SkImage> image(surface->newImageSnapshot());
fTexture.reset(SkRef(image->getTexture()));
}
protected:
GrTexture* onGenerateTexture(GrContext* ctx, SkImageUsageType, const SkIRect* subset) override {
if (ctx) {
SkASSERT(ctx == fCtx.get());
}
if (!subset) {
return SkRef(fTexture.get());
}
// need to copy the subset into a new texture
GrSurfaceDesc desc = fTexture->desc();
desc.fWidth = subset->width();
desc.fHeight = subset->height();
GrTexture* dst = fCtx->textureProvider()->createTexture(desc, false);
fCtx->copySurface(dst, fTexture, *subset, SkIPoint::Make(0, 0));
return dst;
}
private:
SkAutoTUnref<GrContext> fCtx;
SkAutoTUnref<GrTexture> fTexture;
};
static SkImageGenerator* make_tex_generator(GrContext* ctx, SkPicture* pic) {
const SkImageInfo info = SkImageInfo::MakeN32Premul(100, 100);
if (!ctx) {
return new EmptyGenerator(info);
}
return new TextureGenerator(ctx, info, pic);
}
#endif
class ImageCacheratorGM : public skiagm::GM {
SkString fName;
SkImageGenerator* (*fFactory)(GrContext*, SkPicture*);
SkAutoTUnref<SkPicture> fPicture;
SkAutoTDelete<SkImageCacherator> fCache;
SkAutoTDelete<SkImageCacherator> fCacheSubset;
public:
ImageCacheratorGM(const char suffix[], SkImageGenerator* (*factory)(GrContext*, SkPicture*))
: fFactory(factory)
{
fName.printf("image-cacherator-from-%s", suffix);
}
protected:
SkString onShortName() override {
return fName;
}
SkISize onISize() override {
return SkISize::Make(960, 450);
}
void onOnceBeforeDraw() override {
const SkRect bounds = SkRect::MakeXYWH(100, 100, 100, 100);
SkPictureRecorder recorder;
draw_something(recorder.beginRecording(bounds), bounds);
fPicture.reset(recorder.endRecording());
}
void makeCaches(GrContext* ctx) {
auto gen = fFactory(ctx, fPicture);
SkDEBUGCODE(const uint32_t genID = gen->uniqueID();)
fCache.reset(SkImageCacherator::NewFromGenerator(gen));
const SkIRect subset = SkIRect::MakeLTRB(50, 50, 100, 100);
gen = fFactory(ctx, fPicture);
SkDEBUGCODE(const uint32_t genSubsetID = gen->uniqueID();)
fCacheSubset.reset(SkImageCacherator::NewFromGenerator(gen, &subset));
// whole caches should have the same ID as the generator. Subsets should be diff
SkASSERT(fCache->uniqueID() == genID);
SkASSERT(fCacheSubset->uniqueID() != genID);
SkASSERT(fCacheSubset->uniqueID() != genSubsetID);
SkASSERT(fCache->info().dimensions() == SkISize::Make(100, 100));
SkASSERT(fCacheSubset->info().dimensions() == SkISize::Make(50, 50));
}
static void draw_as_bitmap(SkCanvas* canvas, SkImageCacherator* cache, SkScalar x, SkScalar y) {
SkBitmap bitmap;
cache->lockAsBitmap(&bitmap);
canvas->drawBitmap(bitmap, x, y);
}
static void draw_as_tex(SkCanvas* canvas, SkImageCacherator* cache, SkScalar x, SkScalar y) {
#if SK_SUPPORT_GPU
SkAutoTUnref<GrTexture> texture(cache->lockAsTexture(canvas->getGrContext(),
kUntiled_SkImageUsageType));
if (!texture) {
// show placeholder if we have no texture
SkPaint paint;
paint.setStyle(SkPaint::kStroke_Style);
SkRect r = SkRect::MakeXYWH(x, y, SkIntToScalar(cache->info().width()),
SkIntToScalar(cache->info().width()));
canvas->drawRect(r, paint);
canvas->drawLine(r.left(), r.top(), r.right(), r.bottom(), paint);
canvas->drawLine(r.left(), r.bottom(), r.right(), r.top(), paint);
return;
}
// No API to draw a GrTexture directly, so we cheat and create a private image subclass
SkAutoTUnref<SkImage> image(new SkImage_Gpu(cache->info().width(), cache->info().height(),
cache->uniqueID(), kPremul_SkAlphaType, texture,
0, SkSurface::kNo_Budgeted));
canvas->drawImage(image, x, y);
#endif
}
void drawSet(SkCanvas* canvas) const {
SkMatrix matrix = SkMatrix::MakeTrans(-100, -100);
canvas->drawPicture(fPicture, &matrix, nullptr);
// Draw the tex first, so it doesn't hit a lucky cache from the raster version. This
// way we also can force the generateTexture call.
draw_as_tex(canvas, fCache, 310, 0);
draw_as_tex(canvas, fCacheSubset, 310+101, 0);
draw_as_bitmap(canvas, fCache, 150, 0);
draw_as_bitmap(canvas, fCacheSubset, 150+101, 0);
}
void onDraw(SkCanvas* canvas) override {
this->makeCaches(canvas->getGrContext());
canvas->translate(20, 20);
this->drawSet(canvas);
canvas->save();
canvas->translate(0, 130);
canvas->scale(0.25f, 0.25f);
this->drawSet(canvas);
canvas->restore();
canvas->save();
canvas->translate(0, 200);
canvas->scale(2, 2);
this->drawSet(canvas);
canvas->restore();
}
private:
typedef skiagm::GM INHERITED;
};
DEF_GM( return new ImageCacheratorGM("picture", make_pic_generator); )
DEF_GM( return new ImageCacheratorGM("raster", make_ras_generator); )
#if SK_SUPPORT_GPU
DEF_GM( return new ImageCacheratorGM("texture", make_tex_generator); )
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkPath.h"
#include "SkTypeface.h"
#include "SkRandom.h"
/**
* Draws text with random parameters. The text draws each get their own clip rect. It is also
* used as a bench to measure how well the GPU backend batches text draws.
*/
class VariedTextGM : public skiagm::GM {
public:
VariedTextGM(bool effectiveClip, bool lcd)
: fEffectiveClip(effectiveClip)
, fLCD(lcd) {
memset(fTypefacesToUnref, 0, sizeof(fTypefacesToUnref));
}
~VariedTextGM() {
for (size_t i = 0; i < SK_ARRAY_COUNT(fTypefacesToUnref); ++i) {
SkSafeUnref(fTypefacesToUnref[i]);
}
}
protected:
SkString onShortName() override {
SkString name("varied_text");
if (fEffectiveClip) {
name.append("_clipped");
} else {
name.append("_ignorable_clip");
}
if (fLCD) {
name.append("_lcd");
} else {
name.append("_no_lcd");
}
return name;
}
SkISize onISize() override {
return SkISize::Make(640, 480);
}
void onOnceBeforeDraw() override {
fPaint.setAntiAlias(true);
fPaint.setLCDRenderText(fLCD);
SkISize size = this->getISize();
SkScalar w = SkIntToScalar(size.fWidth);
SkScalar h = SkIntToScalar(size.fHeight);
SK_COMPILE_ASSERT(4 == SK_ARRAY_COUNT(fTypefacesToUnref), typeface_cnt);
fTypefacesToUnref[0] = sk_tool_utils::create_portable_typeface("sans-serif", SkTypeface::kNormal);
fTypefacesToUnref[1] = sk_tool_utils::create_portable_typeface("sans-serif", SkTypeface::kBold);
fTypefacesToUnref[2] = sk_tool_utils::create_portable_typeface("serif", SkTypeface::kNormal);
fTypefacesToUnref[3] = sk_tool_utils::create_portable_typeface("serif", SkTypeface::kBold);
SkRandom random;
for (int i = 0; i < kCnt; ++i) {
int length = random.nextRangeU(kMinLength, kMaxLength);
char text[kMaxLength];
for (int j = 0; j < length; ++j) {
text[j] = (char)random.nextRangeU('!', 'z');
}
fStrings[i].set(text, length);
fColors[i] = random.nextU();
fColors[i] |= 0xFF000000;
static const SkScalar kMinPtSize = 8.f;
static const SkScalar kMaxPtSize = 32.f;
fPtSizes[i] = random.nextRangeScalar(kMinPtSize, kMaxPtSize);
fTypefaces[i] = fTypefacesToUnref[
random.nextULessThan(SK_ARRAY_COUNT(fTypefacesToUnref))];
SkRect r;
fPaint.setColor(fColors[i]);
fPaint.setTypeface(fTypefaces[i]);
fPaint.setTextSize(fPtSizes[i]);
fPaint.measureText(fStrings[i].c_str(), fStrings[i].size(), &r);
// safeRect is set of x,y positions where we can draw the string without hitting
// the GM's border.
SkRect safeRect = SkRect::MakeLTRB(-r.fLeft, -r.fTop, w - r.fRight, h - r.fBottom);
if (safeRect.isEmpty()) {
// If we don't fit then just don't worry about how we get cliped to the device
// border.
safeRect = SkRect::MakeWH(w, h);
}
fPositions[i].fX = random.nextRangeScalar(safeRect.fLeft, safeRect.fRight);
fPositions[i].fY = random.nextRangeScalar(safeRect.fTop, safeRect.fBottom);
fClipRects[i] = r;
fClipRects[i].offset(fPositions[i].fX, fPositions[i].fY);
fClipRects[i].outset(2.f, 2.f);
if (fEffectiveClip) {
fClipRects[i].fRight -= 0.25f * fClipRects[i].width();
}
}
}
void onDraw(SkCanvas* canvas) override {
for (int i = 0; i < kCnt; ++i) {
fPaint.setColor(fColors[i]);
fPaint.setTextSize(fPtSizes[i]);
fPaint.setTypeface(fTypefaces[i]);
canvas->save();
canvas->clipRect(fClipRects[i]);
canvas->translate(fPositions[i].fX, fPositions[i].fY);
canvas->drawText(fStrings[i].c_str(), fStrings[i].size(), 0, 0, fPaint);
canvas->restore();
}
// Visualize the clips, but not in bench mode.
if (kBench_Mode != this->getMode()) {
SkPaint wirePaint;
wirePaint.setAntiAlias(true);
wirePaint.setStrokeWidth(0);
wirePaint.setStyle(SkPaint::kStroke_Style);
for (int i = 0; i < kCnt; ++i) {
canvas->drawRect(fClipRects[i], wirePaint);
}
}
}
bool runAsBench() const override { return true; }
private:
static const int kCnt = 30;
static const int kMinLength = 15;
static const int kMaxLength = 40;
bool fEffectiveClip;
bool fLCD;
SkTypeface* fTypefacesToUnref[4];
SkPaint fPaint;
// precomputed for each text draw
SkString fStrings[kCnt];
SkColor fColors[kCnt];
SkScalar fPtSizes[kCnt];
SkTypeface* fTypefaces[kCnt];
SkPoint fPositions[kCnt];
SkRect fClipRects[kCnt];
typedef skiagm::GM INHERITED;
};
DEF_GM( return SkNEW(VariedTextGM(false, false)); )
DEF_GM( return SkNEW(VariedTextGM(true, false)); )
DEF_GM( return SkNEW(VariedTextGM(false, true)); )
DEF_GM( return SkNEW(VariedTextGM(true, true)); )
<commit_msg>make varied_text* gm portable<commit_after>/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkPath.h"
#include "SkTypeface.h"
#include "SkRandom.h"
/**
* Draws text with random parameters. The text draws each get their own clip rect. It is also
* used as a bench to measure how well the GPU backend batches text draws.
*/
class VariedTextGM : public skiagm::GM {
public:
VariedTextGM(bool effectiveClip, bool lcd)
: fEffectiveClip(effectiveClip)
, fLCD(lcd) {
memset(fTypefacesToUnref, 0, sizeof(fTypefacesToUnref));
}
~VariedTextGM() {
for (size_t i = 0; i < SK_ARRAY_COUNT(fTypefacesToUnref); ++i) {
SkSafeUnref(fTypefacesToUnref[i]);
}
}
protected:
SkString onShortName() override {
SkString name("varied_text");
if (fEffectiveClip) {
name.append("_clipped");
} else {
name.append("_ignorable_clip");
}
if (fLCD) {
name.append("_lcd");
} else {
name.append("_no_lcd");
}
return name;
}
SkISize onISize() override {
return SkISize::Make(640, 480);
}
void onOnceBeforeDraw() override {
fPaint.setAntiAlias(true);
fPaint.setLCDRenderText(fLCD);
SkISize size = this->getISize();
SkScalar w = SkIntToScalar(size.fWidth);
SkScalar h = SkIntToScalar(size.fHeight);
SK_COMPILE_ASSERT(4 == SK_ARRAY_COUNT(fTypefacesToUnref), typeface_cnt);
fTypefacesToUnref[0] = sk_tool_utils::create_portable_typeface_always("sans-serif", SkTypeface::kNormal);
fTypefacesToUnref[1] = sk_tool_utils::create_portable_typeface_always("sans-serif", SkTypeface::kBold);
fTypefacesToUnref[2] = sk_tool_utils::create_portable_typeface_always("serif", SkTypeface::kNormal);
fTypefacesToUnref[3] = sk_tool_utils::create_portable_typeface_always("serif", SkTypeface::kBold);
SkRandom random;
for (int i = 0; i < kCnt; ++i) {
int length = random.nextRangeU(kMinLength, kMaxLength);
char text[kMaxLength];
for (int j = 0; j < length; ++j) {
text[j] = (char)random.nextRangeU('!', 'z');
}
fStrings[i].set(text, length);
fColors[i] = random.nextU();
fColors[i] |= 0xFF000000;
fColors[i] = sk_tool_utils::color_to_565(fColors[i]);
static const SkScalar kMinPtSize = 8.f;
static const SkScalar kMaxPtSize = 32.f;
fPtSizes[i] = random.nextRangeScalar(kMinPtSize, kMaxPtSize);
fTypefaces[i] = fTypefacesToUnref[
random.nextULessThan(SK_ARRAY_COUNT(fTypefacesToUnref))];
SkRect r;
fPaint.setColor(fColors[i]);
fPaint.setTypeface(fTypefaces[i]);
fPaint.setTextSize(fPtSizes[i]);
fPaint.measureText(fStrings[i].c_str(), fStrings[i].size(), &r);
// safeRect is set of x,y positions where we can draw the string without hitting
// the GM's border.
SkRect safeRect = SkRect::MakeLTRB(-r.fLeft, -r.fTop, w - r.fRight, h - r.fBottom);
if (safeRect.isEmpty()) {
// If we don't fit then just don't worry about how we get cliped to the device
// border.
safeRect = SkRect::MakeWH(w, h);
}
fPositions[i].fX = random.nextRangeScalar(safeRect.fLeft, safeRect.fRight);
fPositions[i].fY = random.nextRangeScalar(safeRect.fTop, safeRect.fBottom);
fClipRects[i] = r;
fClipRects[i].offset(fPositions[i].fX, fPositions[i].fY);
fClipRects[i].outset(2.f, 2.f);
if (fEffectiveClip) {
fClipRects[i].fRight -= 0.25f * fClipRects[i].width();
}
}
}
void onDraw(SkCanvas* canvas) override {
for (int i = 0; i < kCnt; ++i) {
fPaint.setColor(fColors[i]);
fPaint.setTextSize(fPtSizes[i]);
fPaint.setTypeface(fTypefaces[i]);
canvas->save();
canvas->clipRect(fClipRects[i]);
canvas->translate(fPositions[i].fX, fPositions[i].fY);
canvas->drawText(fStrings[i].c_str(), fStrings[i].size(), 0, 0, fPaint);
canvas->restore();
}
// Visualize the clips, but not in bench mode.
if (kBench_Mode != this->getMode()) {
SkPaint wirePaint;
wirePaint.setAntiAlias(true);
wirePaint.setStrokeWidth(0);
wirePaint.setStyle(SkPaint::kStroke_Style);
for (int i = 0; i < kCnt; ++i) {
canvas->drawRect(fClipRects[i], wirePaint);
}
}
}
bool runAsBench() const override { return true; }
private:
static const int kCnt = 30;
static const int kMinLength = 15;
static const int kMaxLength = 40;
bool fEffectiveClip;
bool fLCD;
SkTypeface* fTypefacesToUnref[4];
SkPaint fPaint;
// precomputed for each text draw
SkString fStrings[kCnt];
SkColor fColors[kCnt];
SkScalar fPtSizes[kCnt];
SkTypeface* fTypefaces[kCnt];
SkPoint fPositions[kCnt];
SkRect fClipRects[kCnt];
typedef skiagm::GM INHERITED;
};
DEF_GM( return SkNEW(VariedTextGM(false, false)); )
DEF_GM( return SkNEW(VariedTextGM(true, false)); )
DEF_GM( return SkNEW(VariedTextGM(false, true)); )
DEF_GM( return SkNEW(VariedTextGM(true, true)); )
<|endoftext|>
|
<commit_before>/*
* A simple resizable circular buffer.
*/
#include "rust_internal.h"
bool
is_power_of_two(size_t value) {
if (value > 0) {
return (value & (value - 1)) == 0;
}
return false;
}
circular_buffer::circular_buffer(rust_dom *dom, size_t unit_sz) :
dom(dom),
unit_sz(unit_sz),
_buffer_sz(INITIAL_CIRCULAR_BUFFFER_SIZE_IN_UNITS * unit_sz),
_next(0),
_unread(0),
_buffer((uint8_t *)dom->calloc(_buffer_sz)) {
A(dom, unit_sz, "Unit size must be larger than zero.");
dom->log(rust_log::MEM | rust_log::COMM,
"new circular_buffer(buffer_sz=%d, unread=%d)"
"-> circular_buffer=0x%" PRIxPTR,
_buffer_sz, _unread, this);
A(dom, _buffer, "Failed to allocate buffer.");
}
circular_buffer::~circular_buffer() {
dom->log(rust_log::MEM | rust_log::COMM,
"~circular_buffer 0x%" PRIxPTR,
this);
I(dom, _buffer);
// I(dom, _unread == 0);
dom->free(_buffer);
}
/**
* Copies the unread data from this buffer to the "dst" address.
*/
void
circular_buffer::transfer(void *dst) {
I(dom, dst);
I(dom, is_power_of_two(_buffer_sz));
uint8_t *ptr = (uint8_t *) dst;
for (size_t i = 0; i < _unread; i += unit_sz) {
memcpy(&ptr[i], &_buffer[(_next + i) & (_buffer_sz - 1)], unit_sz);
}
}
/**
* Copies the data at the "src" address into this buffer. The buffer is
* grown if it isn't large enough.
*/
void
circular_buffer::enqueue(void *src) {
I(dom, src);
I(dom, _unread <= _buffer_sz);
// Grow if necessary.
if (_unread == _buffer_sz) {
I(dom, _buffer_sz <= MAX_CIRCULAR_BUFFFER_SIZE);
void *tmp = dom->malloc(_buffer_sz << 1);
transfer(tmp);
_buffer_sz <<= 1;
dom->free(_buffer);
_buffer = (uint8_t *)tmp;
}
dom->log(rust_log::MEM | rust_log::COMM,
"circular_buffer enqueue "
"unread: %d, buffer_sz: %d, unit_sz: %d",
_unread, _buffer_sz, unit_sz);
I(dom, is_power_of_two(_buffer_sz));
I(dom, _unread < _buffer_sz);
I(dom, _unread + unit_sz <= _buffer_sz);
// Copy data
size_t i = (_next + _unread) & (_buffer_sz - 1);
memcpy(&_buffer[i], src, unit_sz);
_unread += unit_sz;
dom->log(rust_log::MEM | rust_log::COMM,
"circular_buffer pushed data at index: %d", i);
}
/**
* Copies data from this buffer to the "dst" address. The buffer is
* shrunk if possible. If the "dst" address is NULL, then the message
* is dequeued but is not copied.
*/
void
circular_buffer::dequeue(void *dst) {
I(dom, unit_sz > 0);
I(dom, _unread >= unit_sz);
I(dom, _unread <= _buffer_sz);
I(dom, _buffer);
dom->log(rust_log::MEM | rust_log::COMM,
"circular_buffer dequeue "
"unread: %d, buffer_sz: %d, unit_sz: %d",
_unread, _buffer_sz, unit_sz);
if (dst != NULL) {
memcpy(dst, &_buffer[_next], unit_sz);
}
dom->log(rust_log::MEM | rust_log::COMM,
"shifted data from index %d", _next);
_unread -= unit_sz;
_next += unit_sz;
I(dom, _next <= _buffer_sz);
if (_next == _buffer_sz) {
_next = 0;
}
// Shrink if possible.
if (_buffer_sz >= INITIAL_CIRCULAR_BUFFFER_SIZE_IN_UNITS * unit_sz &&
_unread <= _buffer_sz / 4) {
dom->log(rust_log::MEM | rust_log::COMM,
"circular_buffer is shrinking to %d bytes", _buffer_sz / 2);
void *tmp = dom->malloc(_buffer_sz / 2);
transfer(tmp);
_buffer_sz >>= 1;
dom->free(_buffer);
_buffer = (uint8_t *)tmp;
_next = 0;
}
}
uint8_t *
circular_buffer::peek() {
return &_buffer[_next];
}
bool
circular_buffer::is_empty() {
return _unread == 0;
}
<commit_msg>Change unread-on-destroy condition for circular buffer to merely a warning.<commit_after>/*
* A simple resizable circular buffer.
*/
#include "rust_internal.h"
bool
is_power_of_two(size_t value) {
if (value > 0) {
return (value & (value - 1)) == 0;
}
return false;
}
circular_buffer::circular_buffer(rust_dom *dom, size_t unit_sz) :
dom(dom),
unit_sz(unit_sz),
_buffer_sz(INITIAL_CIRCULAR_BUFFFER_SIZE_IN_UNITS * unit_sz),
_next(0),
_unread(0),
_buffer((uint8_t *)dom->calloc(_buffer_sz)) {
A(dom, unit_sz, "Unit size must be larger than zero.");
dom->log(rust_log::MEM | rust_log::COMM,
"new circular_buffer(buffer_sz=%d, unread=%d)"
"-> circular_buffer=0x%" PRIxPTR,
_buffer_sz, _unread, this);
A(dom, _buffer, "Failed to allocate buffer.");
}
circular_buffer::~circular_buffer() {
dom->log(rust_log::MEM | rust_log::COMM,
"~circular_buffer 0x%" PRIxPTR,
this);
I(dom, _buffer);
W(dom, _unread == 0, "~circular_buffer with unread messages.");
dom->free(_buffer);
}
/**
* Copies the unread data from this buffer to the "dst" address.
*/
void
circular_buffer::transfer(void *dst) {
I(dom, dst);
I(dom, is_power_of_two(_buffer_sz));
uint8_t *ptr = (uint8_t *) dst;
for (size_t i = 0; i < _unread; i += unit_sz) {
memcpy(&ptr[i], &_buffer[(_next + i) & (_buffer_sz - 1)], unit_sz);
}
}
/**
* Copies the data at the "src" address into this buffer. The buffer is
* grown if it isn't large enough.
*/
void
circular_buffer::enqueue(void *src) {
I(dom, src);
I(dom, _unread <= _buffer_sz);
// Grow if necessary.
if (_unread == _buffer_sz) {
I(dom, _buffer_sz <= MAX_CIRCULAR_BUFFFER_SIZE);
void *tmp = dom->malloc(_buffer_sz << 1);
transfer(tmp);
_buffer_sz <<= 1;
dom->free(_buffer);
_buffer = (uint8_t *)tmp;
}
dom->log(rust_log::MEM | rust_log::COMM,
"circular_buffer enqueue "
"unread: %d, buffer_sz: %d, unit_sz: %d",
_unread, _buffer_sz, unit_sz);
I(dom, is_power_of_two(_buffer_sz));
I(dom, _unread < _buffer_sz);
I(dom, _unread + unit_sz <= _buffer_sz);
// Copy data
size_t i = (_next + _unread) & (_buffer_sz - 1);
memcpy(&_buffer[i], src, unit_sz);
_unread += unit_sz;
dom->log(rust_log::MEM | rust_log::COMM,
"circular_buffer pushed data at index: %d", i);
}
/**
* Copies data from this buffer to the "dst" address. The buffer is
* shrunk if possible. If the "dst" address is NULL, then the message
* is dequeued but is not copied.
*/
void
circular_buffer::dequeue(void *dst) {
I(dom, unit_sz > 0);
I(dom, _unread >= unit_sz);
I(dom, _unread <= _buffer_sz);
I(dom, _buffer);
dom->log(rust_log::MEM | rust_log::COMM,
"circular_buffer dequeue "
"unread: %d, buffer_sz: %d, unit_sz: %d",
_unread, _buffer_sz, unit_sz);
if (dst != NULL) {
memcpy(dst, &_buffer[_next], unit_sz);
}
dom->log(rust_log::MEM | rust_log::COMM,
"shifted data from index %d", _next);
_unread -= unit_sz;
_next += unit_sz;
I(dom, _next <= _buffer_sz);
if (_next == _buffer_sz) {
_next = 0;
}
// Shrink if possible.
if (_buffer_sz >= INITIAL_CIRCULAR_BUFFFER_SIZE_IN_UNITS * unit_sz &&
_unread <= _buffer_sz / 4) {
dom->log(rust_log::MEM | rust_log::COMM,
"circular_buffer is shrinking to %d bytes", _buffer_sz / 2);
void *tmp = dom->malloc(_buffer_sz / 2);
transfer(tmp);
_buffer_sz >>= 1;
dom->free(_buffer);
_buffer = (uint8_t *)tmp;
_next = 0;
}
}
uint8_t *
circular_buffer::peek() {
return &_buffer[_next];
}
bool
circular_buffer::is_empty() {
return _unread == 0;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Script Generator project on Qt Labs.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "shellheadergenerator.h"
#include "fileout.h"
#include <QtCore/QDir>
#include <qdebug.h>
QString ShellHeaderGenerator::fileNameForClass(const AbstractMetaClass *meta_class) const
{
return QString("PythonQtWrapper_%1.h").arg(meta_class->name());
}
void ShellHeaderGenerator::writeFieldAccessors(QTextStream &s, const AbstractMetaField *field)
{
const AbstractMetaFunction *setter = field->setter();
const AbstractMetaFunction *getter = field->getter();
// static fields are not supported (yet?)
if (setter->isStatic()) return;
// Uuid data4 did not work (TODO: move to typesystem...(
if (field->enclosingClass()->name()=="QUuid" && setter->name()=="data4") return;
if (field->enclosingClass()->name()=="QIPv6Address") return;
if (!field->type()->isConstant()) {
writeFunctionSignature(s, setter, 0, QString(),
Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | ShowStatic | UnderscoreSpaces));
s << "{ theWrappedObject->" << field->name() << " = " << setter->arguments()[0]->argumentName() << "; }\n";
}
writeFunctionSignature(s, getter, 0, QString(),
Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));
s << "{ return theWrappedObject->" << field->name() << "; }\n";
}
void ShellHeaderGenerator::write(QTextStream &s, const AbstractMetaClass *meta_class)
{
QString builtIn = ShellGenerator::isBuiltIn(meta_class->name())?"_builtin":"";
QString pro_file_name = meta_class->package().replace(".", "_") + builtIn + "/" + meta_class->package().replace(".", "_") + builtIn + ".pri";
priGenerator->addHeader(pro_file_name, fileNameForClass(meta_class));
setupGenerator->addClass(meta_class->package().replace(".", "_") + builtIn, meta_class);
QString include_block = "PYTHONQTWRAPPER_" + meta_class->name().toUpper() + "_H";
s << "#ifndef " << include_block << endl
<< "#define " << include_block << endl << endl;
Include inc = meta_class->typeEntry()->include();
ShellGenerator::writeInclude(s, inc);
s << "#include <QObject>" << endl << endl;
s << "#include <PythonQt.h>" << endl << endl;
IncludeList list = meta_class->typeEntry()->extraIncludes();
qSort(list.begin(), list.end());
foreach (const Include &inc, list) {
ShellGenerator::writeInclude(s, inc);
}
s << endl;
AbstractMetaFunctionList ctors = meta_class->queryFunctions(AbstractMetaClass::Constructors
| AbstractMetaClass::WasVisible
| AbstractMetaClass::NotRemovedFromTargetLang);
if (meta_class->qualifiedCppName().contains("Ssl")) {
s << "#ifndef QT_NO_OPENSSL" << endl;
}
// Shell-------------------------------------------------------------------
if (meta_class->generateShellClass()) {
AbstractMetaFunctionList virtualsForShell = getVirtualFunctionsForShell(meta_class);
s << "class " << shellClassName(meta_class)
<< " : public " << meta_class->qualifiedCppName() << endl << "{" << endl;
s << "public:" << endl;
foreach(AbstractMetaFunction* fun, ctors) {
s << " ";
writeFunctionSignature(s, fun, 0,"PythonQtShell_",
Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));
s << ":" << meta_class->qualifiedCppName() << "(";
QString scriptFunctionName = fun->originalName();
AbstractMetaArgumentList args = fun->arguments();
for (int i = 0; i < args.size(); ++i) {
if (i > 0)
s << ", ";
s << args.at(i)->argumentName();
}
s << "),_wrapper(NULL) {};" << endl;
}
s << endl;
s << " ~" << shellClassName(meta_class) << "();" << endl;
foreach(AbstractMetaFunction* fun, virtualsForShell) {
s << "virtual ";
writeFunctionSignature(s, fun, 0, QString(),
Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));
s << ";" << endl;
}
s << endl;
s << " PythonQtInstanceWrapper* _wrapper; " << endl;
s << "};" << endl << endl;
}
// Promoter-------------------------------------------------------------------
AbstractMetaFunctionList promoteFunctions = getProtectedFunctionsThatNeedPromotion(meta_class);
if (!promoteFunctions.isEmpty()) {
s << "class " << promoterClassName(meta_class)
<< " : public " << meta_class->qualifiedCppName() << endl << "{ public:" << endl;
foreach(AbstractMetaFunction* fun, promoteFunctions) {
s << "inline ";
writeFunctionSignature(s, fun, 0, "promoted_",
Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));
s << " { ";
QString scriptFunctionName = fun->originalName();
AbstractMetaArgumentList args = fun->arguments();
if (fun->type())
s << "return ";
s << meta_class->qualifiedCppName() << "::";
s << fun->originalName() << "(";
for (int i = 0; i < args.size(); ++i) {
if (i > 0)
s << ", ";
s << args.at(i)->argumentName();
}
s << "); }" << endl;
}
s << "};" << endl << endl;
}
// Wrapper-------------------------------------------------------------------
s << "class " << wrapperClassName(meta_class)
<< " : public QObject" << endl
<< "{ Q_OBJECT" << endl;
s << "public:" << endl;
AbstractMetaEnumList enums1 = meta_class->enums();
AbstractMetaEnumList enums;
QList<FlagsTypeEntry*> flags;
foreach(AbstractMetaEnum* enum1, enums1) {
// catch gadgets and enums that are not exported on QObjects...
if (enum1->wasPublic() && (!meta_class->isQObject() || !enum1->hasQEnumsDeclaration())) {
enums << enum1;
if (enum1->typeEntry()->flags()) {
flags << enum1->typeEntry()->flags();
}
}
}
if (enums.count()) {
s << "Q_ENUMS(";
foreach(AbstractMetaEnum* enum1, enums) {
s << enum1->name() << " ";
}
s << ")" << endl;
if (flags.count()) {
s << "Q_FLAGS(";
foreach(FlagsTypeEntry* flag1, flags) {
QString origName = flag1->originalName();
int idx = origName.lastIndexOf("::");
if (idx!= -1) {
origName = origName.mid(idx+2);
}
s << origName << " ";
}
s << ")" << endl;
}
foreach(AbstractMetaEnum* enum1, enums) {
s << "enum " << enum1->name() << "{" << endl;
bool first = true;
foreach(AbstractMetaEnumValue* value, enum1->values()) {
if (first) { first = false; }
else { s << ", "; }
s << " " << value->name() << " = " << meta_class->qualifiedCppName() << "::" << value->name();
}
s << "};" << endl;
}
if (flags.count()) {
foreach(AbstractMetaEnum* enum1, enums) {
if (enum1->typeEntry()->flags()) {
QString origName = enum1->typeEntry()->flags()->originalName();
int idx = origName.lastIndexOf("::");
if (idx!= -1) {
origName = origName.mid(idx+2);
}
s << "Q_DECLARE_FLAGS("<< origName << ", " << enum1->name() <<")"<<endl;
}
}
}
}
s << "public slots:" << endl;
if (meta_class->generateShellClass() || !meta_class->isAbstract()) {
bool copyConstructorSeen = false;
bool defaultConstructorSeen = false;
foreach (const AbstractMetaFunction *fun, ctors) {
if (!fun->isPublic() || fun->isAbstract()) { continue; }
s << meta_class->qualifiedCppName() << "* ";
writeFunctionSignature(s, fun, 0, "new_",
Option(IncludeDefaultExpression | OriginalName | ShowStatic));
s << ";" << endl;
if (fun->arguments().size()==1 && meta_class->qualifiedCppName() == fun->arguments().at(0)->type()->typeEntry()->qualifiedCppName()) {
copyConstructorSeen = true;
}
if (fun->arguments().size()==0) {
defaultConstructorSeen = true;
}
}
if (meta_class->typeEntry()->isValue()
&& !copyConstructorSeen && defaultConstructorSeen) {
QString className = meta_class->generateShellClass()?shellClassName(meta_class):meta_class->qualifiedCppName();
s << meta_class->qualifiedCppName() << "* new_" << meta_class->name() << "(const " << meta_class->qualifiedCppName() << "& other) {" << endl;
s << className << "* a = new " << className << "();" << endl;
s << "*((" << meta_class->qualifiedCppName() << "*)a) = other;" << endl;
s << "return a; }" << endl;
}
}
if (meta_class->hasPublicDestructor() && !meta_class->isNamespace()) {
s << "void delete_" << meta_class->name() << "(" << meta_class->qualifiedCppName() << "* obj) { delete obj; } ";
s << endl;
}
AbstractMetaFunctionList functions = getFunctionsToWrap(meta_class);
foreach (const AbstractMetaFunction *function, functions) {
if (!function->isSlot() || function->isVirtual()) {
s << " ";
writeFunctionSignature(s, function, 0, QString(),
Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));
s << ";" << endl;
}
}
if (meta_class->hasDefaultToStringFunction() || meta_class->hasToStringCapability()) {
s << " QString py_toString(" << meta_class->qualifiedCppName() << "*);" << endl;
}
if (meta_class->hasDefaultIsNull()) {
s << " bool __nonzero__(" << meta_class->qualifiedCppName() << "* obj) { return !obj->isNull(); }" << endl;
}
// Field accessors
foreach (const AbstractMetaField *field, meta_class->fields()) {
if (field->isPublic()) {
writeFieldAccessors(s, field);
}
}
writeInjectedCode(s, meta_class);
s << "};" << endl << endl;
if (meta_class->qualifiedCppName().contains("Ssl")) {
s << "#endif" << endl << endl;
}
s << "#endif // " << include_block << endl;
}
void ShellHeaderGenerator::writeInjectedCode(QTextStream &s, const AbstractMetaClass *meta_class)
{
CodeSnipList code_snips = meta_class->typeEntry()->codeSnips();
foreach (const CodeSnip &cs, code_snips) {
if (cs.language == TypeSystem::PyWrapperDeclaration) {
s << cs.code() << endl;
}
}
}
<commit_msg>readded linefeed<commit_after>/****************************************************************************
**
** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Script Generator project on Qt Labs.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "shellheadergenerator.h"
#include "fileout.h"
#include <QtCore/QDir>
#include <qdebug.h>
QString ShellHeaderGenerator::fileNameForClass(const AbstractMetaClass *meta_class) const
{
return QString("PythonQtWrapper_%1.h").arg(meta_class->name());
}
void ShellHeaderGenerator::writeFieldAccessors(QTextStream &s, const AbstractMetaField *field)
{
const AbstractMetaFunction *setter = field->setter();
const AbstractMetaFunction *getter = field->getter();
// static fields are not supported (yet?)
if (setter->isStatic()) return;
// Uuid data4 did not work (TODO: move to typesystem...(
if (field->enclosingClass()->name()=="QUuid" && setter->name()=="data4") return;
if (field->enclosingClass()->name()=="QIPv6Address") return;
if (!field->type()->isConstant()) {
writeFunctionSignature(s, setter, 0, QString(),
Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | ShowStatic | UnderscoreSpaces));
s << "{ theWrappedObject->" << field->name() << " = " << setter->arguments()[0]->argumentName() << "; }\n";
}
writeFunctionSignature(s, getter, 0, QString(),
Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));
s << "{ return theWrappedObject->" << field->name() << "; }\n";
}
void ShellHeaderGenerator::write(QTextStream &s, const AbstractMetaClass *meta_class)
{
QString builtIn = ShellGenerator::isBuiltIn(meta_class->name())?"_builtin":"";
QString pro_file_name = meta_class->package().replace(".", "_") + builtIn + "/" + meta_class->package().replace(".", "_") + builtIn + ".pri";
priGenerator->addHeader(pro_file_name, fileNameForClass(meta_class));
setupGenerator->addClass(meta_class->package().replace(".", "_") + builtIn, meta_class);
QString include_block = "PYTHONQTWRAPPER_" + meta_class->name().toUpper() + "_H";
s << "#ifndef " << include_block << endl
<< "#define " << include_block << endl << endl;
Include inc = meta_class->typeEntry()->include();
ShellGenerator::writeInclude(s, inc);
s << "#include <QObject>" << endl << endl;
s << "#include <PythonQt.h>" << endl << endl;
IncludeList list = meta_class->typeEntry()->extraIncludes();
qSort(list.begin(), list.end());
foreach (const Include &inc, list) {
ShellGenerator::writeInclude(s, inc);
}
s << endl;
AbstractMetaFunctionList ctors = meta_class->queryFunctions(AbstractMetaClass::Constructors
| AbstractMetaClass::WasVisible
| AbstractMetaClass::NotRemovedFromTargetLang);
if (meta_class->qualifiedCppName().contains("Ssl")) {
s << "#ifndef QT_NO_OPENSSL" << endl;
}
// Shell-------------------------------------------------------------------
if (meta_class->generateShellClass()) {
AbstractMetaFunctionList virtualsForShell = getVirtualFunctionsForShell(meta_class);
s << "class " << shellClassName(meta_class)
<< " : public " << meta_class->qualifiedCppName() << endl << "{" << endl;
s << "public:" << endl;
foreach(AbstractMetaFunction* fun, ctors) {
s << " ";
writeFunctionSignature(s, fun, 0,"PythonQtShell_",
Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));
s << ":" << meta_class->qualifiedCppName() << "(";
QString scriptFunctionName = fun->originalName();
AbstractMetaArgumentList args = fun->arguments();
for (int i = 0; i < args.size(); ++i) {
if (i > 0)
s << ", ";
s << args.at(i)->argumentName();
}
s << "),_wrapper(NULL) {};" << endl;
}
s << endl;
s << " ~" << shellClassName(meta_class) << "();" << endl;
s << endl;
foreach(AbstractMetaFunction* fun, virtualsForShell) {
s << "virtual ";
writeFunctionSignature(s, fun, 0, QString(),
Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));
s << ";" << endl;
}
s << endl;
s << " PythonQtInstanceWrapper* _wrapper; " << endl;
s << "};" << endl << endl;
}
// Promoter-------------------------------------------------------------------
AbstractMetaFunctionList promoteFunctions = getProtectedFunctionsThatNeedPromotion(meta_class);
if (!promoteFunctions.isEmpty()) {
s << "class " << promoterClassName(meta_class)
<< " : public " << meta_class->qualifiedCppName() << endl << "{ public:" << endl;
foreach(AbstractMetaFunction* fun, promoteFunctions) {
s << "inline ";
writeFunctionSignature(s, fun, 0, "promoted_",
Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));
s << " { ";
QString scriptFunctionName = fun->originalName();
AbstractMetaArgumentList args = fun->arguments();
if (fun->type())
s << "return ";
s << meta_class->qualifiedCppName() << "::";
s << fun->originalName() << "(";
for (int i = 0; i < args.size(); ++i) {
if (i > 0)
s << ", ";
s << args.at(i)->argumentName();
}
s << "); }" << endl;
}
s << "};" << endl << endl;
}
// Wrapper-------------------------------------------------------------------
s << "class " << wrapperClassName(meta_class)
<< " : public QObject" << endl
<< "{ Q_OBJECT" << endl;
s << "public:" << endl;
AbstractMetaEnumList enums1 = meta_class->enums();
AbstractMetaEnumList enums;
QList<FlagsTypeEntry*> flags;
foreach(AbstractMetaEnum* enum1, enums1) {
// catch gadgets and enums that are not exported on QObjects...
if (enum1->wasPublic() && (!meta_class->isQObject() || !enum1->hasQEnumsDeclaration())) {
enums << enum1;
if (enum1->typeEntry()->flags()) {
flags << enum1->typeEntry()->flags();
}
}
}
if (enums.count()) {
s << "Q_ENUMS(";
foreach(AbstractMetaEnum* enum1, enums) {
s << enum1->name() << " ";
}
s << ")" << endl;
if (flags.count()) {
s << "Q_FLAGS(";
foreach(FlagsTypeEntry* flag1, flags) {
QString origName = flag1->originalName();
int idx = origName.lastIndexOf("::");
if (idx!= -1) {
origName = origName.mid(idx+2);
}
s << origName << " ";
}
s << ")" << endl;
}
foreach(AbstractMetaEnum* enum1, enums) {
s << "enum " << enum1->name() << "{" << endl;
bool first = true;
foreach(AbstractMetaEnumValue* value, enum1->values()) {
if (first) { first = false; }
else { s << ", "; }
s << " " << value->name() << " = " << meta_class->qualifiedCppName() << "::" << value->name();
}
s << "};" << endl;
}
if (flags.count()) {
foreach(AbstractMetaEnum* enum1, enums) {
if (enum1->typeEntry()->flags()) {
QString origName = enum1->typeEntry()->flags()->originalName();
int idx = origName.lastIndexOf("::");
if (idx!= -1) {
origName = origName.mid(idx+2);
}
s << "Q_DECLARE_FLAGS("<< origName << ", " << enum1->name() <<")"<<endl;
}
}
}
}
s << "public slots:" << endl;
if (meta_class->generateShellClass() || !meta_class->isAbstract()) {
bool copyConstructorSeen = false;
bool defaultConstructorSeen = false;
foreach (const AbstractMetaFunction *fun, ctors) {
if (!fun->isPublic() || fun->isAbstract()) { continue; }
s << meta_class->qualifiedCppName() << "* ";
writeFunctionSignature(s, fun, 0, "new_",
Option(IncludeDefaultExpression | OriginalName | ShowStatic));
s << ";" << endl;
if (fun->arguments().size()==1 && meta_class->qualifiedCppName() == fun->arguments().at(0)->type()->typeEntry()->qualifiedCppName()) {
copyConstructorSeen = true;
}
if (fun->arguments().size()==0) {
defaultConstructorSeen = true;
}
}
if (meta_class->typeEntry()->isValue()
&& !copyConstructorSeen && defaultConstructorSeen) {
QString className = meta_class->generateShellClass()?shellClassName(meta_class):meta_class->qualifiedCppName();
s << meta_class->qualifiedCppName() << "* new_" << meta_class->name() << "(const " << meta_class->qualifiedCppName() << "& other) {" << endl;
s << className << "* a = new " << className << "();" << endl;
s << "*((" << meta_class->qualifiedCppName() << "*)a) = other;" << endl;
s << "return a; }" << endl;
}
}
if (meta_class->hasPublicDestructor() && !meta_class->isNamespace()) {
s << "void delete_" << meta_class->name() << "(" << meta_class->qualifiedCppName() << "* obj) { delete obj; } ";
s << endl;
}
AbstractMetaFunctionList functions = getFunctionsToWrap(meta_class);
foreach (const AbstractMetaFunction *function, functions) {
if (!function->isSlot() || function->isVirtual()) {
s << " ";
writeFunctionSignature(s, function, 0, QString(),
Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));
s << ";" << endl;
}
}
if (meta_class->hasDefaultToStringFunction() || meta_class->hasToStringCapability()) {
s << " QString py_toString(" << meta_class->qualifiedCppName() << "*);" << endl;
}
if (meta_class->hasDefaultIsNull()) {
s << " bool __nonzero__(" << meta_class->qualifiedCppName() << "* obj) { return !obj->isNull(); }" << endl;
}
// Field accessors
foreach (const AbstractMetaField *field, meta_class->fields()) {
if (field->isPublic()) {
writeFieldAccessors(s, field);
}
}
writeInjectedCode(s, meta_class);
s << "};" << endl << endl;
if (meta_class->qualifiedCppName().contains("Ssl")) {
s << "#endif" << endl << endl;
}
s << "#endif // " << include_block << endl;
}
void ShellHeaderGenerator::writeInjectedCode(QTextStream &s, const AbstractMetaClass *meta_class)
{
CodeSnipList code_snips = meta_class->typeEntry()->codeSnips();
foreach (const CodeSnip &cs, code_snips) {
if (cs.language == TypeSystem::PyWrapperDeclaration) {
s << cs.code() << endl;
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2003-2016 Rony Shapiro <ronys@pwsafe.org>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/** \file mainManage.cpp
* This file contains implementations of PasswordSafeFrame
* member functions corresponding to actions under the 'Manage'
* menubar menu.
*/
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "wx/filename.h"
#include "passwordsafeframe.h"
#include "safecombinationprompt.h"
#include "optionspropsheet.h"
#include "SystemTray.h"
#include "ManagePwdPolicies.h"
#ifndef NO_YUBI
#include "yubicfg.h"
#endif
#include "core/PWSdirs.h"
#ifdef __WXMSW__
#include <wx/msw/msvcrt.h>
#endif
/*!
* wxEVT_COMMAND_MENU_SELECTED event handler for ID_OPTIONS_M
*/
void PasswordSafeFrame::OnPreferencesClick( wxCommandEvent& /* evt */ )
{
PWSprefs* prefs = PWSprefs::GetInstance();
const StringX sxOldDBPrefsString(prefs->Store());
COptions *window = new COptions(this);
if (window->ShowModal() == wxID_OK) {
StringX sxNewDBPrefsString(prefs->Store(true));
// Update system tray icon if visible so changes show up immediately
if (m_sysTray && prefs->GetPref(PWSprefs::UseSystemTray))
m_sysTray->ShowIcon();
if (!m_core.GetCurFile().empty() && !m_core.IsReadOnly() &&
m_core.GetReadFileVersion() == PWSfile::VCURRENT) {
if (sxOldDBPrefsString != sxNewDBPrefsString) {
Command *pcmd = DBPrefsCommand::Create(&m_core, sxNewDBPrefsString);
if (pcmd) {
//I don't know why notifications should ever be suspended, but that's how
//things were before I messed with them, so I want to limit the damage by
//enabling notifications only as long as required and no more
m_core.ResumeOnDBNotification();
Execute(pcmd); //deleted automatically
m_core.SuspendOnDBNotification();
}
}
}
}
window->Destroy();
}
//////////////////////////////////////////
// Backup and Restore
//
void PasswordSafeFrame::OnBackupSafe(wxCommandEvent& /*evt*/)
{
PWSprefs *prefs = PWSprefs::GetInstance();
const wxFileName currbackup(towxstring(prefs->GetPref(PWSprefs::CurrentBackup)));
const wxString title(_("Please Choose a Name for this Backup:"));
wxString dir;
if (m_core.GetCurFile().empty())
dir = towxstring(PWSdirs::GetSafeDir());
else {
wxFileName::SplitPath(towxstring(m_core.GetCurFile()), &dir, NULL, NULL);
wxCHECK_RET(!dir.IsEmpty(), _("Could not parse current file path"));
}
//returns empty string if user cancels
wxString wxbf = wxFileSelector(title,
dir,
currbackup.GetFullName(),
wxT("bak"),
_("Password Safe Backups (*.bak)|*.bak"),
wxFD_SAVE|wxFD_OVERWRITE_PROMPT,
this);
/*
The wxFileSelector code says it appends the default extension if user
doesn't type one, but it actually doesn't and I don't see the purported
code in 2.8.10. And doing it ourselves after the dialog has returned is
risky because we might silenty overwrite an existing file
*/
//create a copy to avoid multiple conversions to StringX
const StringX backupfile(tostringx(wxbf));
#ifdef NOT_YET
if (m_inExit) {
// If U3ExitNow called while in CPWFileDialog,
// PostQuitMessage makes us return here instead
// of exiting the app. Try resignalling
PostQuitMessage(0);
return PWScore::USER_CANCEL;
}
#endif
if (!backupfile.empty()) { //i.e. if user didn't cancel
if (m_core.WriteFile(backupfile, m_core.GetReadFileVersion(),
false) == PWScore::CANT_OPEN_FILE) {
wxMessageBox( wxbf << wxT("\n\n") << _("Could not open file for writing!"),
_("Write Error"), wxOK|wxICON_ERROR, this);
}
prefs->SetPref(PWSprefs::CurrentBackup, backupfile);
}
}
void PasswordSafeFrame::OnRestoreSafe(wxCommandEvent& /*evt*/)
{
if (SaveIfChanged() != PWScore::SUCCESS)
return;
const wxFileName currbackup(towxstring(PWSprefs::GetInstance()->GetPref(PWSprefs::CurrentBackup)));
wxString dir;
if (m_core.GetCurFile().empty())
dir = towxstring(PWSdirs::GetSafeDir());
else {
wxFileName::SplitPath(towxstring(m_core.GetCurFile()), &dir, NULL, NULL);
wxCHECK_RET(!dir.IsEmpty(), _("Could not parse current file path"));
}
//returns empty string if user cancels
wxString wxbf = wxFileSelector(_("Please Choose a Backup to restore:"),
dir,
currbackup.GetFullName(),
wxT("bak"),
_("Password Safe Backups (*.bak)|*.bak"),
wxFD_OPEN|wxFD_FILE_MUST_EXIST,
this);
if (wxbf.empty())
return;
#ifdef NOT_YET
if (m_inExit) {
// If U3ExitNow called while in CPWFileDialog,
// PostQuitMessage makes us return here instead
// of exiting the app. Try resignalling
PostQuitMessage(0);
return PWScore::USER_CANCEL;
}
#endif
CSafeCombinationPrompt pwdprompt(this, m_core, wxbf);
if (pwdprompt.ShowModal() == wxID_OK) {
const StringX passkey = pwdprompt.GetPassword();
// unlock the file we're leaving
if (!m_core.GetCurFile().empty()) {
m_core.UnlockFile(m_core.GetCurFile().c_str());
}
// clear the data before restoring
ClearData();
if (m_core.ReadFile(tostringx(wxbf), passkey, true, MAXTEXTCHARS) == PWScore::CANT_OPEN_FILE) {
wxMessageBox(wxbf << wxT("\n\n") << _("Could not open file for reading!"),
_("File Read Error"), wxOK | wxICON_ERROR, this);
return /*PWScore::CANT_OPEN_FILE*/;
}
m_core.SetCurFile(wxEmptyString); // Force a Save As...
m_core.SetDBChanged(true); // So that the restored file will be saved
SetTitle(_("Password Safe - <Untitled Restored Backup>"));
#ifdef NOT_YET
app.SetTooltipText(L"PasswordSafe");
#endif
#ifdef NOT_YET
ChangeOkUpdate();
#endif
RefreshViews();
}
}
/*!
* wxEVT_COMMAND_MENU_SELECTED event handler for ID_PWDPOLSM
*/
void PasswordSafeFrame::OnPwdPolsMClick( wxCommandEvent& )
{
CManagePasswordPolicies ppols(this, m_core);
ppols.ShowModal();
}
#ifndef NO_YUBI
/*!
* wxEVT_COMMAND_MENU_SELECTED event handler for ID_YUBIKEY_MNG
*/
void PasswordSafeFrame::OnYubikeyMngClick( wxCommandEvent& /* event */ )
{
YubiCfgDlg ykCfg(this, m_core);
ykCfg.ShowModal();
}
#endif
<commit_msg>spelling: silently<commit_after>/*
* Copyright (c) 2003-2016 Rony Shapiro <ronys@pwsafe.org>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/** \file mainManage.cpp
* This file contains implementations of PasswordSafeFrame
* member functions corresponding to actions under the 'Manage'
* menubar menu.
*/
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "wx/filename.h"
#include "passwordsafeframe.h"
#include "safecombinationprompt.h"
#include "optionspropsheet.h"
#include "SystemTray.h"
#include "ManagePwdPolicies.h"
#ifndef NO_YUBI
#include "yubicfg.h"
#endif
#include "core/PWSdirs.h"
#ifdef __WXMSW__
#include <wx/msw/msvcrt.h>
#endif
/*!
* wxEVT_COMMAND_MENU_SELECTED event handler for ID_OPTIONS_M
*/
void PasswordSafeFrame::OnPreferencesClick( wxCommandEvent& /* evt */ )
{
PWSprefs* prefs = PWSprefs::GetInstance();
const StringX sxOldDBPrefsString(prefs->Store());
COptions *window = new COptions(this);
if (window->ShowModal() == wxID_OK) {
StringX sxNewDBPrefsString(prefs->Store(true));
// Update system tray icon if visible so changes show up immediately
if (m_sysTray && prefs->GetPref(PWSprefs::UseSystemTray))
m_sysTray->ShowIcon();
if (!m_core.GetCurFile().empty() && !m_core.IsReadOnly() &&
m_core.GetReadFileVersion() == PWSfile::VCURRENT) {
if (sxOldDBPrefsString != sxNewDBPrefsString) {
Command *pcmd = DBPrefsCommand::Create(&m_core, sxNewDBPrefsString);
if (pcmd) {
//I don't know why notifications should ever be suspended, but that's how
//things were before I messed with them, so I want to limit the damage by
//enabling notifications only as long as required and no more
m_core.ResumeOnDBNotification();
Execute(pcmd); //deleted automatically
m_core.SuspendOnDBNotification();
}
}
}
}
window->Destroy();
}
//////////////////////////////////////////
// Backup and Restore
//
void PasswordSafeFrame::OnBackupSafe(wxCommandEvent& /*evt*/)
{
PWSprefs *prefs = PWSprefs::GetInstance();
const wxFileName currbackup(towxstring(prefs->GetPref(PWSprefs::CurrentBackup)));
const wxString title(_("Please Choose a Name for this Backup:"));
wxString dir;
if (m_core.GetCurFile().empty())
dir = towxstring(PWSdirs::GetSafeDir());
else {
wxFileName::SplitPath(towxstring(m_core.GetCurFile()), &dir, NULL, NULL);
wxCHECK_RET(!dir.IsEmpty(), _("Could not parse current file path"));
}
//returns empty string if user cancels
wxString wxbf = wxFileSelector(title,
dir,
currbackup.GetFullName(),
wxT("bak"),
_("Password Safe Backups (*.bak)|*.bak"),
wxFD_SAVE|wxFD_OVERWRITE_PROMPT,
this);
/*
The wxFileSelector code says it appends the default extension if user
doesn't type one, but it actually doesn't and I don't see the purported
code in 2.8.10. And doing it ourselves after the dialog has returned is
risky because we might silently overwrite an existing file
*/
//create a copy to avoid multiple conversions to StringX
const StringX backupfile(tostringx(wxbf));
#ifdef NOT_YET
if (m_inExit) {
// If U3ExitNow called while in CPWFileDialog,
// PostQuitMessage makes us return here instead
// of exiting the app. Try resignalling
PostQuitMessage(0);
return PWScore::USER_CANCEL;
}
#endif
if (!backupfile.empty()) { //i.e. if user didn't cancel
if (m_core.WriteFile(backupfile, m_core.GetReadFileVersion(),
false) == PWScore::CANT_OPEN_FILE) {
wxMessageBox( wxbf << wxT("\n\n") << _("Could not open file for writing!"),
_("Write Error"), wxOK|wxICON_ERROR, this);
}
prefs->SetPref(PWSprefs::CurrentBackup, backupfile);
}
}
void PasswordSafeFrame::OnRestoreSafe(wxCommandEvent& /*evt*/)
{
if (SaveIfChanged() != PWScore::SUCCESS)
return;
const wxFileName currbackup(towxstring(PWSprefs::GetInstance()->GetPref(PWSprefs::CurrentBackup)));
wxString dir;
if (m_core.GetCurFile().empty())
dir = towxstring(PWSdirs::GetSafeDir());
else {
wxFileName::SplitPath(towxstring(m_core.GetCurFile()), &dir, NULL, NULL);
wxCHECK_RET(!dir.IsEmpty(), _("Could not parse current file path"));
}
//returns empty string if user cancels
wxString wxbf = wxFileSelector(_("Please Choose a Backup to restore:"),
dir,
currbackup.GetFullName(),
wxT("bak"),
_("Password Safe Backups (*.bak)|*.bak"),
wxFD_OPEN|wxFD_FILE_MUST_EXIST,
this);
if (wxbf.empty())
return;
#ifdef NOT_YET
if (m_inExit) {
// If U3ExitNow called while in CPWFileDialog,
// PostQuitMessage makes us return here instead
// of exiting the app. Try resignalling
PostQuitMessage(0);
return PWScore::USER_CANCEL;
}
#endif
CSafeCombinationPrompt pwdprompt(this, m_core, wxbf);
if (pwdprompt.ShowModal() == wxID_OK) {
const StringX passkey = pwdprompt.GetPassword();
// unlock the file we're leaving
if (!m_core.GetCurFile().empty()) {
m_core.UnlockFile(m_core.GetCurFile().c_str());
}
// clear the data before restoring
ClearData();
if (m_core.ReadFile(tostringx(wxbf), passkey, true, MAXTEXTCHARS) == PWScore::CANT_OPEN_FILE) {
wxMessageBox(wxbf << wxT("\n\n") << _("Could not open file for reading!"),
_("File Read Error"), wxOK | wxICON_ERROR, this);
return /*PWScore::CANT_OPEN_FILE*/;
}
m_core.SetCurFile(wxEmptyString); // Force a Save As...
m_core.SetDBChanged(true); // So that the restored file will be saved
SetTitle(_("Password Safe - <Untitled Restored Backup>"));
#ifdef NOT_YET
app.SetTooltipText(L"PasswordSafe");
#endif
#ifdef NOT_YET
ChangeOkUpdate();
#endif
RefreshViews();
}
}
/*!
* wxEVT_COMMAND_MENU_SELECTED event handler for ID_PWDPOLSM
*/
void PasswordSafeFrame::OnPwdPolsMClick( wxCommandEvent& )
{
CManagePasswordPolicies ppols(this, m_core);
ppols.ShowModal();
}
#ifndef NO_YUBI
/*!
* wxEVT_COMMAND_MENU_SELECTED event handler for ID_YUBIKEY_MNG
*/
void PasswordSafeFrame::OnYubikeyMngClick( wxCommandEvent& /* event */ )
{
YubiCfgDlg ykCfg(this, m_core);
ykCfg.ShowModal();
}
#endif
<|endoftext|>
|
<commit_before>#include "comm.h"
#include "room.h"
#include "low.h"
#include "extern.h"
#include "obj_gas.h"
#include "pathfinder.h"
#include "obj_portal.h"
#include "being.h"
#include "obj_plant.h"
#include "materials.h"
// TGas uses function pointers to get a virtual-class like affect,
// without having to have multiple objects and object types for each
// gas type created in makeNewObj it also makes gasses able to change
// their type and behavior on the fly, which can be useful if decaying
typedef void (*specialsFunction)(TGas *myself);
typedef const char * (*nameFunction)(const TGas *myself);
int getSmokeIndex(int volume)
{
if(volume<=0){
return 0;
} else if(volume<=5){
return 1;
} else if(volume<=10){
return 2;
} else if(volume<=25){
return 3;
} else if(volume<=50){
return 4;
} else if(volume<=100){
return 5;
} else if(volume<=250){
return 6;
} else if(volume<=1000){
return 7;
} else if(volume<=10000){
return 8;
} else if(volume<=25000){
return 9;
} else {
return 10;
}
}
void doNothing(TGas *myself)
{
}
void doChoke(TGas *myself)
{
if(!myself->roomp || getSmokeIndex(myself->getVolume()) < 7)
return;
for(StuffIter it=myself->roomp->stuff.begin();it!=myself->roomp->stuff.end();){
TBeing *tb;
if((tb=dynamic_cast<TBeing *>(*(it++))) && !::number(0,4)){
tb->sendTo(COLOR_BASIC, "<r>The large amount of smoke in the room causes you to choke and cough!<1>\n\r");
int rc=tb->reconcileDamage(tb, ::number(3,11), DAMAGE_SUFFOCATION);
if (IS_SET_DELETE(rc, DELETE_VICT)) {
delete tb;
continue;
}
}
}
}
#define NUM_SCENTS 3
void doScent(TGas *myself)
{
if(!myself->roomp)
return;
static const sstring self_scents[NUM_SCENTS] = {
"Is that your own musk you smell? It must be.",
"This place smells alot like you. You've really left your mark here.",
"This smells like an interesting place full of danger or excitement!"
};
static const sstring opp_scents[NUM_SCENTS] = {
"You smell an attractive troglodyte nearby.",
"Someone was here recently who smells GOOD! Yowza, what a troglodyte!",
"You smell an alluring troglodyte nearby who was in danger!",
};
static const sstring same_scents[NUM_SCENTS] = {
"The scent of some nearby showoff troglodyte fills your nostrils.",
"You smell some troglodyge's musk nearby. What a loser.",
"It smells like troglodyte has stunk up the place here with their own musk.",
};
TBeing *createdBy = myself->getCreatedBy();
for(StuffIter it= myself->roomp->stuff.begin();it!= myself->roomp->stuff.end();++it)
{
// only 25% chance of action per tick
if (::number(0,3))
continue;
TPlant *plant = dynamic_cast<TPlant *>(*it);
if (plant)
{
plant->updateAge();
act("$n wilts slightly from exposure to $N!", FALSE, plant, NULL, myself, TO_ROOM);
continue;
}
TBeing *being = dynamic_cast<TBeing *>(*it);
if (!being)
continue;
if (/*!being->isImmortal() && */!being->isImmune(IMMUNE_SUFFOCATION, WEAR_BODY) &&
!being->getMyRace()->hasTalent(TALENT_MUSK))
{
act("The smell of $N in this room makes you gag!", FALSE, being, NULL, myself, TO_CHAR);
act("$n coughs and gags on $N in the room!", FALSE, being, NULL, myself, TO_ROOM);
if (!being->isTough())
{
act("You feel really queasy.", FALSE, being, NULL, myself, TO_CHAR);
act("$n turns a sickly pale color.", FALSE, being, NULL, myself, TO_ROOM);
being->doAction("", CMD_PUKE);
}
continue;
}
const sstring *scents = NULL;
if (myself->hasCreator(being->name))
scents = self_scents;
else if (createdBy && being->getSex() == createdBy->getSex())
scents = same_scents;
else
scents = opp_scents;
act(scents[::number(0, NUM_SCENTS-1)], FALSE, being, NULL, myself, TO_CHAR);
}
}
const char * getNameNothing(const TGas *myself)
{
return "smoke wisps generic";
}
const char * getDescNothing(const TGas *myself)
{
return "an unidentified gas cloud is here.";
}
const char * getShortNameNothing(const TGas *myself)
{
return "smoke";
}
const char * getNameSmoke(const TGas *myself)
{
static const char *smokename [] =
{
"<k>a few wisps of smoke<1>",
"<k>a tiny cloud of smoke<1>",
"<k>a small cloud of smoke<1>",
"<k>a cloud of smoke<1>",
"<k>a fair sized cloud of smoke<1>",
"<k>a big cloud of smoke<1>",
"<k>a large cloud of smoke<1>",
"<k>a huge cloud of smoke<1>",
"<k>a massive cloud of smoke<1>",
"<k>a tremendously huge cloud of smoke<1>",
"<k>a room full of smoke<1>"
};
return smokename[getSmokeIndex(myself->getVolume())];
}
const char * getDescSmoke(const TGas *myself)
{
static const char *smokedesc [] =
{
"<k>A few wisps of smoke are fading fast.<1>",
"<k>A tiny cloud of smoke has gathered here.<1>",
"<k>A small cloud of smoke is here.<1>",
"<k>A cloud of smoke is here.<1>",
"<k>A fair sized cloud of smoke is here.<1>",
"<k>A big cloud of smoke is here.<1>",
"<k>A large cloud of smoke is here.<1>",
"<k>A huge cloud of smoke is here.<1>",
"<k>A massive cloud of smoke is here.<1>",
"<k>A tremendously huge cloud of smoke dominates the area.<1>",
"<k>The whole area is filled with smoke.<1>"
};
return smokedesc[getSmokeIndex(myself->getVolume())];
}
const char * getShortNameSmoke(const TGas *myself)
{
return "smoke";
}
const char * getNameMusk(const TGas *myself)
{
return "a cloud of musk";
}
const char * getDescMusk(const TGas *myself)
{
return "a <Y>yellowish musk cloud<1> is here.";
}
const char * getShortNameMusk(const TGas *myself)
{
return "musk cloud";
}
// specials for a gas - choking, stinking, etc
void TGas::doSpecials()
{
static const specialsFunction specials[GAS_MAX] = { doNothing, doChoke, doScent };
return specials[getType()](this);
}
// merge with other gas clouds in the room
void TGas::doMerge(TMergeable *tm)
{
TGas *tGas;
if(!(tGas=dynamic_cast<TGas *>(tm)))
return;
addCreator(tGas->creator.c_str());
addToVolume(tGas->getVolume());
--(*tGas);
delete tGas;
}
bool TGas::willMerge(TMergeable *tm)
{
TGas *tGas;
if(!(tGas=dynamic_cast<TGas *>(tm)) ||
tGas==this || tGas->type != type)
return false;
return true;
}
// drift upwards, or towards the closest outdoor room
void TGas::doDrift()
{
roomDirData *exitp;
TRoom *rp=roomp;
TThing *t;
TPortal *tp;
if(!roomp)
return;
// move up if possible
if((exitp=roomp->exitDir(DIR_UP)) &&
!IS_SET(exitp->condition, EX_CLOSED) &&
(rp=real_roomp(exitp->to_room))){
act("$n drifts upwards.",FALSE, this, 0, 0, TO_ROOM);
--(*this);
*rp += *this;
act("$n drifts in from below.",FALSE, this, 0, 0, TO_ROOM);
} else {
dirTypeT dir;
TPathFinder path;
path.setUsePortals(true);
path.setNoMob(false);
path.setThruDoors(false);
path.setRange(25);
dir=path.findPath(inRoom(), findOutdoors());
if(dir >= MAX_DIR){
dir=dirTypeT(dir-MAX_DIR+1);
int seen = 0;
for(StuffIter it=roomp->stuff.begin();it!=roomp->stuff.end();){
if (!(t=*(it++)))
continue;
if ((tp=dynamic_cast<TPortal *>(t))){
seen++;
if (dir == seen) {
if((rp=real_roomp(tp->getTarget()))){
act(format("$n drifts into %s.") % tp->getName(), FALSE, this, 0, 0, TO_ROOM);
--(*this);
*rp += *this;
act(format("$n drifts in from %s.") % tp->getName(), FALSE, this, 0, 0, TO_ROOM);
}
}
}
}
} else if (dir >= MIN_DIR && dir != DIR_DOWN &&
(exitp=roomp->exitDir(dir)) &&
(rp=real_roomp(exitp->to_room))){
act(format("$n drifts %s.") % dirs_to_blank[dir], FALSE, this, 0, 0, TO_ROOM);
--(*this);
*rp += *this;
act(format("$n drifts in from the %s.") % dirs[rev_dir[dir]], FALSE, this, 0, 0, TO_ROOM);
}
}
}
TGas::TGas(gasTypeT gasType) :
TObj()
{
type = gasType;
}
TGas::TGas(const TGas &a) :
TObj(a)
{
type = a.type;
}
void TGas::setVolume(int n)
{
TObj::setVolume(n);
updateDesc();
if(roomp && roomp->isIndoorSector()){
obj_flags.decay_time=getVolume()/2;
} else {
obj_flags.decay_time=0;
}
}
void TGas::addToVolume(int n)
{
TObj::addToVolume(n);
updateDesc();
if(roomp && roomp->isIndoorSector()){
obj_flags.decay_time=getVolume()/2;
} else {
obj_flags.decay_time=0;
}
}
const char * TGas::getName() const
{
static const nameFunction names[GAS_MAX] = { getNameNothing, getNameSmoke, getNameMusk };
return names[getType()](this);
}
const char * TGas::getDesc() const
{
static const nameFunction descs[GAS_MAX] = { getDescNothing, getDescSmoke, getDescMusk };
return descs[getType()](this);
}
const char * TGas::getShortName() const
{
static const nameFunction shortnames[GAS_MAX] = { getShortNameNothing, getShortNameSmoke, getShortNameMusk };
return shortnames[getType()](this);
}
void TGas::updateDesc()
{
if (isObjStat(ITEM_STRUNG)) {
delete [] shortDescr;
delete [] descr;
extraDescription *exd;
while ((exd = ex_description)) {
ex_description = exd->next;
delete exd;
}
ex_description = NULL;
delete [] action_description;
action_description = NULL;
} else {
addObjStat(ITEM_STRUNG);
name = mud_str_dup(obj_index[getItemIndex()].name);
ex_description = NULL;
action_description = NULL;
}
shortDescr = mud_str_dup(getName());
setDescr(mud_str_dup(getDesc()));
}
bool TGas::isPluralItem() const
{
// a few drops of smoke
if (getType() == GAS_SMOKE && getSmokeIndex(getVolume()) == 0)
return true;
// otherwise, make recursive
return TObj::isPluralItem();
}
int TThing::dropGas(int amt, gasTypeT type)
{
TGas *gas = NULL;
if(amt == 0 || !roomp || type >= GAS_MAX)
return FALSE;
// look for preexisting smoke
for(StuffIter it= roomp->stuff.begin();it!= roomp->stuff.end();++it)
{
gas = dynamic_cast<TGas *>(*it);
if (gas && gas->getType() == type)
break;
gas = NULL;
}
// create new gas
if (!gas)
{
TObj *obj = NULL;
int robj = real_object(GENERIC_GAS);
if (robj < 0 || robj >= (signed int) obj_index.size())
{
vlogf(LOG_BUG, format("dropGas(): No object (%d) in database!") % robj);
return FALSE;
}
if (!(obj = read_object(robj, REAL)))
{
vlogf(LOG_LOW, format("Error, No gas object created (%d)") % robj);
return FALSE;
}
if (!(gas = dynamic_cast<TGas*>(obj)))
{
vlogf(LOG_LOW, "Error, Could not cast gas to TGas");
return FALSE;
}
gas->setType(type);
gas->swapToStrung();
REMOVE_BIT(gas->obj_flags.wear_flags, ITEM_TAKE);
gas->canBeSeen = 1;
gas->setMaterial(MAT_GHOSTLY);
gas->setObjStat(ITEM_NORENT);
delete [] gas->name;
gas->name = mud_str_dup(gas->getShortName());
*roomp += *gas;
}
if (!gas->hasCreator(name))
gas->addCreator(name);
gas->addToVolume(amt);
return TRUE;
}
void TGas::decayMe()
{
int volume = getVolume();
if (!roomp) {
vlogf(LOG_BUG, "TGas::decayMe() called while TGas not in room!");
setVolume(0);
return;
}
if (volume <= 0)
setVolume(0);
else if (volume < 25)
addToVolume((roomp->isIndoorSector() ? -5 : -8));
else // large smokes evaporate faster
addToVolume((roomp->isIndoorSector() ? -(volume/15) : -(volume/8)));
if (getVolume() < 0)
setVolume(0);
}
sstring TGas::statObjInfo() const
{
return "";
}
void TGas::getFourValues(int *x1, int *x2, int *x3, int *x4) const
{
*x1 = int(type);
*x2 = 0;
*x3 = 0;
*x4 = 0;
}
void TGas::assignFourValues(int t, int, int, int)
{
type = gasTypeT(t);
}
<commit_msg>fixed a crash with gas code - needs to break if it modified room->stuff<commit_after>#include "comm.h"
#include "room.h"
#include "low.h"
#include "extern.h"
#include "obj_gas.h"
#include "pathfinder.h"
#include "obj_portal.h"
#include "being.h"
#include "obj_plant.h"
#include "materials.h"
// TGas uses function pointers to get a virtual-class like affect,
// without having to have multiple objects and object types for each
// gas type created in makeNewObj it also makes gasses able to change
// their type and behavior on the fly, which can be useful if decaying
typedef void (*specialsFunction)(TGas *myself);
typedef const char * (*nameFunction)(const TGas *myself);
int getSmokeIndex(int volume)
{
if(volume<=0){
return 0;
} else if(volume<=5){
return 1;
} else if(volume<=10){
return 2;
} else if(volume<=25){
return 3;
} else if(volume<=50){
return 4;
} else if(volume<=100){
return 5;
} else if(volume<=250){
return 6;
} else if(volume<=1000){
return 7;
} else if(volume<=10000){
return 8;
} else if(volume<=25000){
return 9;
} else {
return 10;
}
}
void doNothing(TGas *myself)
{
}
void doChoke(TGas *myself)
{
if(!myself->roomp || getSmokeIndex(myself->getVolume()) < 7)
return;
for(StuffIter it=myself->roomp->stuff.begin();it!=myself->roomp->stuff.end();){
TBeing *tb;
if((tb=dynamic_cast<TBeing *>(*(it++))) && !::number(0,4)){
tb->sendTo(COLOR_BASIC, "<r>The large amount of smoke in the room causes you to choke and cough!<1>\n\r");
int rc=tb->reconcileDamage(tb, ::number(3,11), DAMAGE_SUFFOCATION);
if (IS_SET_DELETE(rc, DELETE_VICT)) {
delete tb;
continue;
}
}
}
}
#define NUM_SCENTS 3
void doScent(TGas *myself)
{
if(!myself->roomp)
return;
static const sstring self_scents[NUM_SCENTS] = {
"Is that your own musk you smell? It must be.",
"This place smells alot like you. You've really left your mark here.",
"This smells like an interesting place full of danger or excitement!"
};
static const sstring opp_scents[NUM_SCENTS] = {
"You smell an attractive troglodyte nearby.",
"Someone was here recently who smells GOOD! Yowza, what a troglodyte!",
"You smell an alluring troglodyte nearby who was in danger!",
};
static const sstring same_scents[NUM_SCENTS] = {
"The scent of some nearby showoff troglodyte fills your nostrils.",
"You smell some troglodyge's musk nearby. What a loser.",
"It smells like troglodyte has stunk up the place here with their own musk.",
};
TBeing *createdBy = myself->getCreatedBy();
for(StuffIter it= myself->roomp->stuff.begin();it!= myself->roomp->stuff.end();++it)
{
// only 25% chance of action per tick
if (::number(0,3))
continue;
TPlant *plant = dynamic_cast<TPlant *>(*it);
if (plant)
{
plant->updateAge();
act("$n wilts slightly from exposure to $N!", FALSE, plant, NULL, myself, TO_ROOM);
continue;
}
TBeing *being = dynamic_cast<TBeing *>(*it);
if (!being)
continue;
if (/*!being->isImmortal() && */!being->isImmune(IMMUNE_SUFFOCATION, WEAR_BODY) &&
!being->getMyRace()->hasTalent(TALENT_MUSK))
{
act("The smell of $N in this room makes you gag!", FALSE, being, NULL, myself, TO_CHAR);
act("$n coughs and gags on $N in the room!", FALSE, being, NULL, myself, TO_ROOM);
if (!being->isTough())
{
act("You feel really queasy.", FALSE, being, NULL, myself, TO_CHAR);
act("$n turns a sickly pale color.", FALSE, being, NULL, myself, TO_ROOM);
being->doAction("", CMD_PUKE);
}
continue;
}
const sstring *scents = NULL;
if (myself->hasCreator(being->name))
scents = self_scents;
else if (createdBy && being->getSex() == createdBy->getSex())
scents = same_scents;
else
scents = opp_scents;
act(scents[::number(0, NUM_SCENTS-1)], FALSE, being, NULL, myself, TO_CHAR);
}
}
const char * getNameNothing(const TGas *myself)
{
return "smoke wisps generic";
}
const char * getDescNothing(const TGas *myself)
{
return "an unidentified gas cloud is here.";
}
const char * getShortNameNothing(const TGas *myself)
{
return "smoke";
}
const char * getNameSmoke(const TGas *myself)
{
static const char *smokename [] =
{
"<k>a few wisps of smoke<1>",
"<k>a tiny cloud of smoke<1>",
"<k>a small cloud of smoke<1>",
"<k>a cloud of smoke<1>",
"<k>a fair sized cloud of smoke<1>",
"<k>a big cloud of smoke<1>",
"<k>a large cloud of smoke<1>",
"<k>a huge cloud of smoke<1>",
"<k>a massive cloud of smoke<1>",
"<k>a tremendously huge cloud of smoke<1>",
"<k>a room full of smoke<1>"
};
return smokename[getSmokeIndex(myself->getVolume())];
}
const char * getDescSmoke(const TGas *myself)
{
static const char *smokedesc [] =
{
"<k>A few wisps of smoke are fading fast.<1>",
"<k>A tiny cloud of smoke has gathered here.<1>",
"<k>A small cloud of smoke is here.<1>",
"<k>A cloud of smoke is here.<1>",
"<k>A fair sized cloud of smoke is here.<1>",
"<k>A big cloud of smoke is here.<1>",
"<k>A large cloud of smoke is here.<1>",
"<k>A huge cloud of smoke is here.<1>",
"<k>A massive cloud of smoke is here.<1>",
"<k>A tremendously huge cloud of smoke dominates the area.<1>",
"<k>The whole area is filled with smoke.<1>"
};
return smokedesc[getSmokeIndex(myself->getVolume())];
}
const char * getShortNameSmoke(const TGas *myself)
{
return "smoke";
}
const char * getNameMusk(const TGas *myself)
{
return "a cloud of musk";
}
const char * getDescMusk(const TGas *myself)
{
return "a <Y>yellowish musk cloud<1> is here.";
}
const char * getShortNameMusk(const TGas *myself)
{
return "musk cloud";
}
// specials for a gas - choking, stinking, etc
void TGas::doSpecials()
{
static const specialsFunction specials[GAS_MAX] = { doNothing, doChoke, doScent };
return specials[getType()](this);
}
// merge with other gas clouds in the room
void TGas::doMerge(TMergeable *tm)
{
TGas *tGas;
if(!(tGas=dynamic_cast<TGas *>(tm)))
return;
addCreator(tGas->creator.c_str());
addToVolume(tGas->getVolume());
--(*tGas);
delete tGas;
}
bool TGas::willMerge(TMergeable *tm)
{
TGas *tGas;
if(!(tGas=dynamic_cast<TGas *>(tm)) ||
tGas==this || tGas->type != type)
return false;
return true;
}
// drift upwards, or towards the closest outdoor room
void TGas::doDrift()
{
roomDirData *exitp;
TRoom *rp=roomp;
TThing *t;
TPortal *tp;
if(!roomp)
return;
// move up if possible
if((exitp=roomp->exitDir(DIR_UP)) &&
!IS_SET(exitp->condition, EX_CLOSED) &&
(rp=real_roomp(exitp->to_room))){
act("$n drifts upwards.",FALSE, this, 0, 0, TO_ROOM);
--(*this);
*rp += *this;
act("$n drifts in from below.",FALSE, this, 0, 0, TO_ROOM);
} else {
dirTypeT dir;
TPathFinder path;
path.setUsePortals(true);
path.setNoMob(false);
path.setThruDoors(false);
path.setRange(25);
dir=path.findPath(inRoom(), findOutdoors());
if(dir >= MAX_DIR){
dir=dirTypeT(dir-MAX_DIR+1);
int seen = 0;
for(StuffIter it=roomp->stuff.begin();it!=roomp->stuff.end();){
if (!(t=*(it++)))
continue;
if ((tp=dynamic_cast<TPortal *>(t)) && dir == seen && (rp=real_roomp(tp->getTarget()))){
act(format("$n drifts into %s.") % tp->getName(), FALSE, this, 0, 0, TO_ROOM);
--(*this);
*rp += *this;
act(format("$n drifts in from %s.") % tp->getName(), FALSE, this, 0, 0, TO_ROOM);
break;
}
}
} else if (dir >= MIN_DIR && dir != DIR_DOWN &&
(exitp=roomp->exitDir(dir)) &&
(rp=real_roomp(exitp->to_room))){
act(format("$n drifts %s.") % dirs_to_blank[dir], FALSE, this, 0, 0, TO_ROOM);
--(*this);
*rp += *this;
act(format("$n drifts in from the %s.") % dirs[rev_dir[dir]], FALSE, this, 0, 0, TO_ROOM);
}
}
}
TGas::TGas(gasTypeT gasType) :
TObj()
{
type = gasType;
}
TGas::TGas(const TGas &a) :
TObj(a)
{
type = a.type;
}
void TGas::setVolume(int n)
{
TObj::setVolume(n);
updateDesc();
if(roomp && roomp->isIndoorSector()){
obj_flags.decay_time=getVolume()/2;
} else {
obj_flags.decay_time=0;
}
}
void TGas::addToVolume(int n)
{
TObj::addToVolume(n);
updateDesc();
if(roomp && roomp->isIndoorSector()){
obj_flags.decay_time=getVolume()/2;
} else {
obj_flags.decay_time=0;
}
}
const char * TGas::getName() const
{
static const nameFunction names[GAS_MAX] = { getNameNothing, getNameSmoke, getNameMusk };
return names[getType()](this);
}
const char * TGas::getDesc() const
{
static const nameFunction descs[GAS_MAX] = { getDescNothing, getDescSmoke, getDescMusk };
return descs[getType()](this);
}
const char * TGas::getShortName() const
{
static const nameFunction shortnames[GAS_MAX] = { getShortNameNothing, getShortNameSmoke, getShortNameMusk };
return shortnames[getType()](this);
}
void TGas::updateDesc()
{
if (isObjStat(ITEM_STRUNG)) {
delete [] shortDescr;
delete [] descr;
extraDescription *exd;
while ((exd = ex_description)) {
ex_description = exd->next;
delete exd;
}
ex_description = NULL;
delete [] action_description;
action_description = NULL;
} else {
addObjStat(ITEM_STRUNG);
name = mud_str_dup(obj_index[getItemIndex()].name);
ex_description = NULL;
action_description = NULL;
}
shortDescr = mud_str_dup(getName());
setDescr(mud_str_dup(getDesc()));
}
bool TGas::isPluralItem() const
{
// a few drops of smoke
if (getType() == GAS_SMOKE && getSmokeIndex(getVolume()) == 0)
return true;
// otherwise, make recursive
return TObj::isPluralItem();
}
int TThing::dropGas(int amt, gasTypeT type)
{
TGas *gas = NULL;
if(amt == 0 || !roomp || type >= GAS_MAX)
return FALSE;
// look for preexisting smoke
for(StuffIter it= roomp->stuff.begin();it!= roomp->stuff.end();++it)
{
gas = dynamic_cast<TGas *>(*it);
if (gas && gas->getType() == type)
break;
gas = NULL;
}
// create new gas
if (!gas)
{
TObj *obj = NULL;
int robj = real_object(GENERIC_GAS);
if (robj < 0 || robj >= (signed int) obj_index.size())
{
vlogf(LOG_BUG, format("dropGas(): No object (%d) in database!") % robj);
return FALSE;
}
if (!(obj = read_object(robj, REAL)))
{
vlogf(LOG_LOW, format("Error, No gas object created (%d)") % robj);
return FALSE;
}
if (!(gas = dynamic_cast<TGas*>(obj)))
{
vlogf(LOG_LOW, "Error, Could not cast gas to TGas");
return FALSE;
}
gas->setType(type);
gas->swapToStrung();
REMOVE_BIT(gas->obj_flags.wear_flags, ITEM_TAKE);
gas->canBeSeen = 1;
gas->setMaterial(MAT_GHOSTLY);
gas->setObjStat(ITEM_NORENT);
delete [] gas->name;
gas->name = mud_str_dup(gas->getShortName());
*roomp += *gas;
}
if (!gas->hasCreator(name))
gas->addCreator(name);
gas->addToVolume(amt);
return TRUE;
}
void TGas::decayMe()
{
int volume = getVolume();
if (!roomp) {
vlogf(LOG_BUG, "TGas::decayMe() called while TGas not in room!");
setVolume(0);
return;
}
if (volume <= 0)
setVolume(0);
else if (volume < 25)
addToVolume((roomp->isIndoorSector() ? -5 : -8));
else // large smokes evaporate faster
addToVolume((roomp->isIndoorSector() ? -(volume/15) : -(volume/8)));
if (getVolume() < 0)
setVolume(0);
}
sstring TGas::statObjInfo() const
{
return "";
}
void TGas::getFourValues(int *x1, int *x2, int *x3, int *x4) const
{
*x1 = int(type);
*x2 = 0;
*x3 = 0;
*x4 = 0;
}
void TGas::assignFourValues(int t, int, int, int)
{
type = gasTypeT(t);
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <unordered_map>
#include <ctime>
int main(int argc, char* argv[])
{
if (argc != 5)
{
std::cerr << "Path Finder only accepts 4 arguments\n";
exit(1);
}
// Load in all page titles into a vector
std::cout << "\033[92m==>\033[0m Reading in page titles as a vector & map\n";
std::vector<std::string> pages;
std::unordered_map<std::string, int> page_ids;
{
std::clock_t start = std::clock();
std::ifstream page_titles_file(argv[1]);
std::string page_name;
// We won't be using the first index of the vector for anything since
// the page_id indexes start at 1 instead of 0. This should help to
// prevent any errors during devlopment
pages.push_back("");
// Read the page name into the vector and into the hash-map
int index = 1;
while (std::getline(page_titles_file, page_name))
{
pages.push_back(page_name);
page_ids[page_name] = index++;
}
std::cout << "\033[94m -> \033[0mRead in " << index - 1 << " page titles\n";
double duration = (std::clock() - start) / (double) CLOCKS_PER_SEC;
std::cout << "\033[94m -> \033[0mtook " << duration << " seconds\n";
}
// Load in all page links into a hash map
std::cout << "\033[92m==>\033[0m Reading in page links as a map\n";
std::unordered_map<int,std::vector<int>> page_links;
{
std::clock_t start = std::clock();
std::ifstream page_links_file(argv[2]);
std::string links;
while (std::getline(page_links_file, links))
{
int split_at = links.find(':');
int link_id = atoi(links.substr(0, split_at).c_str());
links = links.substr(split_at + 2);
std::stringstream stream_links(links);
int target_id;
while (stream_links >> target_id)
{
page_links[link_id].push_back(target_id);
}
}
double duration = (std::clock() - start) / (double) CLOCKS_PER_SEC;
std::cout << "\033[94m -> \033[0mtook " << duration << " seconds\n";
}
int page_id = page_ids[argv[3]];
std::cout << argv[3] << "(" << page_id << ") links to:\n";
for (int i : page_links[page_id])
{
std::cout << " * " << pages[i] << std::endl;
}
return 0;
}
<commit_msg>Slightly more efficient link map generation<commit_after>#include <stdio.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <unordered_map>
#include <ctime>
int main(int argc, char* argv[])
{
if (argc != 5)
{
std::cerr << "Path Finder only accepts 4 arguments\n";
exit(1);
}
// Load in all page titles into a vector
std::cout << "\033[92m==>\033[0m Reading in page titles as a vector & map\n";
std::vector<std::string> pages;
std::unordered_map<std::string, int> page_ids;
{
std::clock_t start = std::clock();
std::ifstream page_titles_file(argv[1]);
std::string page_name;
// We won't be using the first index of the vector for anything since
// the page_id indexes start at 1 instead of 0. This should help to
// prevent any errors during devlopment
pages.push_back("");
// Read the page name into the vector and into the hash-map
int index = 1;
while (std::getline(page_titles_file, page_name))
{
pages.push_back(page_name);
page_ids[page_name] = index++;
}
std::cout << "\033[94m -> \033[0mRead in " << index - 1 << " page titles\n";
double duration = (std::clock() - start) / (double) CLOCKS_PER_SEC;
std::cout << "\033[94m -> \033[0mtook " << duration << " seconds\n";
}
// Load in all page links into a hash map
std::cout << "\033[92m==>\033[0m Reading in page links as a map\n";
std::unordered_map<int,std::vector<int>> page_links;
{
std::clock_t start = std::clock();
std::ifstream page_links_file(argv[2]);
std::string link_id;
int current_link = 0;
while (page_links_file >> link_id)
{
if (link_id.back() == ':')
{
current_link = atoi(link_id.c_str());
}
else
{
page_links[current_link].push_back(atoi(link_id.c_str()));
}
}
double duration = (std::clock() - start) / (double) CLOCKS_PER_SEC;
std::cout << "\033[94m -> \033[0mtook " << duration << " seconds\n";
}
int page_id = page_ids[argv[3]];
std::cout << argv[3] << "(" << page_id << ") links to:\n";
for (int i : page_links[page_id])
{
std::cout << " * " << pages[i] << std::endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright (C) 2015 Felix Rohrbach <kde@fxrh.de>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "user.h"
#include "connection.h"
#include "room.h"
#include "avatar.h"
#include "events/event.h"
#include "events/roommemberevent.h"
#include "csapi/room_state.h"
#include "csapi/profile.h"
#include "csapi/content-repo.h"
#include <QtCore/QTimer>
#include <QtCore/QRegularExpression>
#include <QtCore/QPointer>
#include <QtCore/QStringBuilder>
#include <QtCore/QElapsedTimer>
#include <functional>
using namespace QMatrixClient;
using namespace std::placeholders;
using std::move;
class User::Private
{
public:
static Avatar makeAvatar(QUrl url)
{
return Avatar(move(url));
}
Private(QString userId, Connection* connection)
: userId(move(userId)), connection(connection)
{ }
QString userId;
Connection* connection;
QString bridged;
QString mostUsedName;
QMultiHash<QString, const Room*> otherNames;
Avatar mostUsedAvatar { makeAvatar({}) };
std::vector<Avatar> otherAvatars;
auto otherAvatar(QUrl url)
{
return std::find_if(otherAvatars.begin(), otherAvatars.end(),
[&url] (const auto& av) { return av.url() == url; });
}
QMultiHash<QUrl, const Room*> avatarsToRooms;
mutable int totalRooms = 0;
QString nameForRoom(const Room* r, const QString& hint = {}) const;
void setNameForRoom(const Room* r, QString newName, QString oldName);
QUrl avatarUrlForRoom(const Room* r, const QUrl& hint = {}) const;
void setAvatarForRoom(const Room* r, const QUrl& newUrl,
const QUrl& oldUrl);
void setAvatarOnServer(QString contentUri, User* q);
};
QString User::Private::nameForRoom(const Room* r, const QString& hint) const
{
// If the hint is accurate, this function is O(1) instead of O(n)
if (hint == mostUsedName || otherNames.contains(hint, r))
return hint;
return otherNames.key(r, mostUsedName);
}
static constexpr int MIN_JOINED_ROOMS_TO_LOG = 20;
void User::Private::setNameForRoom(const Room* r, QString newName,
QString oldName)
{
Q_ASSERT(oldName != newName);
Q_ASSERT(oldName == mostUsedName || otherNames.contains(oldName, r));
if (totalRooms < 2)
{
Q_ASSERT_X(totalRooms > 0 && otherNames.empty(), __FUNCTION__,
"Internal structures inconsistency");
mostUsedName = move(newName);
return;
}
otherNames.remove(oldName, r);
if (newName != mostUsedName)
{
// Check if the newName is about to become most used.
if (otherNames.count(newName) >= totalRooms - otherNames.size())
{
Q_ASSERT(totalRooms > 1);
QElapsedTimer et;
if (totalRooms > MIN_JOINED_ROOMS_TO_LOG)
{
qCDebug(MAIN) << "Switching the most used name of user" << userId
<< "from" << mostUsedName << "to" << newName;
qCDebug(MAIN) << "The user is in" << totalRooms << "rooms";
et.start();
}
for (auto* r1: connection->roomMap())
if (nameForRoom(r1) == mostUsedName)
otherNames.insert(mostUsedName, r1);
mostUsedName = newName;
otherNames.remove(newName);
if (totalRooms > MIN_JOINED_ROOMS_TO_LOG)
qCDebug(PROFILER) << et << "to switch the most used name";
}
else
otherNames.insert(newName, r);
}
}
QUrl User::Private::avatarUrlForRoom(const Room* r, const QUrl& hint) const
{
// If the hint is accurate, this function is O(1) instead of O(n)
if (hint == mostUsedAvatar.url() || avatarsToRooms.contains(hint, r))
return hint;
auto it = std::find(avatarsToRooms.begin(), avatarsToRooms.end(), r);
return it == avatarsToRooms.end() ? mostUsedAvatar.url() : it.key();
}
void User::Private::setAvatarForRoom(const Room* r, const QUrl& newUrl,
const QUrl& oldUrl)
{
Q_ASSERT(oldUrl != newUrl);
Q_ASSERT(oldUrl == mostUsedAvatar.url() ||
avatarsToRooms.contains(oldUrl, r));
if (totalRooms < 2)
{
Q_ASSERT_X(totalRooms > 0 && otherAvatars.empty(), __FUNCTION__,
"Internal structures inconsistency");
mostUsedAvatar.updateUrl(newUrl);
return;
}
avatarsToRooms.remove(oldUrl, r);
if (!avatarsToRooms.contains(oldUrl))
{
auto it = otherAvatar(oldUrl);
if (it != otherAvatars.end())
otherAvatars.erase(it);
}
if (newUrl != mostUsedAvatar.url())
{
// Check if the new avatar is about to become most used.
if (avatarsToRooms.count(newUrl) >= totalRooms - avatarsToRooms.size())
{
QElapsedTimer et;
if (totalRooms > MIN_JOINED_ROOMS_TO_LOG)
{
qCDebug(MAIN) << "Switching the most used avatar of user" << userId
<< "from" << mostUsedAvatar.url().toDisplayString()
<< "to" << newUrl.toDisplayString();
et.start();
}
avatarsToRooms.remove(newUrl);
auto nextMostUsedIt = otherAvatar(newUrl);
Q_ASSERT(nextMostUsedIt != otherAvatars.end());
std::swap(mostUsedAvatar, *nextMostUsedIt);
for (const auto* r1: connection->roomMap())
if (avatarUrlForRoom(r1) == nextMostUsedIt->url())
avatarsToRooms.insert(nextMostUsedIt->url(), r1);
if (totalRooms > MIN_JOINED_ROOMS_TO_LOG)
qCDebug(PROFILER) << et << "to switch the most used avatar";
} else {
if (otherAvatar(newUrl) == otherAvatars.end())
otherAvatars.emplace_back(makeAvatar(newUrl));
avatarsToRooms.insert(newUrl, r);
}
}
}
User::User(QString userId, Connection* connection)
: QObject(connection), d(new Private(move(userId), connection))
{
setObjectName(userId);
}
Connection* User::connection() const
{
Q_ASSERT(d->connection);
return d->connection;
}
User::~User() = default;
QString User::id() const
{
return d->userId;
}
bool User::isGuest() const
{
Q_ASSERT(!d->userId.isEmpty() && d->userId.startsWith('@'));
auto it = std::find_if_not(d->userId.begin() + 1, d->userId.end(),
[] (QChar c) { return c.isDigit(); });
Q_ASSERT(it != d->userId.end());
return *it == ':';
}
QString User::name(const Room* room) const
{
return d->nameForRoom(room);
}
QString User::rawName(const Room* room) const
{
return d->bridged.isEmpty() ? name(room) :
name(room) % " (" % d->bridged % ')';
}
void User::updateName(const QString& newName, const Room* room)
{
updateName(newName, d->nameForRoom(room), room);
}
void User::updateName(const QString& newName, const QString& oldName,
const Room* room)
{
Q_ASSERT(oldName == d->mostUsedName || d->otherNames.contains(oldName, room));
if (newName != oldName)
{
emit nameAboutToChange(newName, oldName, room);
d->setNameForRoom(room, newName, oldName);
setObjectName(displayname());
emit nameChanged(newName, oldName, room);
}
}
void User::updateAvatarUrl(const QUrl& newUrl, const QUrl& oldUrl,
const Room* room)
{
Q_ASSERT(oldUrl == d->mostUsedAvatar.url() ||
d->avatarsToRooms.contains(oldUrl, room));
if (newUrl != oldUrl)
{
d->setAvatarForRoom(room, newUrl, oldUrl);
setObjectName(displayname());
emit avatarChanged(this, room);
}
}
void User::rename(const QString& newName)
{
auto job = connection()->callApi<SetDisplayNameJob>(id(), newName);
connect(job, &BaseJob::success, this, [=] { updateName(newName); });
}
void User::rename(const QString& newName, const Room* r)
{
if (!r)
{
qCWarning(MAIN) << "Passing a null room to two-argument User::rename()"
"is incorrect; client developer, please fix it";
rename(newName);
return;
}
Q_ASSERT_X(r->memberJoinState(this) == JoinState::Join, __FUNCTION__,
"Attempt to rename a user that's not a room member");
MemberEventContent evtC;
evtC.displayName = newName;
auto job = r->setMemberState(id(), RoomMemberEvent(move(evtC)));
connect(job, &BaseJob::success, this, [=] { updateName(newName, r); });
}
bool User::setAvatar(const QString& fileName)
{
return avatarObject().upload(connection(), fileName,
std::bind(&Private::setAvatarOnServer, d.data(), _1, this));
}
bool User::setAvatar(QIODevice* source)
{
return avatarObject().upload(connection(), source,
std::bind(&Private::setAvatarOnServer, d.data(), _1, this));
}
void User::requestDirectChat()
{
connection()->requestDirectChat(this);
}
void User::ignore()
{
connection()->addToIgnoredUsers(this);
}
void User::unmarkIgnore()
{
connection()->removeFromIgnoredUsers(this);
}
bool User::isIgnored() const
{
return connection()->isIgnored(this);
}
void User::Private::setAvatarOnServer(QString contentUri, User* q)
{
auto* j = connection->callApi<SetAvatarUrlJob>(userId, contentUri);
connect(j, &BaseJob::success, q,
[=] { q->updateAvatarUrl(contentUri, avatarUrlForRoom(nullptr)); });
}
QString User::displayname(const Room* room) const
{
if (room)
return room->roomMembername(this);
const auto name = d->nameForRoom(nullptr);
return name.isEmpty() ? d->userId : name;
}
QString User::fullName(const Room* room) const
{
const auto name = d->nameForRoom(room);
return name.isEmpty() ? d->userId : name % " (" % d->userId % ')';
}
QString User::bridged() const
{
return d->bridged;
}
const Avatar& User::avatarObject(const Room* room) const
{
auto it = d->otherAvatar(d->avatarUrlForRoom(room));
return it != d->otherAvatars.end() ? *it : d->mostUsedAvatar;
}
QImage User::avatar(int dimension, const Room* room)
{
return avatar(dimension, dimension, room);
}
QImage User::avatar(int width, int height, const Room* room)
{
return avatar(width, height, room, []{});
}
QImage User::avatar(int width, int height, const Room* room,
const Avatar::get_callback_t& callback)
{
return avatarObject(room).get(d->connection, width, height,
[=] { emit avatarChanged(this, room); callback(); });
}
QString User::avatarMediaId(const Room* room) const
{
return avatarObject(room).mediaId();
}
QUrl User::avatarUrl(const Room* room) const
{
return avatarObject(room).url();
}
void User::processEvent(const RoomMemberEvent& event, const Room* room)
{
Q_ASSERT(room);
if (event.membership() != MembershipType::Invite &&
event.membership() != MembershipType::Join)
return;
auto aboutToEnter = room->memberJoinState(this) == JoinState::Leave &&
(event.membership() == MembershipType::Join ||
event.membership() == MembershipType::Invite);
if (aboutToEnter)
++d->totalRooms;
auto newName = event.displayName();
// `bridged` value uses the same notification signal as the name;
// it is assumed that first setting of the bridge occurs together with
// the first setting of the name, and further bridge updates are
// exceptionally rare (the only reasonable case being that the bridge
// changes the naming convention). For the same reason room-specific
// bridge tags are not supported at all.
QRegularExpression reSuffix(" \\((IRC|Gitter|Telegram)\\)$");
auto match = reSuffix.match(newName);
if (match.hasMatch())
{
if (d->bridged != match.captured(1))
{
if (!d->bridged.isEmpty())
qCWarning(MAIN) << "Bridge for user" << id() << "changed:"
<< d->bridged << "->" << match.captured(1);
d->bridged = match.captured(1);
}
newName.truncate(match.capturedStart(0));
}
if (event.prevContent())
{
// FIXME: the hint doesn't work for bridged users
auto oldNameHint =
d->nameForRoom(room, event.prevContent()->displayName);
updateName(newName, oldNameHint, room);
updateAvatarUrl(event.avatarUrl(),
d->avatarUrlForRoom(room, event.prevContent()->avatarUrl),
room);
} else {
updateName(newName, room);
updateAvatarUrl(event.avatarUrl(), d->avatarUrlForRoom(room), room);
}
}
<commit_msg>User: strip RLO/LRO markers on renaming as well<commit_after>/******************************************************************************
* Copyright (C) 2015 Felix Rohrbach <kde@fxrh.de>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "user.h"
#include "connection.h"
#include "room.h"
#include "avatar.h"
#include "events/event.h"
#include "events/roommemberevent.h"
#include "csapi/room_state.h"
#include "csapi/profile.h"
#include "csapi/content-repo.h"
#include <QtCore/QTimer>
#include <QtCore/QRegularExpression>
#include <QtCore/QPointer>
#include <QtCore/QStringBuilder>
#include <QtCore/QElapsedTimer>
#include <functional>
using namespace QMatrixClient;
using namespace std::placeholders;
using std::move;
class User::Private
{
public:
static Avatar makeAvatar(QUrl url)
{
return Avatar(move(url));
}
Private(QString userId, Connection* connection)
: userId(move(userId)), connection(connection)
{ }
QString userId;
Connection* connection;
QString bridged;
QString mostUsedName;
QMultiHash<QString, const Room*> otherNames;
Avatar mostUsedAvatar { makeAvatar({}) };
std::vector<Avatar> otherAvatars;
auto otherAvatar(QUrl url)
{
return std::find_if(otherAvatars.begin(), otherAvatars.end(),
[&url] (const auto& av) { return av.url() == url; });
}
QMultiHash<QUrl, const Room*> avatarsToRooms;
mutable int totalRooms = 0;
QString nameForRoom(const Room* r, const QString& hint = {}) const;
void setNameForRoom(const Room* r, QString newName, QString oldName);
QUrl avatarUrlForRoom(const Room* r, const QUrl& hint = {}) const;
void setAvatarForRoom(const Room* r, const QUrl& newUrl,
const QUrl& oldUrl);
void setAvatarOnServer(QString contentUri, User* q);
};
QString User::Private::nameForRoom(const Room* r, const QString& hint) const
{
// If the hint is accurate, this function is O(1) instead of O(n)
if (hint == mostUsedName || otherNames.contains(hint, r))
return hint;
return otherNames.key(r, mostUsedName);
}
static constexpr int MIN_JOINED_ROOMS_TO_LOG = 20;
void User::Private::setNameForRoom(const Room* r, QString newName,
QString oldName)
{
Q_ASSERT(oldName != newName);
Q_ASSERT(oldName == mostUsedName || otherNames.contains(oldName, r));
if (totalRooms < 2)
{
Q_ASSERT_X(totalRooms > 0 && otherNames.empty(), __FUNCTION__,
"Internal structures inconsistency");
mostUsedName = move(newName);
return;
}
otherNames.remove(oldName, r);
if (newName != mostUsedName)
{
// Check if the newName is about to become most used.
if (otherNames.count(newName) >= totalRooms - otherNames.size())
{
Q_ASSERT(totalRooms > 1);
QElapsedTimer et;
if (totalRooms > MIN_JOINED_ROOMS_TO_LOG)
{
qCDebug(MAIN) << "Switching the most used name of user" << userId
<< "from" << mostUsedName << "to" << newName;
qCDebug(MAIN) << "The user is in" << totalRooms << "rooms";
et.start();
}
for (auto* r1: connection->roomMap())
if (nameForRoom(r1) == mostUsedName)
otherNames.insert(mostUsedName, r1);
mostUsedName = newName;
otherNames.remove(newName);
if (totalRooms > MIN_JOINED_ROOMS_TO_LOG)
qCDebug(PROFILER) << et << "to switch the most used name";
}
else
otherNames.insert(newName, r);
}
}
QUrl User::Private::avatarUrlForRoom(const Room* r, const QUrl& hint) const
{
// If the hint is accurate, this function is O(1) instead of O(n)
if (hint == mostUsedAvatar.url() || avatarsToRooms.contains(hint, r))
return hint;
auto it = std::find(avatarsToRooms.begin(), avatarsToRooms.end(), r);
return it == avatarsToRooms.end() ? mostUsedAvatar.url() : it.key();
}
void User::Private::setAvatarForRoom(const Room* r, const QUrl& newUrl,
const QUrl& oldUrl)
{
Q_ASSERT(oldUrl != newUrl);
Q_ASSERT(oldUrl == mostUsedAvatar.url() ||
avatarsToRooms.contains(oldUrl, r));
if (totalRooms < 2)
{
Q_ASSERT_X(totalRooms > 0 && otherAvatars.empty(), __FUNCTION__,
"Internal structures inconsistency");
mostUsedAvatar.updateUrl(newUrl);
return;
}
avatarsToRooms.remove(oldUrl, r);
if (!avatarsToRooms.contains(oldUrl))
{
auto it = otherAvatar(oldUrl);
if (it != otherAvatars.end())
otherAvatars.erase(it);
}
if (newUrl != mostUsedAvatar.url())
{
// Check if the new avatar is about to become most used.
if (avatarsToRooms.count(newUrl) >= totalRooms - avatarsToRooms.size())
{
QElapsedTimer et;
if (totalRooms > MIN_JOINED_ROOMS_TO_LOG)
{
qCDebug(MAIN) << "Switching the most used avatar of user" << userId
<< "from" << mostUsedAvatar.url().toDisplayString()
<< "to" << newUrl.toDisplayString();
et.start();
}
avatarsToRooms.remove(newUrl);
auto nextMostUsedIt = otherAvatar(newUrl);
Q_ASSERT(nextMostUsedIt != otherAvatars.end());
std::swap(mostUsedAvatar, *nextMostUsedIt);
for (const auto* r1: connection->roomMap())
if (avatarUrlForRoom(r1) == nextMostUsedIt->url())
avatarsToRooms.insert(nextMostUsedIt->url(), r1);
if (totalRooms > MIN_JOINED_ROOMS_TO_LOG)
qCDebug(PROFILER) << et << "to switch the most used avatar";
} else {
if (otherAvatar(newUrl) == otherAvatars.end())
otherAvatars.emplace_back(makeAvatar(newUrl));
avatarsToRooms.insert(newUrl, r);
}
}
}
User::User(QString userId, Connection* connection)
: QObject(connection), d(new Private(move(userId), connection))
{
setObjectName(userId);
}
Connection* User::connection() const
{
Q_ASSERT(d->connection);
return d->connection;
}
User::~User() = default;
QString User::id() const
{
return d->userId;
}
bool User::isGuest() const
{
Q_ASSERT(!d->userId.isEmpty() && d->userId.startsWith('@'));
auto it = std::find_if_not(d->userId.begin() + 1, d->userId.end(),
[] (QChar c) { return c.isDigit(); });
Q_ASSERT(it != d->userId.end());
return *it == ':';
}
QString User::name(const Room* room) const
{
return d->nameForRoom(room);
}
QString User::rawName(const Room* room) const
{
return d->bridged.isEmpty() ? name(room) :
name(room) % " (" % d->bridged % ')';
}
void User::updateName(const QString& newName, const Room* room)
{
updateName(newName, d->nameForRoom(room), room);
}
void User::updateName(const QString& newName, const QString& oldName,
const Room* room)
{
Q_ASSERT(oldName == d->mostUsedName || d->otherNames.contains(oldName, room));
if (newName != oldName)
{
emit nameAboutToChange(newName, oldName, room);
d->setNameForRoom(room, newName, oldName);
setObjectName(displayname());
emit nameChanged(newName, oldName, room);
}
}
void User::updateAvatarUrl(const QUrl& newUrl, const QUrl& oldUrl,
const Room* room)
{
Q_ASSERT(oldUrl == d->mostUsedAvatar.url() ||
d->avatarsToRooms.contains(oldUrl, room));
if (newUrl != oldUrl)
{
d->setAvatarForRoom(room, newUrl, oldUrl);
setObjectName(displayname());
emit avatarChanged(this, room);
}
}
void User::rename(const QString& newName)
{
const auto actualNewName = sanitized(newName);
connect(connection()->callApi<SetDisplayNameJob>(id(), actualNewName),
&BaseJob::success, this, [=] { updateName(actualNewName); });
}
void User::rename(const QString& newName, const Room* r)
{
if (!r)
{
qCWarning(MAIN) << "Passing a null room to two-argument User::rename()"
"is incorrect; client developer, please fix it";
rename(newName);
return;
}
Q_ASSERT_X(r->memberJoinState(this) == JoinState::Join, __FUNCTION__,
"Attempt to rename a user that's not a room member");
const auto actualNewName = sanitized(newName);
MemberEventContent evtC;
evtC.displayName = actualNewName;
connect(r->setMemberState(id(), RoomMemberEvent(move(evtC))),
&BaseJob::success, this, [=] { updateName(actualNewName, r); });
}
bool User::setAvatar(const QString& fileName)
{
return avatarObject().upload(connection(), fileName,
std::bind(&Private::setAvatarOnServer, d.data(), _1, this));
}
bool User::setAvatar(QIODevice* source)
{
return avatarObject().upload(connection(), source,
std::bind(&Private::setAvatarOnServer, d.data(), _1, this));
}
void User::requestDirectChat()
{
connection()->requestDirectChat(this);
}
void User::ignore()
{
connection()->addToIgnoredUsers(this);
}
void User::unmarkIgnore()
{
connection()->removeFromIgnoredUsers(this);
}
bool User::isIgnored() const
{
return connection()->isIgnored(this);
}
void User::Private::setAvatarOnServer(QString contentUri, User* q)
{
auto* j = connection->callApi<SetAvatarUrlJob>(userId, contentUri);
connect(j, &BaseJob::success, q,
[=] { q->updateAvatarUrl(contentUri, avatarUrlForRoom(nullptr)); });
}
QString User::displayname(const Room* room) const
{
if (room)
return room->roomMembername(this);
const auto name = d->nameForRoom(nullptr);
return name.isEmpty() ? d->userId : name;
}
QString User::fullName(const Room* room) const
{
const auto name = d->nameForRoom(room);
return name.isEmpty() ? d->userId : name % " (" % d->userId % ')';
}
QString User::bridged() const
{
return d->bridged;
}
const Avatar& User::avatarObject(const Room* room) const
{
auto it = d->otherAvatar(d->avatarUrlForRoom(room));
return it != d->otherAvatars.end() ? *it : d->mostUsedAvatar;
}
QImage User::avatar(int dimension, const Room* room)
{
return avatar(dimension, dimension, room);
}
QImage User::avatar(int width, int height, const Room* room)
{
return avatar(width, height, room, []{});
}
QImage User::avatar(int width, int height, const Room* room,
const Avatar::get_callback_t& callback)
{
return avatarObject(room).get(d->connection, width, height,
[=] { emit avatarChanged(this, room); callback(); });
}
QString User::avatarMediaId(const Room* room) const
{
return avatarObject(room).mediaId();
}
QUrl User::avatarUrl(const Room* room) const
{
return avatarObject(room).url();
}
void User::processEvent(const RoomMemberEvent& event, const Room* room)
{
Q_ASSERT(room);
if (event.membership() != MembershipType::Invite &&
event.membership() != MembershipType::Join)
return;
auto aboutToEnter = room->memberJoinState(this) == JoinState::Leave &&
(event.membership() == MembershipType::Join ||
event.membership() == MembershipType::Invite);
if (aboutToEnter)
++d->totalRooms;
auto newName = event.displayName();
// `bridged` value uses the same notification signal as the name;
// it is assumed that first setting of the bridge occurs together with
// the first setting of the name, and further bridge updates are
// exceptionally rare (the only reasonable case being that the bridge
// changes the naming convention). For the same reason room-specific
// bridge tags are not supported at all.
QRegularExpression reSuffix(" \\((IRC|Gitter|Telegram)\\)$");
auto match = reSuffix.match(newName);
if (match.hasMatch())
{
if (d->bridged != match.captured(1))
{
if (!d->bridged.isEmpty())
qCWarning(MAIN) << "Bridge for user" << id() << "changed:"
<< d->bridged << "->" << match.captured(1);
d->bridged = match.captured(1);
}
newName.truncate(match.capturedStart(0));
}
if (event.prevContent())
{
// FIXME: the hint doesn't work for bridged users
auto oldNameHint =
d->nameForRoom(room, event.prevContent()->displayName);
updateName(newName, oldNameHint, room);
updateAvatarUrl(event.avatarUrl(),
d->avatarUrlForRoom(room, event.prevContent()->avatarUrl),
room);
} else {
updateName(newName, room);
updateAvatarUrl(event.avatarUrl(), d->avatarUrlForRoom(room), room);
}
}
<|endoftext|>
|
<commit_before>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://www.visualizationlibrary.org */
/* */
/* Copyright (c) 2005-2010, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#ifndef BufferObject_INCLUDE_ONCE
#define BufferObject_INCLUDE_ONCE
#include <vlCore/Vector2.hpp>
#include <vlCore/Vector3.hpp>
#include <vlCore/Vector4.hpp>
#include <vlCore/Buffer.hpp>
#include <vlGraphics/OpenGL.hpp>
#include <vlCore/vlnamespace.hpp>
#include <vlCore/Vector4.hpp>
#include <vlCore/Sphere.hpp>
#include <vlCore/AABB.hpp>
namespace vl
{
//-----------------------------------------------------------------------------
// BufferObject
//-----------------------------------------------------------------------------
/**
* The BufferObject class is a Buffer that can upload its data on the GPU memory.
* \remarks
* BufferObject is the storage used by ArrayAbstract and subclasses like ArrayFloat3, ArrayUByte4 etc.
*/
class BufferObject: public Buffer
{
VL_INSTRUMENT_CLASS(vl::BufferObject, Buffer)
public:
BufferObject()
{
VL_DEBUG_SET_OBJECT_NAME()
mHandle = 0;
mUsage = BU_STATIC_DRAW;
mByteCountBufferObject = 0;
}
BufferObject(const BufferObject& other): Buffer(other)
{
VL_DEBUG_SET_OBJECT_NAME()
mHandle = 0;
mUsage = BU_STATIC_DRAW;
mByteCountBufferObject = 0;
// copy local data
*this = other;
}
// deletes the BufferObject data and copyes only the local data
BufferObject& operator=(const BufferObject& other)
{
deleteBufferObject();
super::operator=(other);
return *this;
}
// swaps data with another BufferObject, including BufferObject handle, usage and local data.
void swap(BufferObject& other)
{
// swap local data
Buffer::swap(other);
// tmp
unsigned int tmp_handle = mHandle;
EBufferObjectUsage tmp_usage = mUsage;
GLsizeiptr tmp_bytes = mByteCountBufferObject;
// this <- other
mHandle = other.mHandle;
mUsage = tmp_usage;
mByteCountBufferObject = other.mByteCountBufferObject;
// other <- this
other.mHandle = tmp_handle;
other.mUsage = tmp_usage;
other.mByteCountBufferObject = tmp_bytes;
}
~BufferObject()
{
deleteBufferObject();
}
void setHandle(unsigned int handle) { mHandle = handle; }
unsigned int handle() const { return mHandle; }
GLsizeiptr byteCountBufferObject() const { return mByteCountBufferObject; }
void createBufferObject()
{
VL_CHECK_OGL();
VL_CHECK(Has_BufferObject)
if (Has_BufferObject && handle() == 0)
{
VL_CHECK(mByteCountBufferObject == 0)
VL_glGenBuffers( 1, &mHandle ); VL_CHECK_OGL();
mByteCountBufferObject = 0;
VL_CHECK(handle())
}
}
void deleteBufferObject()
{
// mic fixme: it would be nice to re-enable these
// VL_CHECK_OGL();
VL_CHECK(Has_BufferObject)
if (Has_BufferObject && handle() != 0)
{
VL_glDeleteBuffers( 1, &mHandle ); // VL_CHECK_OGL();
mHandle = 0;
mByteCountBufferObject = 0;
}
}
void downloadBufferObject()
{
VL_CHECK(Has_BufferObject)
if ( Has_BufferObject && handle() )
{
resize( byteCountBufferObject() );
void* vbo_ptr = mapBufferObject(BA_READ_ONLY);
memcpy( ptr(), vbo_ptr, byteCountBufferObject() );
unmapBufferObject();
}
}
// Modifies the BufferObject using data from the local storage.
// @note Discarding the local storage might delete data used by other Arrays.
void setBufferData( EBufferObjectUsage usage, bool discard_local_storage=false )
{
setBufferData( (int)bytesUsed(), ptr(), usage );
mUsage = usage;
if (discard_local_storage)
clear();
}
// Modifies the BufferObject using the supplied data.
// @note Use this function to initialize or resize the BufferObject and set it's usage flag.
// If data == NULL the buffer will be allocated but no data will be written to the BufferObject.
// If data != NULL such data will be copied into the BufferObject.
void setBufferData( GLsizeiptr byte_count, const GLvoid* data, EBufferObjectUsage usage )
{
VL_CHECK_OGL();
VL_CHECK(Has_BufferObject)
if ( Has_BufferObject )
{
createBufferObject();
// we use the GL_ARRAY_BUFFER slot to send the data for no special reason
VL_glBindBuffer( GL_ARRAY_BUFFER, handle() ); VL_CHECK_OGL();
VL_glBufferData( GL_ARRAY_BUFFER, byte_count, data, usage ); VL_CHECK_OGL();
VL_glBindBuffer( GL_ARRAY_BUFFER, 0 ); VL_CHECK_OGL();
mByteCountBufferObject = byte_count;
mUsage = usage;
}
}
// Modifies an existing BufferObject using data from the local storage.
// @note You can use this function only on already initialized BufferObjects, use setBufferData() to initialize a BufferObject.
// @note Discarding the local storage might delete data used by other Arrays.
void setBufferSubData( GLintptr offset=0, GLsizeiptr byte_count=-1, bool discard_local_storage=false )
{
byte_count = byte_count < 0 ? byteCountBufferObject() : byte_count;
setBufferSubData( offset, byte_count, ptr() );
if (discard_local_storage)
clear();
}
// Modifies an existing BufferObject using the supplied data.
// @note You can use this function only on already initialized BufferObjects, use setBufferData() to initialize a BufferObject.
// @param[in] data Must be != NULL, pointer to the data being written to the BufferObject.
void setBufferSubData( GLintptr offset, GLsizeiptr byte_count, const GLvoid* data )
{
VL_CHECK_OGL();
VL_CHECK(Has_BufferObject)
VL_CHECK(data);
VL_CHECK(handle())
if (Has_BufferObject && data && handle())
{
// we use the GL_ARRAY_BUFFER slot to send the data for no special reason
VL_glBindBuffer( GL_ARRAY_BUFFER, handle() ); VL_CHECK_OGL();
VL_glBufferSubData( GL_ARRAY_BUFFER, offset, byte_count, data ); VL_CHECK_OGL();
VL_glBindBuffer( GL_ARRAY_BUFFER, 0 ); VL_CHECK_OGL();
}
}
// Maps a BufferObject so that it can be read or written by the CPU.
// @note You can map only one BufferObject at a time and you must unmap it before using the BufferObject again or mapping another one.
void* mapBufferObject(EBufferObjectAccess access)
{
VL_CHECK_OGL();
VL_CHECK(Has_BufferObject)
if ( Has_BufferObject )
{
createBufferObject();
VL_glBindBuffer( GL_ARRAY_BUFFER, handle() ); VL_CHECK_OGL();
void* ptr = VL_glMapBuffer( GL_ARRAY_BUFFER, access ); VL_CHECK_OGL();
VL_glBindBuffer( GL_ARRAY_BUFFER, 0 ); VL_CHECK_OGL();
return ptr;
}
else
return NULL;
}
// Unmaps a previously mapped BufferObject.
// @return Returs true or false based on what's specified in the OpenGL specs:
// "UnmapBuffer returns TRUE unless data values in the buffers data store have
// become corrupted during the period that the buffer was mapped. Such corruption
// can be the result of a screen resolution change or other window system-dependent
// event that causes system heaps such as those for high-performance graphics memory
// to be discarded. GL implementations must guarantee that such corruption can
// occur only during the periods that a buffers data store is mapped. If such corruption
// has occurred, UnmapBuffer returns FALSE, and the contents of the buffers
// data store become undefined."
bool unmapBufferObject()
{
VL_CHECK_OGL();
VL_CHECK(Has_BufferObject)
if ( Has_BufferObject )
{
createBufferObject();
VL_glBindBuffer( GL_ARRAY_BUFFER, handle() ); VL_CHECK_OGL();
bool ok = VL_glUnmapBuffer( GL_ARRAY_BUFFER ) == GL_TRUE; VL_CHECK_OGL();
VL_glBindBuffer( GL_ARRAY_BUFFER, 0 ); VL_CHECK_OGL();
VL_CHECK_OGL();
return ok;
}
else
return false;
}
//! BufferObject usage flag as specified by setBufferData().
EBufferObjectUsage usage() const { return mUsage; }
protected:
unsigned int mHandle;
GLsizeiptr mByteCountBufferObject;
EBufferObjectUsage mUsage;
};
}
#endif
<commit_msg>fixed BufferObject destructor to be more loose when no GL context is present and no BufferObject was created.<commit_after>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://www.visualizationlibrary.org */
/* */
/* Copyright (c) 2005-2010, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#ifndef BufferObject_INCLUDE_ONCE
#define BufferObject_INCLUDE_ONCE
#include <vlCore/Vector2.hpp>
#include <vlCore/Vector3.hpp>
#include <vlCore/Vector4.hpp>
#include <vlCore/Buffer.hpp>
#include <vlGraphics/OpenGL.hpp>
#include <vlCore/vlnamespace.hpp>
#include <vlCore/Vector4.hpp>
#include <vlCore/Sphere.hpp>
#include <vlCore/AABB.hpp>
namespace vl
{
//-----------------------------------------------------------------------------
// BufferObject
//-----------------------------------------------------------------------------
/**
* The BufferObject class is a Buffer that can upload its data on the GPU memory.
* \remarks
* BufferObject is the storage used by ArrayAbstract and subclasses like ArrayFloat3, ArrayUByte4 etc.
*/
class BufferObject: public Buffer
{
VL_INSTRUMENT_CLASS(vl::BufferObject, Buffer)
public:
BufferObject()
{
VL_DEBUG_SET_OBJECT_NAME()
mHandle = 0;
mUsage = BU_STATIC_DRAW;
mByteCountBufferObject = 0;
}
BufferObject(const BufferObject& other): Buffer(other)
{
VL_DEBUG_SET_OBJECT_NAME()
mHandle = 0;
mUsage = BU_STATIC_DRAW;
mByteCountBufferObject = 0;
// copy local data
*this = other;
}
// deletes the BufferObject data and copyes only the local data
BufferObject& operator=(const BufferObject& other)
{
deleteBufferObject();
super::operator=(other);
return *this;
}
// swaps data with another BufferObject, including BufferObject handle, usage and local data.
void swap(BufferObject& other)
{
// swap local data
Buffer::swap(other);
// tmp
unsigned int tmp_handle = mHandle;
EBufferObjectUsage tmp_usage = mUsage;
GLsizeiptr tmp_bytes = mByteCountBufferObject;
// this <- other
mHandle = other.mHandle;
mUsage = tmp_usage;
mByteCountBufferObject = other.mByteCountBufferObject;
// other <- this
other.mHandle = tmp_handle;
other.mUsage = tmp_usage;
other.mByteCountBufferObject = tmp_bytes;
}
~BufferObject()
{
deleteBufferObject();
}
void setHandle(unsigned int handle) { mHandle = handle; }
unsigned int handle() const { return mHandle; }
GLsizeiptr byteCountBufferObject() const { return mByteCountBufferObject; }
void createBufferObject()
{
VL_CHECK_OGL();
VL_CHECK(Has_BufferObject)
if (Has_BufferObject && handle() == 0)
{
VL_CHECK(mByteCountBufferObject == 0)
VL_glGenBuffers( 1, &mHandle ); VL_CHECK_OGL();
mByteCountBufferObject = 0;
VL_CHECK(handle())
}
}
void deleteBufferObject()
{
// mic fixme: it would be nice to re-enable these
// VL_CHECK_OGL();
VL_CHECK(Has_BufferObject || handle() == 0)
if (Has_BufferObject && handle() != 0)
{
VL_glDeleteBuffers( 1, &mHandle ); // VL_CHECK_OGL();
mHandle = 0;
mByteCountBufferObject = 0;
}
}
void downloadBufferObject()
{
VL_CHECK(Has_BufferObject)
if ( Has_BufferObject && handle() )
{
resize( byteCountBufferObject() );
void* vbo_ptr = mapBufferObject(BA_READ_ONLY);
memcpy( ptr(), vbo_ptr, byteCountBufferObject() );
unmapBufferObject();
}
}
// Modifies the BufferObject using data from the local storage.
// @note Discarding the local storage might delete data used by other Arrays.
void setBufferData( EBufferObjectUsage usage, bool discard_local_storage=false )
{
setBufferData( (int)bytesUsed(), ptr(), usage );
mUsage = usage;
if (discard_local_storage)
clear();
}
// Modifies the BufferObject using the supplied data.
// @note Use this function to initialize or resize the BufferObject and set it's usage flag.
// If data == NULL the buffer will be allocated but no data will be written to the BufferObject.
// If data != NULL such data will be copied into the BufferObject.
void setBufferData( GLsizeiptr byte_count, const GLvoid* data, EBufferObjectUsage usage )
{
VL_CHECK_OGL();
VL_CHECK(Has_BufferObject)
if ( Has_BufferObject )
{
createBufferObject();
// we use the GL_ARRAY_BUFFER slot to send the data for no special reason
VL_glBindBuffer( GL_ARRAY_BUFFER, handle() ); VL_CHECK_OGL();
VL_glBufferData( GL_ARRAY_BUFFER, byte_count, data, usage ); VL_CHECK_OGL();
VL_glBindBuffer( GL_ARRAY_BUFFER, 0 ); VL_CHECK_OGL();
mByteCountBufferObject = byte_count;
mUsage = usage;
}
}
// Modifies an existing BufferObject using data from the local storage.
// @note You can use this function only on already initialized BufferObjects, use setBufferData() to initialize a BufferObject.
// @note Discarding the local storage might delete data used by other Arrays.
void setBufferSubData( GLintptr offset=0, GLsizeiptr byte_count=-1, bool discard_local_storage=false )
{
byte_count = byte_count < 0 ? byteCountBufferObject() : byte_count;
setBufferSubData( offset, byte_count, ptr() );
if (discard_local_storage)
clear();
}
// Modifies an existing BufferObject using the supplied data.
// @note You can use this function only on already initialized BufferObjects, use setBufferData() to initialize a BufferObject.
// @param[in] data Must be != NULL, pointer to the data being written to the BufferObject.
void setBufferSubData( GLintptr offset, GLsizeiptr byte_count, const GLvoid* data )
{
VL_CHECK_OGL();
VL_CHECK(Has_BufferObject)
VL_CHECK(data);
VL_CHECK(handle())
if (Has_BufferObject && data && handle())
{
// we use the GL_ARRAY_BUFFER slot to send the data for no special reason
VL_glBindBuffer( GL_ARRAY_BUFFER, handle() ); VL_CHECK_OGL();
VL_glBufferSubData( GL_ARRAY_BUFFER, offset, byte_count, data ); VL_CHECK_OGL();
VL_glBindBuffer( GL_ARRAY_BUFFER, 0 ); VL_CHECK_OGL();
}
}
// Maps a BufferObject so that it can be read or written by the CPU.
// @note You can map only one BufferObject at a time and you must unmap it before using the BufferObject again or mapping another one.
void* mapBufferObject(EBufferObjectAccess access)
{
VL_CHECK_OGL();
VL_CHECK(Has_BufferObject)
if ( Has_BufferObject )
{
createBufferObject();
VL_glBindBuffer( GL_ARRAY_BUFFER, handle() ); VL_CHECK_OGL();
void* ptr = VL_glMapBuffer( GL_ARRAY_BUFFER, access ); VL_CHECK_OGL();
VL_glBindBuffer( GL_ARRAY_BUFFER, 0 ); VL_CHECK_OGL();
return ptr;
}
else
return NULL;
}
// Unmaps a previously mapped BufferObject.
// @return Returs true or false based on what's specified in the OpenGL specs:
// "UnmapBuffer returns TRUE unless data values in the buffers data store have
// become corrupted during the period that the buffer was mapped. Such corruption
// can be the result of a screen resolution change or other window system-dependent
// event that causes system heaps such as those for high-performance graphics memory
// to be discarded. GL implementations must guarantee that such corruption can
// occur only during the periods that a buffers data store is mapped. If such corruption
// has occurred, UnmapBuffer returns FALSE, and the contents of the buffers
// data store become undefined."
bool unmapBufferObject()
{
VL_CHECK_OGL();
VL_CHECK(Has_BufferObject)
if ( Has_BufferObject )
{
createBufferObject();
VL_glBindBuffer( GL_ARRAY_BUFFER, handle() ); VL_CHECK_OGL();
bool ok = VL_glUnmapBuffer( GL_ARRAY_BUFFER ) == GL_TRUE; VL_CHECK_OGL();
VL_glBindBuffer( GL_ARRAY_BUFFER, 0 ); VL_CHECK_OGL();
VL_CHECK_OGL();
return ok;
}
else
return false;
}
//! BufferObject usage flag as specified by setBufferData().
EBufferObjectUsage usage() const { return mUsage; }
protected:
unsigned int mHandle;
GLsizeiptr mByteCountBufferObject;
EBufferObjectUsage mUsage;
};
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <boost/asio.hpp>
#include <windows.h>
#include <boost/program_options.hpp>
#include <base/logging.h>
#include <base/contrail_ports.h>
#include <pugixml/pugixml.hpp>
#include <base/task.h>
#include <io/event_manager.h>
#include <sandesh/common/vns_types.h>
#include <sandesh/common/vns_constants.h>
#include <base/misc_utils.h>
#include <cmn/buildinfo.h>
#include <cmn/agent_cmn.h>
#include <cfg/cfg_init.h>
#include <cfg/cfg_mirror.h>
#include <cfg/discovery_agent.h>
#include <init/agent_param.h>
#include <oper/operdb_init.h>
#include <oper/vrf.h>
#include <oper/multicast.h>
#include <oper/mirror_table.h>
#include <controller/controller_init.h>
#include <controller/controller_vrf_export.h>
#include <pkt/pkt_init.h>
#include <services/services_init.h>
#include <vrouter/ksync/ksync_init.h>
#include <openstack/instance_service_server.h>
#include <uve/agent_uve.h>
#include <kstate/kstate.h>
#include <pkt/proto.h>
#include <diag/diag.h>
#include <boost/functional/factory.hpp>
#include <cmn/agent_factory.h>
#include "contrail_agent_init.h"
namespace opt = boost::program_options;
void RouterIdDepInit(Agent *agent) {
InstanceInfoServiceServerInit(agent);
// Parse config and then connect
Agent::GetInstance()->controller()->Connect();
LOG(DEBUG, "Router ID Dependent modules (Nova and BGP) INITIALIZED");
}
bool GetBuildInfo(std::string &build_info_str) {
return MiscUtils::GetBuildInfo(MiscUtils::Agent, BuildInfo, build_info_str);
}
int main(int argc, char *argv[]) {
AgentParam params;
try {
params.ParseArguments(argc, argv);
} catch (...) {
cout << "Invalid arguments. ";
cout << params.options() << endl;
exit(0);
}
opt::variables_map var_map = params.var_map();
if (var_map.count("help")) {
cout << params.options() << endl;
exit(0);
}
if (var_map.count("version")) {
string build_info;
MiscUtils::GetBuildInfo(MiscUtils::Agent, BuildInfo, build_info);
cout << params.options() << endl;
exit(0);
}
string init_file = "";
if (var_map.count("config_file")) {
init_file = var_map["config_file"].as<string>();
struct stat s;
if (stat(init_file.c_str(), &s) != 0) {
LOG(ERROR, "Error opening config file <" << init_file
<< ">. Error number <" << errno << ">");
exit(EINVAL);
}
}
// Read agent parameters from config file and arguments
params.Init(init_file, argv[0]);
// Initialize TBB
// Call to GetScheduler::GetInstance() will also create Task Scheduler
TaskScheduler::Initialize(params.tbb_thread_count());
// Initialize the agent-init control class
ContrailAgentInit init;
string build_info;
GetBuildInfo(build_info);
MiscUtils::LogVersionInfo(build_info, Category::VROUTER);
init.set_agent_param(¶ms);
// kick start initialization
int ret = 0;
if ((ret = init.Start()) != 0) {
return ret;
}
Agent *agent = init.agent();
agent->event_manager()->Run();
return 0;
}
<commit_msg>JW-810 fixed: report error when opening config file fails<commit_after>/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <boost/asio.hpp>
#include <windows.h>
#include <boost/program_options.hpp>
#include <base/logging.h>
#include <base/contrail_ports.h>
#include <pugixml/pugixml.hpp>
#include <base/task.h>
#include <io/event_manager.h>
#include <sandesh/common/vns_types.h>
#include <sandesh/common/vns_constants.h>
#include <base/misc_utils.h>
#include <cmn/buildinfo.h>
#include <cmn/agent_cmn.h>
#include <cfg/cfg_init.h>
#include <cfg/cfg_mirror.h>
#include <cfg/discovery_agent.h>
#include <init/agent_param.h>
#include <oper/operdb_init.h>
#include <oper/vrf.h>
#include <oper/multicast.h>
#include <oper/mirror_table.h>
#include <controller/controller_init.h>
#include <controller/controller_vrf_export.h>
#include <pkt/pkt_init.h>
#include <services/services_init.h>
#include <vrouter/ksync/ksync_init.h>
#include <openstack/instance_service_server.h>
#include <uve/agent_uve.h>
#include <kstate/kstate.h>
#include <pkt/proto.h>
#include <diag/diag.h>
#include <boost/functional/factory.hpp>
#include <cmn/agent_factory.h>
#include "contrail_agent_init.h"
namespace opt = boost::program_options;
void RouterIdDepInit(Agent *agent) {
InstanceInfoServiceServerInit(agent);
// Parse config and then connect
Agent::GetInstance()->controller()->Connect();
LOG(DEBUG, "Router ID Dependent modules (Nova and BGP) INITIALIZED");
}
bool GetBuildInfo(std::string &build_info_str) {
return MiscUtils::GetBuildInfo(MiscUtils::Agent, BuildInfo, build_info_str);
}
int main(int argc, char *argv[]) {
AgentParam params;
try {
params.ParseArguments(argc, argv);
} catch (...) {
cout << "Invalid arguments. ";
cout << params.options() << endl;
exit(0);
}
opt::variables_map var_map = params.var_map();
if (var_map.count("help")) {
cout << params.options() << endl;
exit(0);
}
if (var_map.count("version")) {
string build_info;
MiscUtils::GetBuildInfo(MiscUtils::Agent, BuildInfo, build_info);
cout << params.options() << endl;
exit(0);
}
string init_file = "";
if (var_map.count("config_file")) {
init_file = var_map["config_file"].as<string>();
struct stat s;
if (stat(init_file.c_str(), &s) != 0) {
cout << "Error opening config file <" << init_file
<< ">. Error number <" << errno << ">";
exit(EINVAL);
}
}
// Read agent parameters from config file and arguments
params.Init(init_file, argv[0]);
// Initialize TBB
// Call to GetScheduler::GetInstance() will also create Task Scheduler
TaskScheduler::Initialize(params.tbb_thread_count());
// Initialize the agent-init control class
ContrailAgentInit init;
string build_info;
GetBuildInfo(build_info);
MiscUtils::LogVersionInfo(build_info, Category::VROUTER);
init.set_agent_param(¶ms);
// kick start initialization
int ret = 0;
if ((ret = init.Start()) != 0) {
return ret;
}
Agent *agent = init.agent();
agent->event_manager()->Run();
return 0;
}
<|endoftext|>
|
<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <vw/Camera/LensDistortion.h>
#include <vw/Camera/PinholeModel.h>
#include <vw/Math/LevenbergMarquardt.h>
using namespace vw;
// Special LMA Models to figure out foward and backward ---------
// Optimization functor for computing the undistorted coordinates
// using levenberg marquardt.
struct UndistortOptimizeFunctor : public math::LeastSquaresModelBase<UndistortOptimizeFunctor> {
typedef Vector2 result_type;
typedef Vector2 domain_type;
typedef Matrix<double> jacobian_type;
const camera::PinholeModel& m_cam;
const camera::LensDistortion &m_distort;
UndistortOptimizeFunctor(const camera::PinholeModel& cam, const camera::LensDistortion& d) : m_cam(cam), m_distort(d) {}
inline result_type operator()( domain_type const& x ) const {
return m_distort.distorted_coordinates(m_cam, x);
}
};
struct DistortOptimizeFunctor : public math::LeastSquaresModelBase<DistortOptimizeFunctor> {
typedef Vector2 result_type;
typedef Vector2 domain_type;
typedef Matrix<double> jacobian_type;
const camera::PinholeModel& m_cam;
const camera::LensDistortion &m_distort;
DistortOptimizeFunctor(const camera::PinholeModel& cam, const camera::LensDistortion& d) : m_cam(cam), m_distort(d) {}
inline result_type operator()( domain_type const& x ) const {
Vector2 result = m_distort.undistorted_coordinates(m_cam, x);
return result;
}
};
// Backup implemenations for Lens Distortion -------------------
Vector2
vw::camera::LensDistortion::undistorted_coordinates(const camera::PinholeModel& cam, Vector2 const& v) const {
UndistortOptimizeFunctor model(cam, *this);
int status;
Vector2 solution =
math::levenberg_marquardt( model, v, v, status, 1e-6, 1e-6 );
VW_DEBUG_ASSERT( status != math::optimization::eConvergedRelTolerance, PixelToRayErr() << "undistorted_coordinates: failed to converge." );
return solution;
}
vw::Vector2
vw::camera::LensDistortion::distorted_coordinates(const camera::PinholeModel& cam, Vector2 const& v) const {
DistortOptimizeFunctor model(cam, *this);
int status;
Vector2 solution =
math::levenberg_marquardt( model, v, v, status, 1e-6, 1e-6 );
VW_DEBUG_ASSERT( status != math::optimization::eConvergedRelTolerance, PixelToRayErr() << "distorted_coordinates: failed to converge." );
return solution;
}
// Specific Implementations -------------------------------------
Vector2
vw::camera::TsaiLensDistortion::distorted_coordinates(const camera::PinholeModel& cam, Vector2 const& p) const {
Vector2 focal = cam.focal_length();
Vector2 offset = cam.point_offset();
if (focal[0] < 1e-300 || focal[1] < 1e-300)
return Vector2(HUGE_VAL, HUGE_VAL);
Vector2 p_0 = elem_quot(p - offset, focal); // represents x and y
double r2 = norm_2_sqr( p_0 );
Vector2 distortion( m_distortion[3], m_distortion[2] );
Vector2 p_1 = elem_quot(distortion, p_0);
Vector2 p_3 = 2*elem_prod(distortion,p_0);
Vector2 b = elem_prod(r2,p_1);
b = elem_sum(b,r2*(m_distortion[0] + r2 * m_distortion[1]) + sum(p_3));
// Prevent divide by zero at the origin or along the x and y center line
Vector2 result = p + elem_prod(b,p - offset);
if (p[0] == offset[0])
result[0] = p[0];
if (p[1] == offset[1])
result[1] = p[1];
return result;
}
Vector2
vw::camera::BrownConradyDistortion::undistorted_coordinates(const camera::PinholeModel& cam, Vector2 const& p) const {
Vector2 offset = cam.point_offset();
Vector2 intermediate = p - m_principal_point - offset;
double r2 = norm_2_sqr(intermediate);
double radial = 1 + m_radial_distortion[0]*r2 +
m_radial_distortion[1]*r2*r2 + m_radial_distortion[2]*r2*r2*r2;
double tangental = m_centering_distortion[0]*r2 + m_centering_distortion[1]*r2*r2;
intermediate *= radial;
intermediate[0] -= tangental*sin(m_centering_angle);
intermediate[1] += tangental*cos(m_centering_angle);
return intermediate+offset;
}
std::ostream& vw::camera::operator<<(std::ostream & os,
const camera::LensDistortion& ld) {
ld.write(os);
return os;
}
<commit_msg>Limit Lens Distortion solve to 50 iterations<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <vw/Camera/LensDistortion.h>
#include <vw/Camera/PinholeModel.h>
#include <vw/Math/LevenbergMarquardt.h>
using namespace vw;
// Special LMA Models to figure out foward and backward ---------
// Optimization functor for computing the undistorted coordinates
// using levenberg marquardt.
struct UndistortOptimizeFunctor : public math::LeastSquaresModelBase<UndistortOptimizeFunctor> {
typedef Vector2 result_type;
typedef Vector2 domain_type;
typedef Matrix<double> jacobian_type;
const camera::PinholeModel& m_cam;
const camera::LensDistortion &m_distort;
UndistortOptimizeFunctor(const camera::PinholeModel& cam, const camera::LensDistortion& d) : m_cam(cam), m_distort(d) {}
inline result_type operator()( domain_type const& x ) const {
return m_distort.distorted_coordinates(m_cam, x);
}
};
struct DistortOptimizeFunctor : public math::LeastSquaresModelBase<DistortOptimizeFunctor> {
typedef Vector2 result_type;
typedef Vector2 domain_type;
typedef Matrix<double> jacobian_type;
const camera::PinholeModel& m_cam;
const camera::LensDistortion &m_distort;
DistortOptimizeFunctor(const camera::PinholeModel& cam, const camera::LensDistortion& d) : m_cam(cam), m_distort(d) {}
inline result_type operator()( domain_type const& x ) const {
return m_distort.undistorted_coordinates(m_cam, x);
}
};
// Backup implemenations for Lens Distortion -------------------
Vector2
vw::camera::LensDistortion::undistorted_coordinates(const camera::PinholeModel& cam, Vector2 const& v) const {
UndistortOptimizeFunctor model(cam, *this);
int status;
Vector2 solution =
math::levenberg_marquardt( model, v, v, status, 1e-6, 1e-6, 50 );
VW_DEBUG_ASSERT( status != math::optimization::eConvergedRelTolerance, PixelToRayErr() << "undistorted_coordinates: failed to converge." );
return solution;
}
vw::Vector2
vw::camera::LensDistortion::distorted_coordinates(const camera::PinholeModel& cam, Vector2 const& v) const {
DistortOptimizeFunctor model(cam, *this);
int status;
Vector2 solution =
math::levenberg_marquardt( model, v, v, status, 1e-6, 1e-6, 50 );
VW_DEBUG_ASSERT( status != math::optimization::eConvergedRelTolerance, PixelToRayErr() << "distorted_coordinates: failed to converge." );
return solution;
}
// Specific Implementations -------------------------------------
Vector2
vw::camera::TsaiLensDistortion::distorted_coordinates(const camera::PinholeModel& cam, Vector2 const& p) const {
Vector2 focal = cam.focal_length();
Vector2 offset = cam.point_offset();
if (focal[0] < 1e-300 || focal[1] < 1e-300)
return Vector2(HUGE_VAL, HUGE_VAL);
Vector2 p_0 = elem_quot(p - offset, focal); // represents x and y
double r2 = norm_2_sqr( p_0 );
Vector2 distortion( m_distortion[3], m_distortion[2] );
Vector2 p_1 = elem_quot(distortion, p_0);
Vector2 p_3 = 2*elem_prod(distortion,p_0);
Vector2 b = elem_prod(r2,p_1);
b = elem_sum(b,r2*(m_distortion[0] + r2 * m_distortion[1]) + sum(p_3));
// Prevent divide by zero at the origin or along the x and y center line
Vector2 result = p + elem_prod(b,p - offset);
if (p[0] == offset[0])
result[0] = p[0];
if (p[1] == offset[1])
result[1] = p[1];
return result;
}
Vector2
vw::camera::BrownConradyDistortion::undistorted_coordinates(const camera::PinholeModel& cam, Vector2 const& p) const {
Vector2 offset = cam.point_offset();
Vector2 intermediate = p - m_principal_point - offset;
double r2 = norm_2_sqr(intermediate);
double radial = 1 + m_radial_distortion[0]*r2 +
m_radial_distortion[1]*r2*r2 + m_radial_distortion[2]*r2*r2*r2;
double tangental = m_centering_distortion[0]*r2 + m_centering_distortion[1]*r2*r2;
intermediate *= radial;
intermediate[0] -= tangental*sin(m_centering_angle);
intermediate[1] += tangental*cos(m_centering_angle);
return intermediate+offset;
}
std::ostream& vw::camera::operator<<(std::ostream & os,
const camera::LensDistortion& ld) {
ld.write(os);
return os;
}
<|endoftext|>
|
<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <vw/Plate/SnapshotManager.h>
#include <vw/Plate/TileManipulation.h>
#include <vw/Mosaic/ImageComposite.h>
#include <vw/Image/ImageView.h>
#include <set>
namespace vw {
namespace platefile {
bool is_leaf(boost::shared_ptr<PlateFile> platefile, TileHeader const& tile_header) {
int current_col = tile_header.col();
int current_row = tile_header.row();
for (int new_row = current_row*2; new_row < current_row*2+2; ++new_row) {
for (int new_col = current_col*2; new_col < current_col*2+2; ++new_col) {
try {
std::list<TileHeader> tile_records;
tile_records = platefile->search_by_location(new_col, new_row,
tile_header.level() + 1,
tile_header.transaction_id(),
tile_header.transaction_id(),
false); // fetch_one_additional_entry
// If this node has child tiles, then it is not a leaf node.
if (tile_records.size() > 0)
return false;
} catch (TileNotFoundErr &e) { /* do nothing */ }
}
}
// If not child tiles were found, then this is a leaf node.
return true;
}
template <class PixelT>
int vw::platefile::SnapshotManager<PixelT>::snapshot_helper(int current_col,
int current_row,
int current_level,
std::map<int32, TileHeader> composite_tiles,
vw::BBox2i const& target_region,
int target_level,
int start_transaction_id,
int end_transaction_id,
int write_transaction_id) const {
// Check to see if there are any tiles at this level that need to be
// snapshotted. We fetch one additional tile outside of the
// specified range so that we get any tiles that were not actually
// composited during the last snapshot.
std::list<TileHeader> tile_records;
try {
tile_records = m_platefile->search_by_location(current_col, current_row, current_level,
start_transaction_id, end_transaction_id,
true); // fetch_one_additional_entry
} catch (TileNotFoundErr &e) { /* do nothing */ }
// If there are no valid tiles at this level, then there is nothing
// further for us to do here on this branch of the recursion. We
// return immediately.
if (tile_records.size() == 0)
return 0;
// Insert the TileHeaders for this level into the composite_tiles
// map<>. Elements will be inserted in order, and any duplicate
// transaction_ids will be overwritten by new tile records. In
// this fashion, we build up a list of the highest resolution
// valid tiles in order of transaction id.
for (std::list<TileHeader>::iterator iter = tile_records.begin();
iter != tile_records.end(); ++iter) {
if (current_level == target_level || is_leaf(m_platefile, *iter) ) {
// We always add any valid tiles at the target_level, since
// they should always be included in the composite.
//
// When adding tiles that may need to be supersampled, we are
// only interested in leaf nodes. All others will have higher
// resolution tiles available as their children that we should
// use instead.
composite_tiles[iter->transaction_id()] = *iter;
}
}
// If we have reached the target level, then we use the
// accumulated tiles to generate a snapshot for this tile.
if (current_level == target_level) {
// Check to see if the second entry is the start_transaction_id.
// If this is the case, then we can safely skip the first tile
// (which is then assumed to be the "additional_entry" that
// falls earlier than the given transaction range) since it
// will have already been incorporated into the previous
// snapshot.
if (composite_tiles.size() >= 2) {
std::map<int32, TileHeader>::iterator lowest_tid_iter = composite_tiles.begin();
std::map<int32, TileHeader>::iterator second_tid_iter = lowest_tid_iter;
++second_tid_iter;
if (int(second_tid_iter->first) == start_transaction_id) {
composite_tiles.erase(lowest_tid_iter);
}
}
// If we arrive at the target level and find that we have fewer
// than two tiles to composite, then there's no actual
// compositing that needs to be done. We can safely bail on
// this tile.
if (composite_tiles.size() < 2)
return 0;
// Create a tile into which we will accumulate composited data.
ImageView<PixelT> composite_tile(m_platefile->default_tile_size(),
m_platefile->default_tile_size());
int num_composited = 0;
for (std::map<int32, TileHeader>::reverse_iterator iter = composite_tiles.rbegin();
iter != composite_tiles.rend(); ++iter) {
TileHeader ¤t_hdr = iter->second;
// std::cout << "\t--> [ " << current_hdr.transaction_id() << " ] "
// << current_hdr.col() << " " << current_hdr.row()
// << " @ " << current_hdr.level() << "\n";
// Tile access is highly localized during snapshotting, so it
// speeds things up considerably to cache them here.
ImageView<PixelT> new_tile;
if ( !(this->restore_tile(new_tile, current_hdr.col(), current_hdr.row(),
current_hdr.level(), current_hdr.transaction_id())) ) {
try {
// If the tile isn't in our cache, then we take the
// performance hit and read the tile from the platefile.
m_platefile->read(new_tile,
current_hdr.col(), current_hdr.row(),
current_hdr.level(), current_hdr.transaction_id(),
true); // exact_transaction_match
this->save_tile(new_tile, current_hdr.col(), current_hdr.row(),
current_hdr.level(), current_hdr.transaction_id());
} catch (BlobIoErr &e) {
// If we get a BlobIO error, that's bad news, but not worth
// killing the snapshot for. Instead we log the error here and move
// onto the next location.
std::ostringstream ostr;
ostr << "WARNING: error reading tile from blob: " << e.what();
m_platefile->log(ostr.str());
continue;
}
}
// If this is the first tile in this location, it's already at
// the target_level, and it's opaque (which is a very common
// case), then we don't need to save it as part of the
// snapshot since its already the top tile in the snapshot.
// This optimization saves us both space and time!
if ( current_hdr.level() == target_level &&
iter == composite_tiles.rbegin() &&
is_opaque(new_tile) ) {
return 0;
}
// If we are compositing a tile from a lower resolution in the
// pyramid, it needs to be supersampled and cropped before we
// can use it here.
if (current_hdr.level() != target_level) {
new_tile = resample_img_from_level(
new_tile, current_hdr.col(), current_hdr.row(), current_hdr.level(),
current_col, current_row, target_level);
}
// Add the new tile UNDERNEATH the tiles we have already composited.
vw::mosaic::ImageComposite<PixelT> composite;
composite.insert(new_tile, 0, 0);
composite.insert(composite_tile, 0, 0);
composite.set_draft_mode( true );
composite.prepare();
// Overwrite the composite_tile
composite_tile = composite;
++num_composited;
// Check to see if the composite tile is opaque. If it is,
// then there's no point in compositing any more tiles because
// they will end up hidden anyway.
if ( is_opaque(composite_tile) ) {
break;
}
}
if (num_composited > 0) {
// -- debug
vw_out(DebugMessage, "plate::snapshot") << "\t Compositing " << current_col << " "
<< current_row << " @ " << current_level
<< " [ " << num_composited << " ]\n";
//---
// for (unsigned j = 0; j < composite_tile.rows(); ++j) {
// for (unsigned i = 0; i < composite_tile.cols(); ++i) {
// composite_tile(i,j)[0] *= -1;
// }
// }
m_platefile->write_update(composite_tile,
current_col, current_row, current_level,
write_transaction_id);
return 1;
} else {
return 0;
}
} else {
// If we haven't reached the target level, then are four
// possible children that we can explore for more snapshotting
// information.
int num_tiles_updated = 0;
for (int new_row = current_row*2; new_row < current_row*2+2; ++new_row) {
for (int new_col = current_col*2; new_col < current_col*2+2; ++new_col) {
// We should only explore those child tiles that overlap
// with the target_region at the target level. To test
// this, we create a bounding box for the child tile we are
// testing, and scale that bounding box up to see how big it
// is when projected into the target_level of the pyramid.
BBox2i parent_region(new_col, new_row, 1, 1);
parent_region.min() *= pow(2,target_level-(current_level+1));
parent_region.max() *= pow(2,target_level-(current_level+1));
// With the scaled up parent region and the target region in
// hand, we can do a simple intersection test to assess
// whether this child tile is worth exploring.
if (parent_region.intersects(target_region)) {
num_tiles_updated += snapshot_helper(new_col, new_row, current_level+1,
composite_tiles, target_region, target_level,
start_transaction_id, end_transaction_id,
write_transaction_id);
}
}
}
return num_tiles_updated;
}
}
}} // namespace vw::platefile
template <class PixelT>
void vw::platefile::SnapshotManager<PixelT>::snapshot(int level, BBox2i const& tile_region,
int start_transaction_id,
int end_transaction_id,
int write_transaction_id) const {
// Subdivide the bbox into smaller workunits if necessary.
// This helps to keep operations efficient.
std::list<BBox2i> tile_workunits = bbox_tiles(tile_region, 1024, 1024);
for ( std::list<BBox2i>::iterator region_iter = tile_workunits.begin();
region_iter != tile_workunits.end(); ++region_iter) {
// Create an empty list of composite tiles and then kick off the
// recursive snapshotting process.
std::map<int32, TileHeader> composite_tiles;
int num_tiles_updated = snapshot_helper(0, 0, 0, composite_tiles, *region_iter, level,
start_transaction_id, end_transaction_id,
write_transaction_id);
if (num_tiles_updated > 0)
vw_out() << "\t--> Snapshot " << *region_iter << " @ level " << level
<< " (" << num_tiles_updated << " tiles updated).\n";
}
}
// Create a full snapshot of every level and every region in the mosaic.
template <class PixelT>
void vw::platefile::SnapshotManager<PixelT>::full_snapshot(int start_transaction_id,
int end_transaction_id,
int write_transaction_id) const {
for (int level = 0; level < m_platefile->num_levels(); ++level) {
// For debugging:
// for (int level = 11; level < 12; ++level) {
// Snapshot the entire region at each level. These region will be
// broken down into smaller work units in snapshot().
int region_size = pow(2,level);
int subdivided_region_size = region_size / 16;
if (subdivided_region_size < 1024) subdivided_region_size = 1024;
BBox2i full_region(0,0,region_size,region_size);
std::list<BBox2i> workunits = bbox_tiles(full_region,
subdivided_region_size,
subdivided_region_size);
for ( std::list<BBox2i>::iterator region_iter = workunits.begin();
region_iter != workunits.end(); ++region_iter) {
snapshot(level, *region_iter, start_transaction_id,
end_transaction_id, write_transaction_id);
}
}
}
// Explicit template instatiation
namespace vw {
namespace platefile {
template
void vw::platefile::SnapshotManager<PixelGrayA<uint8> >::snapshot(int level,
BBox2i const& bbox,
int start_transaction_id,
int end_transaction_id,
int write_transaction_id) const;
template
void vw::platefile::SnapshotManager<PixelGrayA<int16> >::snapshot(int level,
BBox2i const& bbox,
int start_transaction_id,
int end_transaction_id,
int write_transaction_id) const;
template
void vw::platefile::SnapshotManager<PixelRGBA<uint8> >::snapshot(int level,
BBox2i const& bbox,
int start_transaction_id,
int end_transaction_id,
int write_transaction_id) const;
template
void vw::platefile::SnapshotManager<PixelGrayA<uint8> >::full_snapshot(int start_transaction_id,
int end_transaction_id,
int write_transaction_id) const;
template
void vw::platefile::SnapshotManager<PixelGrayA<int16> >::full_snapshot(int start_transaction_id,
int end_transaction_id,
int write_transaction_id) const;
template
void vw::platefile::SnapshotManager<PixelRGBA<uint8> >::full_snapshot(int start_transaction_id,
int end_transaction_id,
int write_transaction_id) const;
}}
<commit_msg>Added better error handling when a tile read fails during a snapshot, and also added more verbose debugging.<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <vw/Plate/SnapshotManager.h>
#include <vw/Plate/TileManipulation.h>
#include <vw/Mosaic/ImageComposite.h>
#include <vw/Image/ImageView.h>
#include <set>
namespace vw {
namespace platefile {
bool is_leaf(boost::shared_ptr<PlateFile> platefile, TileHeader const& tile_header) {
int current_col = tile_header.col();
int current_row = tile_header.row();
for (int new_row = current_row*2; new_row < current_row*2+2; ++new_row) {
for (int new_col = current_col*2; new_col < current_col*2+2; ++new_col) {
try {
std::list<TileHeader> tile_records;
tile_records = platefile->search_by_location(new_col, new_row,
tile_header.level() + 1,
tile_header.transaction_id(),
tile_header.transaction_id(),
false); // fetch_one_additional_entry
// If this node has child tiles, then it is not a leaf node.
if (tile_records.size() > 0)
return false;
} catch (TileNotFoundErr &e) { /* do nothing */ }
}
}
// If not child tiles were found, then this is a leaf node.
return true;
}
template <class PixelT>
int vw::platefile::SnapshotManager<PixelT>::snapshot_helper(int current_col,
int current_row,
int current_level,
std::map<int32, TileHeader> composite_tiles,
vw::BBox2i const& target_region,
int target_level,
int start_transaction_id,
int end_transaction_id,
int write_transaction_id) const {
// Check to see if there are any tiles at this level that need to be
// snapshotted. We fetch one additional tile outside of the
// specified range so that we get any tiles that were not actually
// composited during the last snapshot.
std::list<TileHeader> tile_records;
try {
tile_records = m_platefile->search_by_location(current_col, current_row, current_level,
start_transaction_id, end_transaction_id,
true); // fetch_one_additional_entry
} catch (TileNotFoundErr &e) { /* do nothing */ }
// If there are no valid tiles at this level, then there is nothing
// further for us to do here on this branch of the recursion. We
// return immediately.
if (tile_records.size() == 0)
return 0;
// Insert the TileHeaders for this level into the composite_tiles
// map<>. Elements will be inserted in order, and any duplicate
// transaction_ids will be overwritten by new tile records. In
// this fashion, we build up a list of the highest resolution
// valid tiles in order of transaction id.
for (std::list<TileHeader>::iterator iter = tile_records.begin();
iter != tile_records.end(); ++iter) {
if (current_level == target_level || is_leaf(m_platefile, *iter) ) {
// We always add any valid tiles at the target_level, since
// they should always be included in the composite.
//
// When adding tiles that may need to be supersampled, we are
// only interested in leaf nodes. All others will have higher
// resolution tiles available as their children that we should
// use instead.
composite_tiles[iter->transaction_id()] = *iter;
}
}
// If we have reached the target level, then we use the
// accumulated tiles to generate a snapshot for this tile.
if (current_level == target_level) {
// Check to see if the second entry is the start_transaction_id.
// If this is the case, then we can safely skip the first tile
// (which is then assumed to be the "additional_entry" that
// falls earlier than the given transaction range) since it
// will have already been incorporated into the previous
// snapshot.
if (composite_tiles.size() >= 2) {
std::map<int32, TileHeader>::iterator lowest_tid_iter = composite_tiles.begin();
std::map<int32, TileHeader>::iterator second_tid_iter = lowest_tid_iter;
++second_tid_iter;
if (int(second_tid_iter->first) == start_transaction_id) {
composite_tiles.erase(lowest_tid_iter);
}
}
// If we arrive at the target level and find that we have fewer
// than two tiles to composite, then there's no actual
// compositing that needs to be done. We can safely bail on
// this tile.
if (composite_tiles.size() < 2)
return 0;
// Create a tile into which we will accumulate composited data.
ImageView<PixelT> composite_tile(m_platefile->default_tile_size(),
m_platefile->default_tile_size());
int num_composited = 0;
for (std::map<int32, TileHeader>::reverse_iterator iter = composite_tiles.rbegin();
iter != composite_tiles.rend(); ++iter) {
TileHeader ¤t_hdr = iter->second;
// std::cout << "\t--> [ " << current_hdr.transaction_id() << " ] "
// << current_hdr.col() << " " << current_hdr.row()
// << " @ " << current_hdr.level() << "\n";
ImageView<PixelT> new_tile(m_platefile->default_tile_size(),
m_platefile->default_tile_size());
// Tile access is highly localized during snapshotting, so it
// speeds things up considerably to cache them here. We check
// the cache first and then read the tile from the platefile
// if nothing is found.
if ( !(this->restore_tile(new_tile, current_hdr.col(), current_hdr.row(),
current_hdr.level(), current_hdr.transaction_id())) ) {
try {
// If the tile isn't in our cache, then we take the
// performance hit and read the tile from the platefile.
m_platefile->read(new_tile,
current_hdr.col(), current_hdr.row(),
current_hdr.level(), current_hdr.transaction_id(),
true); // exact_transaction_match
} catch (BlobIoErr &e) {
// If we get a BlobIO error, that's bad news, but not worth
// killing the snapshot for. Instead we log the error here and move
// onto the next location.
std::ostringstream ostr;
ostr << "WARNING: a BlobIoErr occured while reading tile [" << current_hdr.col()
<< " " << current_hdr.row() << "] @ " << current_hdr.level()
<< " (t_id = " << current_hdr.transaction_id() << "): " << e.what();
m_platefile->log(ostr.str());
vw_out(ErrorMessage) << ostr.str() << "\n";
continue;
} catch (IOErr &e) {
// If we get a BlobIO error, that's bad news, but not worth
// killing the snapshot for. Instead we log the error here and move
// onto the next location.
std::ostringstream ostr;
ostr << "WARNING: an IOErr occurred while reading tile [" << current_hdr.col()
<< " " << current_hdr.row() << "] @ " << current_hdr.level()
<< " (t_id = " << current_hdr.transaction_id() << "): " << e.what();
m_platefile->log(ostr.str());
vw_out(ErrorMessage) << ostr.str() << "\n";
continue;
}
// Save the tile to the read cache.
this->save_tile(new_tile, current_hdr.col(), current_hdr.row(),
current_hdr.level(), current_hdr.transaction_id());
}
// If this is the first tile in this location, it's already at
// the target_level, and it's opaque (which is a very common
// case), then we don't need to save it as part of the
// snapshot since its already the top tile in the snapshot.
// This optimization saves us both space and time!
if ( current_hdr.level() == target_level &&
iter == composite_tiles.rbegin() &&
is_opaque(new_tile) ) {
return 0;
}
// If we are compositing a tile from a lower resolution in the
// pyramid, it needs to be supersampled and cropped before we
// can use it here.
if (current_hdr.level() != target_level) {
new_tile = resample_img_from_level(
new_tile, current_hdr.col(), current_hdr.row(), current_hdr.level(),
current_col, current_row, target_level);
}
// Add the new tile UNDERNEATH the tiles we have already composited.
vw::mosaic::ImageComposite<PixelT> composite;
composite.insert(new_tile, 0, 0);
composite.insert(composite_tile, 0, 0);
composite.set_draft_mode( true );
composite.prepare();
// Overwrite the composite_tile
composite_tile = composite;
++num_composited;
// Check to see if the composite tile is opaque. If it is,
// then there's no point in compositing any more tiles because
// they will end up hidden anyway.
if ( is_opaque(composite_tile) ) {
break;
}
}
if (num_composited > 0) {
// -- debug
vw_out(DebugMessage, "plate::snapshot") << "\t Compositing " << current_col << " "
<< current_row << " @ " << current_level
<< " [ " << num_composited << " ]\n";
//---
// for (unsigned j = 0; j < composite_tile.rows(); ++j) {
// for (unsigned i = 0; i < composite_tile.cols(); ++i) {
// composite_tile(i,j)[0] *= -1;
// }
// }
m_platefile->write_update(composite_tile,
current_col, current_row, current_level,
write_transaction_id);
return 1;
} else {
return 0;
}
} else {
// If we haven't reached the target level, then are four
// possible children that we can explore for more snapshotting
// information.
int num_tiles_updated = 0;
for (int new_row = current_row*2; new_row < current_row*2+2; ++new_row) {
for (int new_col = current_col*2; new_col < current_col*2+2; ++new_col) {
// We should only explore those child tiles that overlap
// with the target_region at the target level. To test
// this, we create a bounding box for the child tile we are
// testing, and scale that bounding box up to see how big it
// is when projected into the target_level of the pyramid.
BBox2i parent_region(new_col, new_row, 1, 1);
parent_region.min() *= pow(2,target_level-(current_level+1));
parent_region.max() *= pow(2,target_level-(current_level+1));
// With the scaled up parent region and the target region in
// hand, we can do a simple intersection test to assess
// whether this child tile is worth exploring.
if (parent_region.intersects(target_region)) {
num_tiles_updated += snapshot_helper(new_col, new_row, current_level+1,
composite_tiles, target_region, target_level,
start_transaction_id, end_transaction_id,
write_transaction_id);
}
}
}
return num_tiles_updated;
}
}
}} // namespace vw::platefile
template <class PixelT>
void vw::platefile::SnapshotManager<PixelT>::snapshot(int level, BBox2i const& tile_region,
int start_transaction_id,
int end_transaction_id,
int write_transaction_id) const {
// Subdivide the bbox into smaller workunits if necessary.
// This helps to keep operations efficient.
std::list<BBox2i> tile_workunits = bbox_tiles(tile_region, 1024, 1024);
for ( std::list<BBox2i>::iterator region_iter = tile_workunits.begin();
region_iter != tile_workunits.end(); ++region_iter) {
// Create an empty list of composite tiles and then kick off the
// recursive snapshotting process.
std::map<int32, TileHeader> composite_tiles;
int num_tiles_updated = snapshot_helper(0, 0, 0, composite_tiles, *region_iter, level,
start_transaction_id, end_transaction_id,
write_transaction_id);
if (num_tiles_updated > 0)
vw_out() << "\t--> Snapshot " << *region_iter << " @ level " << level
<< " (" << num_tiles_updated << " tiles updated).\n";
}
}
// Create a full snapshot of every level and every region in the mosaic.
template <class PixelT>
void vw::platefile::SnapshotManager<PixelT>::full_snapshot(int start_transaction_id,
int end_transaction_id,
int write_transaction_id) const {
for (int level = 0; level < m_platefile->num_levels(); ++level) {
// For debugging:
// for (int level = 11; level < 12; ++level) {
// Snapshot the entire region at each level. These region will be
// broken down into smaller work units in snapshot().
int region_size = pow(2,level);
int subdivided_region_size = region_size / 16;
if (subdivided_region_size < 1024) subdivided_region_size = 1024;
BBox2i full_region(0,0,region_size,region_size);
std::list<BBox2i> workunits = bbox_tiles(full_region,
subdivided_region_size,
subdivided_region_size);
for ( std::list<BBox2i>::iterator region_iter = workunits.begin();
region_iter != workunits.end(); ++region_iter) {
snapshot(level, *region_iter, start_transaction_id,
end_transaction_id, write_transaction_id);
}
}
}
// Explicit template instatiation
namespace vw {
namespace platefile {
template
void vw::platefile::SnapshotManager<PixelGrayA<uint8> >::snapshot(int level,
BBox2i const& bbox,
int start_transaction_id,
int end_transaction_id,
int write_transaction_id) const;
template
void vw::platefile::SnapshotManager<PixelGrayA<int16> >::snapshot(int level,
BBox2i const& bbox,
int start_transaction_id,
int end_transaction_id,
int write_transaction_id) const;
template
void vw::platefile::SnapshotManager<PixelRGBA<uint8> >::snapshot(int level,
BBox2i const& bbox,
int start_transaction_id,
int end_transaction_id,
int write_transaction_id) const;
template
void vw::platefile::SnapshotManager<PixelGrayA<uint8> >::full_snapshot(int start_transaction_id,
int end_transaction_id,
int write_transaction_id) const;
template
void vw::platefile::SnapshotManager<PixelGrayA<int16> >::full_snapshot(int start_transaction_id,
int end_transaction_id,
int write_transaction_id) const;
template
void vw::platefile::SnapshotManager<PixelRGBA<uint8> >::full_snapshot(int start_transaction_id,
int end_transaction_id,
int write_transaction_id) const;
}}
<|endoftext|>
|
<commit_before>#include <stdlib.h>
#define BOOST_TEST_MODULE watcher::Color test
#include <boost/test/unit_test.hpp>
#include <boost/archive/polymorphic_text_iarchive.hpp>
#include <boost/archive/polymorphic_text_oarchive.hpp>
#include <boost/archive/polymorphic_binary_iarchive.hpp>
#include <boost/archive/polymorphic_binary_oarchive.hpp>
#include "../watcherColors.h"
#include "logger.h"
using namespace std;
using namespace boost;
using namespace watcher;
using namespace boost::unit_test_framework;
BOOST_AUTO_TEST_CASE( ctors_test )
{
LOAD_LOG_PROPS("log.properties");
LOG_INFO("Checking Color constructors...");
Color c1, c2;
BOOST_CHECK_EQUAL( c1, c2 );
c1=Color(0xface1234);
c2.fromString("0xface1234");
BOOST_CHECK_EQUAL( c1, c2 );
c1=Color::blue;
c2=Color(0x0000ff00);
BOOST_CHECK_EQUAL( c1, c2 );
c1=Color::gold;
c2=c1;
BOOST_CHECK_EQUAL( c1, c2 );
c1=Color(0x00, 0x80, 0x00, 0x00);
c2=Color::green;
BOOST_CHECK_EQUAL( c1, c2 );
bool val = c2.fromString("this is not properly formatted");
BOOST_CHECK_EQUAL( val, false );
val = c2.fromString("green");
BOOST_CHECK_EQUAL( val, true );
BOOST_CHECK_EQUAL( c2, Color::green );
}
BOOST_AUTO_TEST_CASE( archive_test )
{
Color green(Color::green);
ostringstream os1;
archive::polymorphic_text_oarchive oa1(os1);
oa1 << green;
LOG_DEBUG("Serialized Color::green: (" << os1.str() << ")");
Color c;
istringstream is1(os1.str());
archive::polymorphic_text_iarchive ia1(is1);
ia1 >> c;
LOG_INFO( "Checking text archiving..." );
BOOST_CHECK_EQUAL( c, green );
BOOST_CHECK_EQUAL( c, Color::green );
BOOST_CHECK_EQUAL( green, Color::green );
ostringstream os2;
archive::polymorphic_binary_oarchive oa2(os2);
oa2 << green;
istringstream is2(os2.str());
archive::polymorphic_binary_iarchive ia2(is2);
ia2 >> c;
LOG_INFO( "Checking binary archiving..." );
BOOST_CHECK_EQUAL( c, green );
BOOST_CHECK_EQUAL( c, Color::green );
BOOST_CHECK_EQUAL( green, Color::green );
}
BOOST_AUTO_TEST_CASE( output_test )
{
LOG_INFO("Checking Color output operators...");
Color c(0xface1234);
string o1("0xface1234");
stringstream o2;
o2 << c;
BOOST_CHECK_EQUAL( o1, o2.str() );
o1 = "blue";
c=Color::blue;
stringstream o3;
o3 << c;
BOOST_CHECK_EQUAL( o1, o3.str() );
}
<commit_msg>Moved into libwatcher test dir.<commit_after><|endoftext|>
|
<commit_before>#pragma once
// `krbn::file_monitor` can be used safely in a multi-threaded environment.
#include "boost_defs.hpp"
#include "cf_utility.hpp"
#include "filesystem.hpp"
#include "logger.hpp"
#include <CoreServices/CoreServices.h>
#include <boost/signals2.hpp>
#include <utility>
#include <vector>
namespace krbn {
class file_monitor final {
public:
// Signals
boost::signals2::signal<void(void)> register_stream_finished;
boost::signals2::signal<void(const std::string& file_path)> file_changed;
// Methods
file_monitor(const std::vector<std::string>& files) : directories_(cf_utility::create_cfmutablearray()),
stream_(nullptr) {
run_loop_thread_ = std::make_shared<cf_utility::run_loop_thread>();
std::vector<std::string> directories;
for (const auto& f : files) {
auto directory = filesystem::dirname(f);
if (std::none_of(std::begin(directories),
std::end(directories),
[&](auto&& d) {
return directory == d;
})) {
directories.push_back(directory);
}
// Do not apply `realpath` here since `realpath(f)` will be failed if `f` does not exist.
files_.push_back(f);
}
for (const auto& d : directories) {
if (auto directory = cf_utility::create_cfstring(d)) {
if (directories_) {
CFArrayAppendValue(directories_, directory);
}
CFRelease(directory);
}
}
}
~file_monitor(void) {
run_loop_thread_->enqueue(^{
unregister_stream();
});
run_loop_thread_ = nullptr;
if (directories_) {
CFRelease(directories_);
directories_ = nullptr;
}
}
std::shared_ptr<cf_utility::run_loop_thread> get_run_loop_thread(void) const {
return run_loop_thread_;
}
void start(void) {
run_loop_thread_->enqueue(^{
register_stream();
});
}
void enqueue_file_changed(const std::string& file_path) {
run_loop_thread_->enqueue(^{
call_file_changed_slots(file_path);
});
}
private:
void register_stream(void) {
// Skip if already started.
if (stream_) {
return;
}
// ----------------------------------------
// File System Events API does not call the callback if the root directory and files are moved at the same time.
//
// Example:
//
// FSEventStreamCreate(... ,{"target/file1", "target/file2"})
//
// $ mkdir target.new
// $ echo target.new/file1
// $ mv target.new target
//
// In this case, the callback will not be called.
//
// Thus, we should signal manually once.
for (const auto& file : files_) {
call_file_changed_slots(file);
}
// ----------------------------------------
FSEventStreamContext context{0};
context.info = this;
// kFSEventStreamCreateFlagWatchRoot and kFSEventStreamCreateFlagFileEvents are required in the following case.
// (When directory == ~/.karabiner.d/configuration, file == ~/.karabiner.d/configuration/xxx.json)
//
// $ mkdir ~/.karabiner.d/configuration
// $ touch ~/.karabiner.d/configuration/xxx.json
// $ mv ~/.karabiner.d/configuration ~/.karabiner.d/configuration.back
// $ ln -s ~/file-synchronisation-service/karabiner.d/configuration ~/.karabiner.d/
// $ touch ~/.karabiner.d/configuration/xxx.json
auto flags = FSEventStreamCreateFlags(0);
flags |= kFSEventStreamCreateFlagWatchRoot;
flags |= kFSEventStreamCreateFlagIgnoreSelf;
flags |= kFSEventStreamCreateFlagFileEvents;
stream_ = FSEventStreamCreate(kCFAllocatorDefault,
static_stream_callback,
&context,
directories_,
kFSEventStreamEventIdSinceNow,
0.1, // 100 ms
flags);
if (!stream_) {
logger::get_logger().error("FSEventStreamCreate error @ {0}", __PRETTY_FUNCTION__);
} else {
FSEventStreamScheduleWithRunLoop(stream_,
run_loop_thread_->get_run_loop(),
kCFRunLoopDefaultMode);
if (!FSEventStreamStart(stream_)) {
logger::get_logger().error("FSEventStreamStart error @ {0}", __PRETTY_FUNCTION__);
}
}
register_stream_finished();
}
void unregister_stream(void) {
if (stream_) {
FSEventStreamStop(stream_);
FSEventStreamInvalidate(stream_);
FSEventStreamRelease(stream_);
stream_ = nullptr;
}
}
static void static_stream_callback(ConstFSEventStreamRef stream,
void* client_callback_info,
size_t num_events,
void* event_paths,
const FSEventStreamEventFlags event_flags[],
const FSEventStreamEventId event_ids[]) {
auto self = reinterpret_cast<file_monitor*>(client_callback_info);
if (self) {
self->stream_callback(num_events,
static_cast<const char**>(event_paths),
event_flags,
event_ids);
}
}
void stream_callback(size_t num_events,
const char* event_paths[],
const FSEventStreamEventFlags event_flags[],
const FSEventStreamEventId event_ids[]) {
for (size_t i = 0; i < num_events; ++i) {
if (event_flags[i] & kFSEventStreamEventFlagRootChanged) {
logger::get_logger().info("The configuration directory is updated.");
// re-register stream
unregister_stream();
register_stream();
} else {
call_file_changed_slots(event_paths[i]);
}
}
}
void call_file_changed_slots(const std::string& file_path) const {
// FSEvents passes realpathed file path to callback.
// Thus, we have to compare realpathed file paths.
if (auto path = filesystem::realpath(file_path)) {
if (filesystem::exists(*path)) {
if (std::any_of(std::begin(files_),
std::end(files_),
[&](auto&& p) {
return *path == filesystem::realpath(p);
})) {
file_changed(*path);
}
}
}
}
CFMutableArrayRef directories_;
std::vector<std::string> files_;
std::shared_ptr<cf_utility::run_loop_thread> run_loop_thread_;
FSEventStreamRef stream_;
};
} // namespace krbn
<commit_msg>check kFSEventStreamEventFlagKernelDropped and kFSEventStreamEventFlagUserDropped in file_monitor<commit_after>#pragma once
// `krbn::file_monitor` can be used safely in a multi-threaded environment.
#include "boost_defs.hpp"
#include "cf_utility.hpp"
#include "filesystem.hpp"
#include "logger.hpp"
#include <CoreServices/CoreServices.h>
#include <boost/signals2.hpp>
#include <utility>
#include <vector>
namespace krbn {
class file_monitor final {
public:
// Signals
boost::signals2::signal<void(void)> register_stream_finished;
boost::signals2::signal<void(const std::string& file_path)> file_changed;
// Methods
file_monitor(const std::vector<std::string>& files) : directories_(cf_utility::create_cfmutablearray()),
stream_(nullptr) {
run_loop_thread_ = std::make_shared<cf_utility::run_loop_thread>();
std::vector<std::string> directories;
for (const auto& f : files) {
auto directory = filesystem::dirname(f);
if (std::none_of(std::begin(directories),
std::end(directories),
[&](auto&& d) {
return directory == d;
})) {
directories.push_back(directory);
}
// Do not apply `realpath` here since `realpath(f)` will be failed if `f` does not exist.
files_.push_back(f);
}
for (const auto& d : directories) {
if (auto directory = cf_utility::create_cfstring(d)) {
if (directories_) {
CFArrayAppendValue(directories_, directory);
}
CFRelease(directory);
}
}
}
~file_monitor(void) {
run_loop_thread_->enqueue(^{
unregister_stream();
});
run_loop_thread_ = nullptr;
if (directories_) {
CFRelease(directories_);
directories_ = nullptr;
}
}
std::shared_ptr<cf_utility::run_loop_thread> get_run_loop_thread(void) const {
return run_loop_thread_;
}
void start(void) {
run_loop_thread_->enqueue(^{
register_stream();
});
}
void enqueue_file_changed(const std::string& file_path) {
run_loop_thread_->enqueue(^{
call_file_changed_slots(file_path);
});
}
private:
void register_stream(void) {
// Skip if already started.
if (stream_) {
return;
}
// ----------------------------------------
// File System Events API does not call the callback if the root directory and files are moved at the same time.
//
// Example:
//
// FSEventStreamCreate(... ,{"target/file1", "target/file2"})
//
// $ mkdir target.new
// $ echo target.new/file1
// $ mv target.new target
//
// In this case, the callback will not be called.
//
// Thus, we should signal manually once.
for (const auto& file : files_) {
call_file_changed_slots(file);
}
// ----------------------------------------
FSEventStreamContext context{0};
context.info = this;
// kFSEventStreamCreateFlagWatchRoot and kFSEventStreamCreateFlagFileEvents are required in the following case.
// (When directory == ~/.karabiner.d/configuration, file == ~/.karabiner.d/configuration/xxx.json)
//
// $ mkdir ~/.karabiner.d/configuration
// $ touch ~/.karabiner.d/configuration/xxx.json
// $ mv ~/.karabiner.d/configuration ~/.karabiner.d/configuration.back
// $ ln -s ~/file-synchronisation-service/karabiner.d/configuration ~/.karabiner.d/
// $ touch ~/.karabiner.d/configuration/xxx.json
auto flags = FSEventStreamCreateFlags(0);
flags |= kFSEventStreamCreateFlagWatchRoot;
flags |= kFSEventStreamCreateFlagIgnoreSelf;
flags |= kFSEventStreamCreateFlagFileEvents;
stream_ = FSEventStreamCreate(kCFAllocatorDefault,
static_stream_callback,
&context,
directories_,
kFSEventStreamEventIdSinceNow,
0.1, // 100 ms
flags);
if (!stream_) {
logger::get_logger().error("FSEventStreamCreate error @ {0}", __PRETTY_FUNCTION__);
} else {
FSEventStreamScheduleWithRunLoop(stream_,
run_loop_thread_->get_run_loop(),
kCFRunLoopDefaultMode);
if (!FSEventStreamStart(stream_)) {
logger::get_logger().error("FSEventStreamStart error @ {0}", __PRETTY_FUNCTION__);
}
}
register_stream_finished();
}
void unregister_stream(void) {
if (stream_) {
FSEventStreamStop(stream_);
FSEventStreamInvalidate(stream_);
FSEventStreamRelease(stream_);
stream_ = nullptr;
}
}
static void static_stream_callback(ConstFSEventStreamRef stream,
void* client_callback_info,
size_t num_events,
void* event_paths,
const FSEventStreamEventFlags event_flags[],
const FSEventStreamEventId event_ids[]) {
auto self = reinterpret_cast<file_monitor*>(client_callback_info);
if (self) {
self->stream_callback(num_events,
static_cast<const char**>(event_paths),
event_flags,
event_ids);
}
}
void stream_callback(size_t num_events,
const char* event_paths[],
const FSEventStreamEventFlags event_flags[],
const FSEventStreamEventId event_ids[]) {
for (size_t i = 0; i < num_events; ++i) {
if (event_flags[i] & (kFSEventStreamEventFlagRootChanged |
kFSEventStreamEventFlagKernelDropped |
kFSEventStreamEventFlagUserDropped)) {
logger::get_logger().info("The configuration directory is updated.");
// re-register stream
unregister_stream();
register_stream();
} else {
call_file_changed_slots(event_paths[i]);
}
}
}
void call_file_changed_slots(const std::string& file_path) const {
// FSEvents passes realpathed file path to callback.
// Thus, we have to compare realpathed file paths.
if (auto path = filesystem::realpath(file_path)) {
if (filesystem::exists(*path)) {
if (std::any_of(std::begin(files_),
std::end(files_),
[&](auto&& p) {
return *path == filesystem::realpath(p);
})) {
file_changed(*path);
}
}
}
}
CFMutableArrayRef directories_;
std::vector<std::string> files_;
std::shared_ptr<cf_utility::run_loop_thread> run_loop_thread_;
FSEventStreamRef stream_;
};
} // namespace krbn
<|endoftext|>
|
<commit_before>#pragma once
#include <mach/mach_time.h>
namespace krbn {
class time_utility final {
public:
static uint64_t absolute_to_nano(uint64_t absolute_time) {
auto& t = get_mach_timebase_info_data();
if (t.numer != t.denom && t.denom != 0) {
return absolute_time * t.numer / t.denom;
}
return absolute_time;
}
static uint64_t nano_to_absolute(uint64_t absolute_time) {
auto& t = get_mach_timebase_info_data();
if (t.numer != t.denom && t.numer != 0) {
return absolute_time * t.denom / t.numer;
}
return absolute_time;
}
private:
static const mach_timebase_info_data_t& get_mach_timebase_info_data(void) {
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
static bool once = false;
static mach_timebase_info_data_t mach_timebase_info_data;
if (!once) {
once = true;
mach_timebase_info(&mach_timebase_info_data);
}
return mach_timebase_info_data;
}
};
} // namespace krbn
<commit_msg>add time_utility::make_current_local_yyyymmdd_string<commit_after>#pragma once
#include "logger.hpp"
#include <mach/mach_time.h>
#include <time.h>
namespace krbn {
class time_utility final {
public:
static uint64_t absolute_to_nano(uint64_t absolute_time) {
auto& t = get_mach_timebase_info_data();
if (t.numer != t.denom && t.denom != 0) {
return absolute_time * t.numer / t.denom;
}
return absolute_time;
}
static uint64_t nano_to_absolute(uint64_t absolute_time) {
auto& t = get_mach_timebase_info_data();
if (t.numer != t.denom && t.numer != 0) {
return absolute_time * t.denom / t.numer;
}
return absolute_time;
}
static std::string make_current_local_yyyymmdd_string(void) {
auto t = time(nullptr);
tm tm;
localtime_r(&t, &tm);
return fmt::format("{0:04d}-{1:02d}-{2:02d}",
tm.tm_year + 1900,
tm.tm_mon + 1,
tm.tm_mday);
}
private:
static const mach_timebase_info_data_t& get_mach_timebase_info_data(void) {
static std::mutex mutex;
std::lock_guard<std::mutex> guard(mutex);
static bool once = false;
static mach_timebase_info_data_t mach_timebase_info_data;
if (!once) {
once = true;
mach_timebase_info(&mach_timebase_info_data);
}
return mach_timebase_info_data;
}
};
} // namespace krbn
<|endoftext|>
|
<commit_before>#ifndef _SDD_HOM_SUM_HH_
#define _SDD_HOM_SUM_HH_
#include <algorithm> // all_of, copy, equal
#include <deque>
#include <initializer_list>
#include <iosfwd>
#include <stdexcept> //invalid_argument
#include <unordered_map>
#include <boost/container/flat_set.hpp>
#include "sdd/dd/definition.hh"
#include "sdd/dd/top.hh"
#include "sdd/hom/consolidate.hh"
#include "sdd/hom/context_fwd.hh"
#include "sdd/hom/definition_fwd.hh"
#include "sdd/hom/evaluation_error.hh"
#include "sdd/hom/identity.hh"
#include "sdd/hom/local.hh"
#include "sdd/order/order.hh"
#include "sdd/util/packed.hh"
namespace sdd { namespace hom {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Sum homomorphism.
template <typename C>
class LIBSDD_ATTRIBUTE_PACKED sum
{
public:
/// @brief The type of a const iterator on this sum's operands.
typedef const homomorphism<C>* const_iterator;
private:
/// @brief The type deduced from configuration of the number of operands.
typedef typename C::operands_size_type operands_size_type;
/// @brief The homomorphism's number of operands.
const operands_size_type size_;
public:
/// @brief Constructor.
sum(boost::container::flat_set<homomorphism<C>>& operands)
: size_(static_cast<operands_size_type>(operands.size()))
{
// Put all homomorphisms operands right after this sum instance.
hom::consolidate(operands_addr(), operands.begin(), operands.end());
}
/// @brief Destructor.
~sum()
{
for (auto& h : *this)
{
h.~homomorphism<C>();
}
}
/// @brief Evaluation.
SDD<C>
operator()(context<C>& cxt, const order<C>& o, const SDD<C>& x)
const
{
dd::sum_builder<C, SDD<C>> sum_operands(size_);
for (const auto& op : *this)
{
sum_operands.add(op(cxt, o, x));
}
try
{
return dd::sum(cxt.sdd_context(), std::move(sum_operands));
}
catch (top<C>& t)
{
evaluation_error<C> e(x);
e.add_top(t);
throw e;
}
}
/// @brief Skip variable predicate.
bool
skip(const order<C>& o)
const noexcept
{
return std::all_of( begin(), end()
, [&o](const homomorphism<C>& h){return h.skip(o);});
}
/// @brief Selector predicate
bool
selector()
const noexcept
{
return std::all_of( begin(), end()
, [](const homomorphism<C>& h){return h.selector();});
}
/// @brief Get an iterator to the first operand.
///
/// O(1).
const_iterator
begin()
const noexcept
{
return reinterpret_cast<const homomorphism<C>*>(operands_addr());
}
/// @brief Get an iterator to the end of operands.
///
/// O(1).
const_iterator
end()
const noexcept
{
return reinterpret_cast<const homomorphism<C>*>(operands_addr()) + size_;
}
/// @brief Get the number of operands.
///
/// O(1).
std::size_t
size()
const noexcept
{
return size_;
}
/// @brief Get the number of extra bytes.
///
/// These extra extra bytes correspond to the operands allocated right after this homomorphism.
std::size_t
extra_bytes()
const noexcept
{
return size_ * sizeof(homomorphism<C>);
}
private:
/// @brief Return the address of the beginning of the operands.
char*
operands_addr()
const noexcept
{
return reinterpret_cast<char*>(const_cast<sum*>(this)) + sizeof(sum);
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Equality of two sum.
/// @related sum
template <typename C>
inline
bool
operator==(const sum<C>& lhs, const sum<C>& rhs)
noexcept
{
return lhs.size() == rhs.size() and std::equal(lhs.begin(), lhs.end(), rhs.begin());
}
/// @internal
/// @related sum
template <typename C>
std::ostream&
operator<<(std::ostream& os, const sum<C>& s)
{
os << "(";
std::copy( s.begin(), std::prev(s.end())
, std::ostream_iterator<homomorphism<C>>(os, " + "));
return os << *std::prev(s.end()) << ")";
}
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Help optimize an union's operands.
template <typename C>
struct sum_builder_helper
{
typedef void result_type;
typedef boost::container::flat_set<homomorphism<C>> operands_type;
typedef std::deque<homomorphism<C>> hom_list_type;
typedef std::unordered_map<typename C::Identifier, hom_list_type> locals_type;
/// @brief Flatten nested sums.
void
operator()( const sum<C>& s
, const homomorphism<C>& h, operands_type& operands, locals_type& locals)
const
{
for (const auto& op : s)
{
apply_visitor(*this, op->data(), op, operands, locals);
}
}
/// @brief Regroup locals.
void
operator()( const local<C>& l
, const homomorphism<C>& h, operands_type& operands, locals_type& locals)
const
{
auto insertion = locals.emplace(l.identifier(), hom_list_type());
insertion.first->second.emplace_back(l.hom());
}
/// @brief Insert normally all other operands.
template <typename T>
void
operator()(const T&, const homomorphism<C>& h, operands_type& operands, locals_type&)
const
{
operands.insert(h);
}
};
} // namespace hom
/*------------------------------------------------------------------------------------------------*/
/// @brief Create the Sum homomorphism.
/// @related homomorphism
template <typename C, typename InputIterator>
homomorphism<C>
Sum(const order<C>& o, InputIterator begin, InputIterator end)
{
const std::size_t size = std::distance(begin, end);
if (size == 0)
{
throw std::invalid_argument("Empty operands at Sum construction.");
}
boost::container::flat_set<homomorphism<C>> operands;
operands.reserve(size);
hom::sum_builder_helper<C> sbv;
typename hom::sum_builder_helper<C>::locals_type locals;
for (; begin != end; ++begin)
{
apply_visitor(sbv, (*begin)->data(), *begin, operands, locals);
}
// insert remaining locals
for (const auto& l : locals)
{
operands.insert(Local<C>(l.first, o, Sum<C>(o, l.second.begin(), l.second.end())));
}
if (operands.size() == 1)
{
return *operands.begin();
}
else
{
const std::size_t extra_bytes = operands.size() * sizeof(homomorphism<C>);
return homomorphism<C>::create2(mem::construct<hom::sum<C>>(), extra_bytes, operands);
}
}
/*------------------------------------------------------------------------------------------------*/
/// @brief Create the Sum homomorphism.
/// @related homomorphism
template <typename C>
homomorphism<C>
Sum(const order<C>& o, std::initializer_list<homomorphism<C>> operands)
{
return Sum<C>(o, operands.begin(), operands.end());
}
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Hash specialization for sdd::hom::sum.
template <typename C>
struct hash<sdd::hom::sum<C>>
{
std::size_t
operator()(const sdd::hom::sum<C>& s)
const noexcept
{
std::size_t seed = 0;
for (const auto& op : s)
{
sdd::util::hash_combine(seed, op);
}
return seed;
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
#endif // _SDD_HOM_SUM_HH_
<commit_msg>Comments, documentation and whitespaces.<commit_after>#ifndef _SDD_HOM_SUM_HH_
#define _SDD_HOM_SUM_HH_
#include <algorithm> // all_of, copy, equal
#include <deque>
#include <initializer_list>
#include <iosfwd>
#include <stdexcept> //invalid_argument
#include <unordered_map>
#include <boost/container/flat_set.hpp>
#include "sdd/dd/definition.hh"
#include "sdd/dd/top.hh"
#include "sdd/hom/consolidate.hh"
#include "sdd/hom/context_fwd.hh"
#include "sdd/hom/definition_fwd.hh"
#include "sdd/hom/evaluation_error.hh"
#include "sdd/hom/identity.hh"
#include "sdd/hom/local.hh"
#include "sdd/order/order.hh"
#include "sdd/util/packed.hh"
namespace sdd { namespace hom {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Sum homomorphism.
template <typename C>
class LIBSDD_ATTRIBUTE_PACKED sum
{
public:
/// @brief The type of a const iterator on this sum's operands.
typedef const homomorphism<C>* const_iterator;
private:
/// @brief The type deduced from configuration of the number of operands.
typedef typename C::operands_size_type operands_size_type;
/// @brief The homomorphism's number of operands.
const operands_size_type size_;
public:
/// @brief Constructor.
sum(boost::container::flat_set<homomorphism<C>>& operands)
: size_(static_cast<operands_size_type>(operands.size()))
{
// Put all homomorphisms operands right after this sum instance.
hom::consolidate(operands_addr(), operands.begin(), operands.end());
}
/// @brief Destructor.
~sum()
{
for (auto& h : *this)
{
h.~homomorphism<C>();
}
}
/// @brief Evaluation.
SDD<C>
operator()(context<C>& cxt, const order<C>& o, const SDD<C>& x)
const
{
dd::sum_builder<C, SDD<C>> sum_operands(size_);
for (const auto& op : *this)
{
sum_operands.add(op(cxt, o, x));
}
try
{
return dd::sum(cxt.sdd_context(), std::move(sum_operands));
}
catch (top<C>& t)
{
evaluation_error<C> e(x);
e.add_top(t);
throw e;
}
}
/// @brief Skip variable predicate.
bool
skip(const order<C>& o)
const noexcept
{
return std::all_of(begin(), end(), [&o](const homomorphism<C>& h){return h.skip(o);});
}
/// @brief Selector predicate
bool
selector()
const noexcept
{
return std::all_of(begin(), end(), [](const homomorphism<C>& h){return h.selector();});
}
/// @brief Get an iterator to the first operand.
///
/// O(1).
const_iterator
begin()
const noexcept
{
return reinterpret_cast<const homomorphism<C>*>(operands_addr());
}
/// @brief Get an iterator to the end of operands.
///
/// O(1).
const_iterator
end()
const noexcept
{
return reinterpret_cast<const homomorphism<C>*>(operands_addr()) + size_;
}
/// @brief Get the number of operands.
///
/// O(1).
std::size_t
size()
const noexcept
{
return size_;
}
/// @brief Get the number of extra bytes.
///
/// These extra extra bytes correspond to the operands allocated right after this homomorphism.
std::size_t
extra_bytes()
const noexcept
{
return size_ * sizeof(homomorphism<C>);
}
private:
/// @brief Return the address of the beginning of the operands.
char*
operands_addr()
const noexcept
{
return reinterpret_cast<char*>(const_cast<sum*>(this)) + sizeof(sum);
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Equality of two sum.
/// @related sum
template <typename C>
inline
bool
operator==(const sum<C>& lhs, const sum<C>& rhs)
noexcept
{
return lhs.size() == rhs.size() and std::equal(lhs.begin(), lhs.end(), rhs.begin());
}
/// @internal
/// @related sum
template <typename C>
std::ostream&
operator<<(std::ostream& os, const sum<C>& s)
{
os << "(";
std::copy(s.begin(), std::prev(s.end()), std::ostream_iterator<homomorphism<C>>(os, " + "));
return os << *std::prev(s.end()) << ")";
}
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Help optimize an union's operands.
template <typename C>
struct sum_builder_helper
{
/// @brief Used by mem::variant.
typedef void result_type;
/// @brief The type of th flat sorted set of operands.
typedef boost::container::flat_set<homomorphism<C>> operands_type;
/// @brief We use a deque to store the list of homomorphisms as the needed size is unknown.
typedef std::deque<homomorphism<C>> hom_list_type;
/// @brief Map Local homomorphisms to the identifiers they work on.
typedef std::unordered_map<typename C::Identifier, hom_list_type> locals_type;
/// @brief Flatten nested sums.
void
operator()( const sum<C>& s
, const homomorphism<C>& h, operands_type& operands, locals_type& locals)
const
{
for (const auto& op : s)
{
apply_visitor(*this, op->data(), op, operands, locals);
}
}
/// @brief Regroup locals.
void
operator()( const local<C>& l
, const homomorphism<C>& h, operands_type& operands, locals_type& locals)
const
{
auto insertion = locals.emplace(l.identifier(), hom_list_type());
insertion.first->second.emplace_back(l.hom());
}
/// @brief Insert normally all other operands.
template <typename T>
void
operator()(const T&, const homomorphism<C>& h, operands_type& operands, locals_type&)
const
{
operands.insert(h);
}
};
} // namespace hom
/*------------------------------------------------------------------------------------------------*/
/// @brief Create the Sum homomorphism.
/// @related homomorphism
template <typename C, typename InputIterator>
homomorphism<C>
Sum(const order<C>& o, InputIterator begin, InputIterator end)
{
const std::size_t size = std::distance(begin, end);
if (size == 0)
{
throw std::invalid_argument("Empty operands at Sum construction.");
}
boost::container::flat_set<homomorphism<C>> operands;
operands.reserve(size);
hom::sum_builder_helper<C> sbv;
typename hom::sum_builder_helper<C>::locals_type locals;
for (; begin != end; ++begin)
{
apply_visitor(sbv, (*begin)->data(), *begin, operands, locals);
}
// insert remaining locals
for (const auto& l : locals)
{
operands.insert(Local<C>(l.first, o, Sum<C>(o, l.second.begin(), l.second.end())));
}
if (operands.size() == 1)
{
return *operands.begin();
}
else
{
const std::size_t extra_bytes = operands.size() * sizeof(homomorphism<C>);
return homomorphism<C>::create2(mem::construct<hom::sum<C>>(), extra_bytes, operands);
}
}
/*------------------------------------------------------------------------------------------------*/
/// @brief Create the Sum homomorphism.
/// @related homomorphism
template <typename C>
homomorphism<C>
Sum(const order<C>& o, std::initializer_list<homomorphism<C>> operands)
{
return Sum<C>(o, operands.begin(), operands.end());
}
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Hash specialization for sdd::hom::sum.
template <typename C>
struct hash<sdd::hom::sum<C>>
{
std::size_t
operator()(const sdd::hom::sum<C>& s)
const noexcept
{
std::size_t seed = 0;
for (const auto& op : s)
{
sdd::util::hash_combine(seed, op);
}
return seed;
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
#endif // _SDD_HOM_SUM_HH_
<|endoftext|>
|
<commit_before>#include "blfhandler.h"
#include <QDebug>
#include <QFile>
#include <QString>
#include <QtEndian>
#define BLF_REMOTE_FLAG 0x80
BLFHandler::BLFHandler()
{
}
/*
Written while peeking at source code here:
https://python-can.readthedocs.io/en/latest/_modules/can/io/blf.html
https://bitbucket.org/tobylorenz/vector_blf/
All the code actually below is freshly written but heavily based upon things seen in those
two source repos.
*/
bool BLFHandler::loadBLF(QString filename, QVector<CANFrame>* frames)
{
BLF_OBJ_HEADER objHeader;
QByteArray fileData;
QByteArray uncompressedData;
QByteArray junk;
BLF_OBJECT obj;
uint32_t pos;
BLF_CAN_OBJ canObject;
BLF_CAN_OBJ2 canObject2;
QFile *inFile = new QFile(filename);
if (!inFile->open(QIODevice::ReadOnly))
{
delete inFile;
return false;
}
inFile->read((char *)&header, sizeof(header));
if (qFromLittleEndian(header.sig) == 0x47474F4C)
{
qDebug() << "Proper BLF file header token";
}
else return false;
while (!inFile->atEnd())
{
qDebug() << "Position within file: " << inFile->pos();
inFile->read((char *)&objHeader.base, sizeof(BLF_OBJ_HEADER_BASE));
if (qFromLittleEndian(objHeader.base.sig) == 0x4A424F4C)
{
int readSize = objHeader.base.objSize - sizeof(BLF_OBJ_HEADER_BASE);
qDebug() << "Proper object header token. Read Size: " << readSize;
fileData = inFile->read(readSize);
junk = inFile->read(readSize % 4); //file is padded so sizes must always end up on even multiple of 4
//qDebug() << "Fudge bytes in readSize: " << (readSize % 4);
switch (objHeader.base.objType)
{
case BLF_CONTAINER:
qDebug() << "Object is a container.";
memcpy(&objHeader.containerObj, fileData.constData(), sizeof(BLF_OBJ_HEADER_CONTAINER));
fileData.remove(0, sizeof(BLF_OBJ_HEADER_CONTAINER));
if (objHeader.containerObj.compressionMethod == BLF_CONT_NO_COMPRESSION)
{
qDebug() << "Container is not compressed";
uncompressedData = fileData;
}
if (objHeader.containerObj.compressionMethod == BLF_CONT_ZLIB_COMPRESSION)
{
qDebug() << "Compressed container. Unpacking it.";
fileData.prepend(objHeader.containerObj.uncompressedSize & 0xFF);
fileData.prepend((objHeader.containerObj.uncompressedSize >> 8) & 0xFF);
fileData.prepend((objHeader.containerObj.uncompressedSize >> 16) & 0xFF);
fileData.prepend((objHeader.containerObj.uncompressedSize >> 24) & 0xFF);
uncompressedData += qUncompress(fileData);
}
qDebug() << "Uncompressed size: " << uncompressedData.count();
pos = 0;
//bool foundHeader = false;
//first skip forward to find a header signature - usually not necessary
while ( (int)(pos + sizeof(BLF_OBJ_HEADER)) < uncompressedData.count())
{
int32_t *headerSig = (int32_t *)(uncompressedData.constData() + pos);
if (*headerSig == 0x4A424F4C) break;
pos += 4;
}
//then process all the objects
while ( (int)(pos + sizeof(BLF_OBJ_HEADER)) < uncompressedData.count())
{
memcpy(&obj.header.base, (uncompressedData.constData() + pos), sizeof(BLF_OBJ_HEADER_BASE));
memcpy(&obj.header.v1Obj, (uncompressedData.constData() + pos) + sizeof(BLF_OBJ_HEADER_BASE), sizeof(BLF_OBJ_HEADER_V1));
qDebug() << "Pos: " << pos << " Type: " << obj.header.base.objType << "Obj Size: " << obj.header.base.objSize;
if (qFromLittleEndian(objHeader.base.sig) == 0x4A424F4C)
{
fileData = uncompressedData.mid(pos + sizeof(BLF_OBJ_HEADER_BASE) + sizeof(BLF_OBJ_HEADER_V1), obj.header.base.objSize - sizeof(BLF_OBJ_HEADER_BASE) - sizeof(BLF_OBJ_HEADER_V1));
if (obj.header.base.objType == BLF_CAN_MSG)
{
memcpy(&canObject, fileData.constData(), sizeof(BLF_CAN_OBJ));
CANFrame frame;
frame.bus = canObject.channel;
frame.setExtendedFrameFormat((canObject.id & 0x80000000ull)?true:false);
frame.setFrameId(canObject.id & 0x1FFFFFFFull);
frame.isReceived = true;
QByteArray bytes(canObject.dlc, 0);
if (canObject.flags & BLF_REMOTE_FLAG) {
frame.setFrameType(QCanBusFrame::RemoteRequestFrame);
} else {
frame.setFrameType(QCanBusFrame::DataFrame);
for (int i = 0; i < 8; i++) bytes[i] = canObject.data[i];
}
frame.setPayload(bytes);
//Should we divide by a thousand or a million? Unsure here. It appears some logs are stamped in microseconds and some in milliseconds?
frame.setTimeStamp(QCanBusFrame::TimeStamp(0, obj.header.v1Obj.uncompSize / 1000.0)); //uncompsize field also used for timestamp oddly enough
frames->append(frame);
}
else if (obj.header.base.objType == BLF_CAN_MSG2)
{
memcpy(&canObject2, fileData.constData(), sizeof(BLF_CAN_OBJ2));
CANFrame frame;
frame.bus = canObject2.channel;
frame.setExtendedFrameFormat((canObject2.id & 0x80000000ull)?true:false);
frame.setFrameId(canObject2.id & 0x1FFFFFFFull);
frame.isReceived = true;
QByteArray bytes(canObject2.dlc, 0);
if (canObject2.flags & BLF_REMOTE_FLAG) {
frame.setFrameType(QCanBusFrame::RemoteRequestFrame);
} else {
frame.setFrameType(QCanBusFrame::DataFrame);
for (int i = 0; i < 8; i++) bytes[i] = canObject2.data[i];
}
//Should we divide by a thousand or a million? Unsure here. It appears some logs are stamped in microseconds and some in milliseconds?
frame.setTimeStamp(QCanBusFrame::TimeStamp(0, obj.header.v1Obj.uncompSize / 1000.0)); //uncompsize field also used for timestamp oddly enough
frames->append(frame);
}
else
{
//qDebug() << "Not a can frame! ObjType: " << obj.header.objType;
if (obj.header.base.objType > 0xFFFF)
return false;
}
pos += obj.header.base.objSize + (obj.header.base.objSize % 4);
}
else
{
qDebug() << "Unexpected object header signature, aborting";
return false;
}
}
uncompressedData.remove(0, pos);
qDebug() << "After removing used data uncompressedData is now this big: " << uncompressedData.count();
break;
}
}
else return false;
}
return true;
}
bool BLFHandler::saveBLF(QString filename, QVector<CANFrame> *frames)
{
Q_UNUSED(filename)
Q_UNUSED(frames)
return false;
}
<commit_msg>Slight changes to BLF loader, just to make debugging easier in the future<commit_after>#include "blfhandler.h"
#include <QDebug>
#include <QFile>
#include <QString>
#include <QtEndian>
#define BLF_REMOTE_FLAG 0x80
BLFHandler::BLFHandler()
{
}
/*
Written while peeking at source code here:
https://python-can.readthedocs.io/en/latest/_modules/can/io/blf.html
https://bitbucket.org/tobylorenz/vector_blf/
All the code actually below is freshly written but heavily based upon things seen in those
two source repos.
*/
bool BLFHandler::loadBLF(QString filename, QVector<CANFrame>* frames)
{
BLF_OBJ_HEADER objHeader;
QByteArray fileData;
QByteArray uncompressedData;
QByteArray junk;
BLF_OBJECT obj;
uint32_t pos;
BLF_CAN_OBJ canObject;
BLF_CAN_OBJ2 canObject2;
QFile *inFile = new QFile(filename);
if (!inFile->open(QIODevice::ReadOnly))
{
delete inFile;
return false;
}
inFile->read((char *)&header, sizeof(header));
if (qFromLittleEndian(header.sig) == 0x47474F4C)
{
qDebug() << "Proper BLF file header token";
}
else return false;
while (!inFile->atEnd())
{
qDebug() << "Position within file: " << inFile->pos();
inFile->read((char *)&objHeader.base, sizeof(BLF_OBJ_HEADER_BASE));
if (qFromLittleEndian(objHeader.base.sig) == 0x4A424F4C)
{
int readSize = objHeader.base.objSize - sizeof(BLF_OBJ_HEADER_BASE);
qDebug() << "Proper object header token. Read Size: " << readSize;
fileData = inFile->read(readSize);
junk = inFile->read(readSize % 4); //file is padded so sizes must always end up on even multiple of 4
//qDebug() << "Fudge bytes in readSize: " << (readSize % 4);
switch (objHeader.base.objType)
{
case BLF_CONTAINER:
qDebug() << "Object is a container.";
memcpy(&objHeader.containerObj, fileData.constData(), sizeof(BLF_OBJ_HEADER_CONTAINER));
fileData.remove(0, sizeof(BLF_OBJ_HEADER_CONTAINER));
if (objHeader.containerObj.compressionMethod == BLF_CONT_NO_COMPRESSION)
{
qDebug() << "Container is not compressed";
uncompressedData = fileData;
}
else if (objHeader.containerObj.compressionMethod == BLF_CONT_ZLIB_COMPRESSION)
{
qDebug() << "Compressed container. Unpacking it.";
fileData.prepend(objHeader.containerObj.uncompressedSize & 0xFF);
fileData.prepend((objHeader.containerObj.uncompressedSize >> 8) & 0xFF);
fileData.prepend((objHeader.containerObj.uncompressedSize >> 16) & 0xFF);
fileData.prepend((objHeader.containerObj.uncompressedSize >> 24) & 0xFF);
uncompressedData += qUncompress(fileData);
}
else
{
qDebug() << "Dunno what this is... " << objHeader.containerObj.compressionMethod;
}
qDebug() << "Uncompressed size: " << uncompressedData.count();
qDebug() << "Currently loaded frames at this point: " << frames->count();
pos = 0;
//bool foundHeader = false;
//first skip forward to find a header signature - usually not necessary
while ( (int)(pos + sizeof(BLF_OBJ_HEADER)) < uncompressedData.count())
{
int32_t *headerSig = (int32_t *)(uncompressedData.constData() + pos);
if (*headerSig == 0x4A424F4C) break;
pos += 4;
}
//then process all the objects
while ( (int)(pos + sizeof(BLF_OBJ_HEADER)) < uncompressedData.count())
{
memcpy(&obj.header.base, (uncompressedData.constData() + pos), sizeof(BLF_OBJ_HEADER_BASE));
memcpy(&obj.header.v1Obj, (uncompressedData.constData() + pos) + sizeof(BLF_OBJ_HEADER_BASE), sizeof(BLF_OBJ_HEADER_V1));
//if (obj.header.base.objType != 1)
//qDebug() << "Pos: " << pos << " Type: " << obj.header.base.objType << "Obj Size: " << obj.header.base.objSize;
if (qFromLittleEndian(objHeader.base.sig) == 0x4A424F4C)
{
fileData = uncompressedData.mid(pos + sizeof(BLF_OBJ_HEADER_BASE) + sizeof(BLF_OBJ_HEADER_V1), obj.header.base.objSize - sizeof(BLF_OBJ_HEADER_BASE) - sizeof(BLF_OBJ_HEADER_V1));
if (obj.header.base.objType == BLF_CAN_MSG)
{
memcpy(&canObject, fileData.constData(), sizeof(BLF_CAN_OBJ));
CANFrame frame;
frame.bus = canObject.channel;
frame.setExtendedFrameFormat((canObject.id & 0x80000000ull)?true:false);
frame.setFrameId(canObject.id & 0x1FFFFFFFull);
frame.isReceived = true;
QByteArray bytes(canObject.dlc, 0);
if (canObject.flags & BLF_REMOTE_FLAG) {
frame.setFrameType(QCanBusFrame::RemoteRequestFrame);
} else {
frame.setFrameType(QCanBusFrame::DataFrame);
for (int i = 0; i < canObject.dlc; i++) bytes[i] = canObject.data[i];
}
frame.setPayload(bytes);
//Should we divide by a thousand or a million? Unsure here. It appears some logs are stamped in microseconds and some in milliseconds?
frame.setTimeStamp(QCanBusFrame::TimeStamp(0, obj.header.v1Obj.uncompSize / 1000.0)); //uncompsize field also used for timestamp oddly enough
frames->append(frame);
}
else if (obj.header.base.objType == BLF_CAN_MSG2)
{
memcpy(&canObject2, fileData.constData(), sizeof(BLF_CAN_OBJ2));
CANFrame frame;
frame.bus = canObject2.channel;
frame.setExtendedFrameFormat((canObject2.id & 0x80000000ull)?true:false);
frame.setFrameId(canObject2.id & 0x1FFFFFFFull);
frame.isReceived = true;
QByteArray bytes(canObject2.dlc, 0);
if (canObject2.flags & BLF_REMOTE_FLAG) {
frame.setFrameType(QCanBusFrame::RemoteRequestFrame);
} else {
frame.setFrameType(QCanBusFrame::DataFrame);
for (int i = 0; i < canObject2.dlc; i++) bytes[i] = canObject2.data[i];
}
//Should we divide by a thousand or a million? Unsure here. It appears some logs are stamped in microseconds and some in milliseconds?
frame.setTimeStamp(QCanBusFrame::TimeStamp(0, obj.header.v1Obj.uncompSize / 1000.0)); //uncompsize field also used for timestamp oddly enough
frames->append(frame);
}
else
{
qDebug() << "Not a can frame! ObjType: " << obj.header.base.objType;
if (obj.header.base.objType > 0xFFFF)
return false;
}
pos += obj.header.base.objSize + (obj.header.base.objSize % 4);
}
else
{
qDebug() << "Unexpected object header signature, aborting";
return false;
}
}
uncompressedData.remove(0, pos);
qDebug() << "After removing used data uncompressedData is now this big: " << uncompressedData.count();
break;
}
}
else return false;
}
return true;
}
bool BLFHandler::saveBLF(QString filename, QVector<CANFrame> *frames)
{
Q_UNUSED(filename)
Q_UNUSED(frames)
return false;
}
<|endoftext|>
|
<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_RANK_HPP
#define STAN_MATH_PRIM_MAT_FUN_RANK_HPP
#include <stan/math/prim/mat/err/check_range.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <vector>
namespace stan {
namespace math {
/**
* Return the number of components of v less than v[s].
*
* @tparam T Type of elements.
* @param[in] v Input vector.
* @param[in] s Position in vector.
* @return Number of components of v less than v[s].
*/
template <typename T>
inline int rank(const std::vector<T> & v, int s) {
using stan::math::check_range;
int size = static_cast<int>(v.size());
check_range("rank", "v", size, s);
--s;
int count(0U);
T compare(v[s]);
for (int i = 0U; i < size; ++i)
if (v[i] < compare)
++count;
return count;
}
/**
* Return the number of components of v less than v[s].
*
* @tparam T Type of elements of the vector.
* @param[in] v Input vector.
* @param s Index for input vector.
* @return Number of components of v less than v[s].
*/
template <typename T, int R, int C>
inline int rank(const Eigen::Matrix<T, R, C> & v, int s) {
using stan::math::check_range;
int size = v.size();
check_range("rank", "v", size, s);
--s;
const T * vv = v.data();
int count(0U);
T compare(vv[s]);
for (int i = 0U; i < size; ++i)
if (vv[i] < compare)
++count;
return count;
}
}
}
#endif
<commit_msg>removed unsigned qualifiers from rank function<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_RANK_HPP
#define STAN_MATH_PRIM_MAT_FUN_RANK_HPP
#include <stan/math/prim/mat/err/check_range.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <vector>
namespace stan {
namespace math {
/**
* Return the number of components of v less than v[s].
*
* @tparam T Type of elements.
* @param[in] v Input vector.
* @param[in] s Position in vector.
* @return Number of components of v less than v[s].
*/
template <typename T>
inline int rank(const std::vector<T> & v, int s) {
using stan::math::check_range;
int size = static_cast<int>(v.size());
check_range("rank", "v", size, s);
--s;
int count(0);
T compare(v[s]);
for (int i = 0; i < size; ++i)
if (v[i] < compare)
++count;
return count;
}
/**
* Return the number of components of v less than v[s].
*
* @tparam T Type of elements of the vector.
* @param[in] v Input vector.
* @param s Index for input vector.
* @return Number of components of v less than v[s].
*/
template <typename T, int R, int C>
inline int rank(const Eigen::Matrix<T, R, C> & v, int s) {
using stan::math::check_range;
int size = v.size();
check_range("rank", "v", size, s);
--s;
const T * vv = v.data();
int count(0);
T compare(vv[s]);
for (int i = 0; i < size; ++i)
if (vv[i] < compare)
++count;
return count;
}
}
}
#endif
<|endoftext|>
|
<commit_before><commit_msg>docx m:r can contain multiple m:t<commit_after><|endoftext|>
|
<commit_before>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnordmetric/sstable/binaryformat.h>
#include <fnordmetric/sstable/livesstable.h>
#include <fnordmetric/util/runtimeexception.h>
namespace fnord {
namespace sstable {
std::unique_ptr<LiveSSTable> LiveSSTable::create(
io::File file,
IndexProvider index_provider,
void const* header,
size_t header_size) {
if (file.size() > 0) {
RAISE(kIllegalStateError, "file size must be 0");
}
auto sstable = new LiveSSTable(std::move(file), index_provider.popIndexes());
sstable->writeHeader(header, header_size);
return std::unique_ptr<LiveSSTable>(sstable);
}
std::unique_ptr<LiveSSTable> LiveSSTable::reopen(
io::File file,
IndexProvider index_provider) {
auto sstable = new LiveSSTable(std::move(file), index_provider.popIndexes());
return std::unique_ptr<LiveSSTable>(sstable);
}
LiveSSTable::LiveSSTable(
io::File&& file,
std::vector<Index::IndexRef>&& indexes) :
file_(std::move(file)),
indexes_(std::move(indexes)),
mmap_(new io::MmapPageManager(file_.fd(), file_.size(), 1)),
header_size_(0),
body_size_(0) {}
LiveSSTable::~LiveSSTable() {
}
// FIXPAUL lock
void LiveSSTable::appendRow(
void const* key,
size_t key_size,
void const* data,
size_t data_size) {
// assert that key is monotonically increasing...
size_t page_size = sizeof(BinaryFormat::RowHeader) + key_size + data_size;
auto alloc = mmap_->allocPage(page_size);
auto page = mmap_->getPage(alloc);
auto header = page->structAt<BinaryFormat::RowHeader>(0);
header->key_size = key_size;
header->data_size = data_size;
auto key_dst = page->structAt<void>(sizeof(BinaryFormat::RowHeader));
memcpy(key_dst, key, key_size);
auto data_dst = page->structAt<void>(
sizeof(BinaryFormat::RowHeader) + key_size);
memcpy(data_dst, data, data_size);
page->sync();
body_size_ += page_size;
}
void LiveSSTable::appendRow(
const std::string& key,
const std::string& value) {
appendRow(key.data(), key.size(), value.data(), value.size());
}
// FIXPAUL lock
void LiveSSTable::writeHeader(void const* data, size_t size) {
auto alloc = mmap_->allocPage(sizeof(BinaryFormat::FileHeader) + size);
auto page = mmap_->getPage(alloc);
if (alloc.offset != 0) {
RAISE(kIllegalStateError, "header page offset must be 0");
}
auto header = page->structAt<BinaryFormat::FileHeader>(0);
header->magic = BinaryFormat::kMagicBytes;
header->body_size = 0;
header->header_size = size;
if (size > 0) {
auto userdata = page->structAt<void>(sizeof(BinaryFormat::FileHeader));
memcpy(userdata, data, size);
}
page->sync();
header_size_ = alloc.size;
}
// FIXPAUL lock
void LiveSSTable::finalize() {
auto page = mmap_->getPage(
io::PageManager::Page(0, sizeof(BinaryFormat::FileHeader)));
auto header = page->structAt<BinaryFormat::FileHeader>(0);
header->body_size = body_size_;
}
// FIXPAUL lock
std::unique_ptr<Cursor> LiveSSTable::getCursor() {
return std::unique_ptr<Cursor>(
new LiveSSTable::Cursor(this, mmap_.get()));
}
// FIXPAUL lock
size_t LiveSSTable::bodySize() const {
return body_size_;
}
size_t LiveSSTable::headerSize() const {
return header_size_;
}
LiveSSTable::Cursor::Cursor(
LiveSSTable* table,
io::MmapPageManager* mmap) :
table_(table),
mmap_(mmap),
pos_(0) {}
void LiveSSTable::Cursor::seekTo(size_t body_offset) {
if (body_offset >= table_->bodySize()) {
RAISE(kIndexError, "seekTo() out of bounds position");
}
pos_ = body_offset;
}
bool LiveSSTable::Cursor::next() {
auto page = getPage();
}
void LiveSSTable::Cursor::getKey(void** data, size_t* size) {
auto page = getPage();
}
void LiveSSTable::Cursor::getData(void** data, size_t* size) {
auto page = getPage();
}
std::unique_ptr<io::PageManager::PageRef> LiveSSTable::Cursor::getPage() {
return mmap_->getPage(io::PageManager::Page(
table_->headerSize() + pos_,
table_->bodySize() - pos_));
}
}
}
<commit_msg>impl LiveSSTable::Cursor<commit_after>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnordmetric/sstable/binaryformat.h>
#include <fnordmetric/sstable/livesstable.h>
#include <fnordmetric/util/runtimeexception.h>
namespace fnord {
namespace sstable {
std::unique_ptr<LiveSSTable> LiveSSTable::create(
io::File file,
IndexProvider index_provider,
void const* header,
size_t header_size) {
if (file.size() > 0) {
RAISE(kIllegalStateError, "file size must be 0");
}
auto sstable = new LiveSSTable(std::move(file), index_provider.popIndexes());
sstable->writeHeader(header, header_size);
return std::unique_ptr<LiveSSTable>(sstable);
}
std::unique_ptr<LiveSSTable> LiveSSTable::reopen(
io::File file,
IndexProvider index_provider) {
auto sstable = new LiveSSTable(std::move(file), index_provider.popIndexes());
return std::unique_ptr<LiveSSTable>(sstable);
}
LiveSSTable::LiveSSTable(
io::File&& file,
std::vector<Index::IndexRef>&& indexes) :
file_(std::move(file)),
indexes_(std::move(indexes)),
mmap_(new io::MmapPageManager(file_.fd(), file_.size(), 1)),
header_size_(0),
body_size_(0) {}
LiveSSTable::~LiveSSTable() {
}
// FIXPAUL lock
void LiveSSTable::appendRow(
void const* key,
size_t key_size,
void const* data,
size_t data_size) {
// assert that key is monotonically increasing...
size_t page_size = sizeof(BinaryFormat::RowHeader) + key_size + data_size;
auto alloc = mmap_->allocPage(page_size);
auto page = mmap_->getPage(alloc);
auto header = page->structAt<BinaryFormat::RowHeader>(0);
header->key_size = key_size;
header->data_size = data_size;
auto key_dst = page->structAt<void>(sizeof(BinaryFormat::RowHeader));
memcpy(key_dst, key, key_size);
auto data_dst = page->structAt<void>(
sizeof(BinaryFormat::RowHeader) + key_size);
memcpy(data_dst, data, data_size);
page->sync();
body_size_ += page_size;
}
void LiveSSTable::appendRow(
const std::string& key,
const std::string& value) {
appendRow(key.data(), key.size(), value.data(), value.size());
}
// FIXPAUL lock
void LiveSSTable::writeHeader(void const* data, size_t size) {
auto alloc = mmap_->allocPage(sizeof(BinaryFormat::FileHeader) + size);
auto page = mmap_->getPage(alloc);
if (alloc.offset != 0) {
RAISE(kIllegalStateError, "header page offset must be 0");
}
auto header = page->structAt<BinaryFormat::FileHeader>(0);
header->magic = BinaryFormat::kMagicBytes;
header->body_size = 0;
header->header_size = size;
if (size > 0) {
auto userdata = page->structAt<void>(sizeof(BinaryFormat::FileHeader));
memcpy(userdata, data, size);
}
page->sync();
header_size_ = alloc.size;
}
// FIXPAUL lock
void LiveSSTable::finalize() {
auto page = mmap_->getPage(
io::PageManager::Page(0, sizeof(BinaryFormat::FileHeader)));
auto header = page->structAt<BinaryFormat::FileHeader>(0);
header->body_size = body_size_;
}
// FIXPAUL lock
std::unique_ptr<Cursor> LiveSSTable::getCursor() {
return std::unique_ptr<Cursor>(
new LiveSSTable::Cursor(this, mmap_.get()));
}
// FIXPAUL lock
size_t LiveSSTable::bodySize() const {
return body_size_;
}
size_t LiveSSTable::headerSize() const {
return header_size_;
}
LiveSSTable::Cursor::Cursor(
LiveSSTable* table,
io::MmapPageManager* mmap) :
table_(table),
mmap_(mmap),
pos_(0) {}
void LiveSSTable::Cursor::seekTo(size_t body_offset) {
if (body_offset >= table_->bodySize()) {
RAISE(kIndexError, "seekTo() out of bounds position");
}
pos_ = body_offset;
}
bool LiveSSTable::Cursor::next() {
auto page = getPage();
auto header = page->structAt<BinaryFormat::RowHeader>(0);
size_t page_size = page->page_.size;
size_t row_size = sizeof(BinaryFormat::RowHeader) + header->key_size +
header->data_size;
if (row_size > page_size) {
RAISE(kIllegalStateError, "row exceeds page boundary");
}
if (row_size == page_size) {
return false;
} else {
pos_ += row_size;
return true;
}
}
void LiveSSTable::Cursor::getKey(void** data, size_t* size) {
auto page = getPage();
size_t page_size = page->page_.size;
auto header = page->structAt<BinaryFormat::RowHeader>(0);
if (header->key_size == 0) {
RAISE(kIllegalStateError, "empty key");
}
if (sizeof(BinaryFormat::RowHeader) + header->key_size > page_size) {
RAISE(kIllegalStateError, "key exceeds page boundary");
}
*data = page->structAt<void>(sizeof(BinaryFormat::RowHeader));
*size = header->key_size;
}
void LiveSSTable::Cursor::getData(void** data, size_t* size) {
auto page = getPage();
auto header = page->structAt<BinaryFormat::RowHeader>(0);
size_t page_size = page->page_.size;
size_t row_size = sizeof(BinaryFormat::RowHeader) + header->key_size +
header->data_size;
if (row_size > page_size) {
RAISE(kIllegalStateError, "row exceeds page boundary");
}
*data = page->structAt<void>(
sizeof(BinaryFormat::RowHeader) + header->key_size);
*size = header->data_size;
}
std::unique_ptr<io::PageManager::PageRef> LiveSSTable::Cursor::getPage() {
return mmap_->getPage(io::PageManager::Page(
table_->headerSize() + pos_,
table_->bodySize() - pos_));
}
}
}
<|endoftext|>
|
<commit_before>//
// Use 'addr2line -e program ADDR' in order to decode addresses in stack frames.
// Use 'c++filt -t SYMBOL' in order to decode C++ mangled symbols like "Ss".
//
#include <stack/StackHandler.h>
#include <core/Options.h>
#include <core/System.h>
#include <core/Logger.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>
#include <execinfo.h>
#include <cxxabi.h>
#include <string>
#define THREAD_ID_LENGTH 20
using namespace exray;
pthread_mutex_t StackHandler::dumpLock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutexattr_t StackHandler::lockAttr;
bool StackHandler::active = false;
bool StackHandler::exitCalled = false;
regex_t StackHandler::framePattern;
/*
* Regex pattern for a stack frame from backtrace_symbols()
* used to extract the function name from a frame.
*
* Example frame string:
* /usr/lib64/libreoffice/program/libucbhelper.so(_ZN9ucbhelper7Content16getPropertyValueERKN3rtl8OUStringE+0xa6) [0x7feb400bedf6]
*
* Match groups
* 0 1 2 3
* ^([^(]+)\\(([^\\+]*)(\\+.*)$
*
* 0: Entire string
* 1: Shared library or program name
* 2: Function name (before the + sign), which may or may not be mangled
* 3: The rest
*/
static const char *FRAME_PATTERN_REGEX = "^([^(]+)\\(([^\\+]*)(\\+.*)$";
void StackHandler::init()
{
pthread_mutexattr_init(&lockAttr);
pthread_mutexattr_settype(&lockAttr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&dumpLock, &lockAttr);
regcomp(&StackHandler::framePattern, FRAME_PATTERN_REGEX, REG_EXTENDED);
StackHandler::active = true;
}
void StackHandler::finish()
{
active = false;
pthread_mutex_destroy(&dumpLock);
}
void StackHandler::setExitCalled()
{
exitCalled = true;
}
StackHandler::StackHandler()
{
gettimeofday(×tamp, NULL);
snprintf(threadID, THREAD_ID_LENGTH, "%d[%d] ", getpid(), System::gettid());
this->traceStrings = NULL;
this->frameCount = 0;
}
StackHandler::~StackHandler()
{
}
// Ignore the first 2 frames that belong to this library
#define SKIP_FRAMES 2
void StackHandler::dumpMangled(int loop, char *traceString[])
{
int currentFrame = SKIP_FRAMES;
for (int i = 1; i <= loop; i++, currentFrame++) {
Logger::printf("%s#%d: %s\n", threadID, i, this->traceStrings[currentFrame]);
}
}
/**
* Convert a mangled C++ function name into human readable string.
*
* @return string containing demangled frame string.
*/
std::string StackHandler::demangleFrame(char *frame)
{
std::string result;
regmatch_t pmatch[REGEX_BUFFER];
int ret = regexec(&framePattern, frame, REGEX_BUFFER, pmatch, 0);
if (ret != 0) {
// probably not a mangled name
return result;
}
int begin = pmatch[2].rm_so;
int end = pmatch[2].rm_eo;
int length = end - begin + 1;
if (length <= 1) {
// there may be no function name in the frame
return result;
}
char *mangled = new char[length];
int destIndex = 0, srcIndex = 0;
for (srcIndex = begin; srcIndex < end; srcIndex++) {
mangled[destIndex++] = frame[srcIndex];
}
mangled[destIndex] = '\0';
int status;
char *demangled = abi::__cxa_demangle(mangled, NULL, NULL, &status);
delete[] mangled;
if (status != 0) { // demangle failed
return result;
}
// copy library or program name
for (srcIndex = pmatch[1].rm_so; srcIndex <= pmatch[1].rm_eo; srcIndex++) {
result.push_back(frame[srcIndex]);
}
// copy demangled function
int demangledLength = strlen(demangled);
for (srcIndex = 0; srcIndex < demangledLength; srcIndex++) {
result.push_back(demangled[srcIndex]);
}
free(demangled);
// copy the rest
for (srcIndex = pmatch[3].rm_so; srcIndex < pmatch[3].rm_eo; srcIndex++) {
result.push_back(frame[srcIndex]);
}
return result;
}
void StackHandler::dumpDemangled(int loop, char *traceString[])
{
int currentFrame = SKIP_FRAMES;
for (int i = 1; i <= loop; i++, currentFrame++) {
std::string demangled = demangleFrame(this->traceStrings[currentFrame]);
if (demangled.length() == 0) {
Logger::printf("%s#%d: %s\n", threadID, i, this->traceStrings[currentFrame]);
}
else {
Logger::printf("%s#%d: %s\n", threadID, i, demangled.c_str());
}
}
}
void StackHandler::dumpVerboseFrames() {
if (frameCount <= SKIP_FRAMES || traceStrings == NULL)
return;
int depth = frameCount - SKIP_FRAMES;
Logger::printf("%sStack Frames\n", threadID);
int loop = (Options::maxFrames < depth) ? Options::maxFrames : depth;
if (Options::demangleFunction) {
dumpDemangled(loop, traceStrings);
}
else {
dumpMangled(loop, traceStrings);
}
free(this->traceStrings);
this->traceStrings = NULL;
}
void StackHandler::captureFrames()
{
// avoid deadlock/infinite loop
if (System::threadInBacktrace() || System::isThreadUnwinding())
return;
System::setBacktraceFlag();
gettimeofday(&this->timestamp, NULL);
this->frameCount = backtrace(this->frames, STACKSIZE);
if (this->traceStrings != NULL)
free(this->traceStrings);
this->traceStrings = backtrace_symbols(this->frames, this->frameCount);
System::clearBacktraceFlag();
}
<commit_msg>minor change<commit_after>//
// Use 'addr2line -e program ADDR' in order to decode addresses in stack frames.
// Use 'c++filt -t SYMBOL' in order to decode C++ mangled symbols like "Ss".
//
#include <stack/StackHandler.h>
#include <core/Options.h>
#include <core/System.h>
#include <core/Logger.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>
#include <execinfo.h>
#include <cxxabi.h>
#include <string>
#define THREAD_ID_LENGTH 20
using namespace exray;
pthread_mutex_t StackHandler::dumpLock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutexattr_t StackHandler::lockAttr;
bool StackHandler::active = false;
bool StackHandler::exitCalled = false;
regex_t StackHandler::framePattern;
/*
* Regex pattern for a stack frame from backtrace_symbols()
* used to extract the function name from a frame.
*
* Example frame string:
* /usr/lib64/libreoffice/program/libucbhelper.so(_ZN9ucbhelper7Content16getPropertyValueERKN3rtl8OUStringE+0xa6) [0x7feb400bedf6]
*
* Match groups
* 0 1 2 3
* ^([^(]+)\\(([^\\+]*)(\\+.*)$
*
* 0: Entire string
* 1: Shared library or program name
* 2: Function name (before the + sign), which may or may not be mangled
* 3: The rest
*/
static const char *FRAME_PATTERN_REGEX = "^([^(]+)\\(([^\\+]*)(\\+.*)$";
void StackHandler::init()
{
pthread_mutexattr_init(&lockAttr);
pthread_mutexattr_settype(&lockAttr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&dumpLock, &lockAttr);
regcomp(&StackHandler::framePattern, FRAME_PATTERN_REGEX, REG_EXTENDED);
StackHandler::active = true;
}
void StackHandler::finish()
{
active = false;
pthread_mutex_destroy(&dumpLock);
}
void StackHandler::setExitCalled()
{
exitCalled = true;
}
StackHandler::StackHandler()
{
gettimeofday(×tamp, NULL);
snprintf(threadID, THREAD_ID_LENGTH, "%d[%d] ", getpid(), System::gettid());
this->traceStrings = NULL;
this->frameCount = 0;
}
StackHandler::~StackHandler()
{
}
// Ignore the first 2 frames that belong to this library
#define SKIP_FRAMES 2
void StackHandler::dumpMangled(int loop, char *traceString[])
{
int currentFrame = SKIP_FRAMES;
for (int i = 1; i <= loop; i++, currentFrame++) {
Logger::printf("%s#%d: %s\n", threadID, i, this->traceStrings[currentFrame]);
}
}
/**
* Convert a mangled C++ function name into human readable string.
*
* @return string containing demangled frame string.
*/
std::string StackHandler::demangleFrame(char *frame)
{
std::string result;
regmatch_t pmatch[REGEX_BUFFER];
int ret = regexec(&framePattern, frame, REGEX_BUFFER, pmatch, 0);
if (ret != 0) {
// probably not a mangled name
return result;
}
int begin = pmatch[2].rm_so;
int end = pmatch[2].rm_eo;
int length = end - begin + 1;
if (length <= 1) {
// there may be no function name in the frame
return result;
}
char *mangled = new char[length];
int destIndex = 0, srcIndex = 0;
for (srcIndex = begin; srcIndex < end; srcIndex++) {
mangled[destIndex++] = frame[srcIndex];
}
mangled[destIndex] = '\0';
int status;
char *demangled = abi::__cxa_demangle(mangled, NULL, NULL, &status);
delete[] mangled;
if (status != 0) { // demangle failed
return result;
}
// copy library or program name
result.append(frame+pmatch[1].rm_so, (pmatch[1].rm_eo - pmatch[1].rm_so + 1));
// copy demangled function
result.append(demangled);
// copy the rest
result.append(frame+pmatch[3].rm_so, (pmatch[3].rm_eo - pmatch[3].rm_so + 1));
return result;
}
void StackHandler::dumpDemangled(int loop, char *traceString[])
{
int currentFrame = SKIP_FRAMES;
for (int i = 1; i <= loop; i++, currentFrame++) {
std::string demangled = demangleFrame(this->traceStrings[currentFrame]);
if (demangled.length() == 0) {
Logger::printf("%s#%d: %s\n", threadID, i, this->traceStrings[currentFrame]);
}
else {
Logger::printf("%s#%d: %s\n", threadID, i, demangled.c_str());
}
}
}
void StackHandler::dumpVerboseFrames() {
if (frameCount <= SKIP_FRAMES || traceStrings == NULL)
return;
int depth = frameCount - SKIP_FRAMES;
Logger::printf("%sStack Frames\n", threadID);
int loop = (Options::maxFrames < depth) ? Options::maxFrames : depth;
if (Options::demangleFunction) {
dumpDemangled(loop, traceStrings);
}
else {
dumpMangled(loop, traceStrings);
}
free(this->traceStrings);
this->traceStrings = NULL;
}
void StackHandler::captureFrames()
{
// avoid deadlock/infinite loop
if (System::threadInBacktrace() || System::isThreadUnwinding())
return;
System::setBacktraceFlag();
gettimeofday(&this->timestamp, NULL);
this->frameCount = backtrace(this->frames, STACKSIZE);
if (this->traceStrings != NULL)
free(this->traceStrings);
this->traceStrings = backtrace_symbols(this->frames, this->frameCount);
System::clearBacktraceFlag();
}
<|endoftext|>
|
<commit_before>/** ==========================================================================
* Original code made by Robert Engeln. Given as a PUBLIC DOMAIN dedication for
* the benefit of g3log. It was originally published at:
* http://code-freeze.blogspot.com/2012/01/generating-stack-traces-from-c.html
* 2014-2015: adapted for g3log by Kjell Hedstrom (KjellKod).
*
* This is PUBLIC DOMAIN to use at your own risk and comes
* with no warranties. This code is yours to share, use and modify with no
* strings attached and no restrictions or obligations.
*
* For more information see g3log/LICENSE or refer refer to http://unlicense.org
* ============================================================================*/
#include "g3log/stacktrace_windows.hpp"
#include <windows.h>
#include <dbghelp.h>
#include <map>
#include <memory>
#include <cassert>
#include <vector>
#include <mutex>
#include <g3log/g3log.hpp>
#pragma comment(lib, "dbghelp.lib")
#if !(defined(WIN32) || defined(_WIN32) || defined(__WIN32__))
#error "stacktrace_win.cpp used but not on a windows system"
#endif
#define g3_MAP_PAIR_STRINGIFY(x) {x, #x}
namespace {
thread_local size_t g_thread_local_recursive_crash_check = 0;
const std::map<g3::SignalType, std::string> kExceptionsAsText = {
g3_MAP_PAIR_STRINGIFY(EXCEPTION_ACCESS_VIOLATION)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_ARRAY_BOUNDS_EXCEEDED)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_DATATYPE_MISALIGNMENT)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_DENORMAL_OPERAND)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_DIVIDE_BY_ZERO)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_INEXACT_RESULT)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_INEXACT_RESULT)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_INVALID_OPERATION)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_OVERFLOW)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_STACK_CHECK)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_UNDERFLOW)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_ILLEGAL_INSTRUCTION)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_IN_PAGE_ERROR)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_INT_DIVIDE_BY_ZERO)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_INT_OVERFLOW)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_INVALID_DISPOSITION)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_NONCONTINUABLE_EXCEPTION)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_PRIV_INSTRUCTION)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_STACK_OVERFLOW)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_BREAKPOINT)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_SINGLE_STEP)
};
// Using the given context, fill in all the stack frames.
// Which then later can be interpreted to human readable text
void captureStackTrace(CONTEXT *context, std::vector<uint64_t> &frame_pointers) {
DWORD machine_type = 0;
STACKFRAME64 frame = {}; // force zeroeing
frame.AddrPC.Mode = AddrModeFlat;
frame.AddrFrame.Mode = AddrModeFlat;
frame.AddrStack.Mode = AddrModeFlat;
#ifdef _M_X64
frame.AddrPC.Offset = context->Rip;
frame.AddrFrame.Offset = context->Rbp;
frame.AddrStack.Offset = context->Rsp;
machine_type = IMAGE_FILE_MACHINE_AMD64;
#else
frame.AddrPC.Offset = context->Eip;
frame.AddrPC.Offset = context->Ebp;
frame.AddrPC.Offset = context->Esp;
machine_type = IMAGE_FILE_MACHINE_I386;
#endif
for (size_t index = 0; index < frame_pointers.size(); ++index)
{
if (StackWalk64(machine_type,
GetCurrentProcess(),
GetCurrentThread(),
&frame,
context,
NULL,
SymFunctionTableAccess64,
SymGetModuleBase64,
NULL)) {
frame_pointers[index] = frame.AddrPC.Offset;
} else {
break;
}
}
}
// extract readable text from a given stack frame. All thanks to
// using SymFromAddr and SymGetLineFromAddr64 with the stack pointer
std::string getSymbolInformation(const size_t index, const std::vector<uint64_t> &frame_pointers) {
auto addr = frame_pointers[index];
std::string frame_dump = "stack dump [" + std::to_string(index) + "]\t";
DWORD64 displacement64;
DWORD displacement;
char symbol_buffer[sizeof(SYMBOL_INFO) + 256];
SYMBOL_INFO *symbol = reinterpret_cast<SYMBOL_INFO *>(symbol_buffer);
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
symbol->MaxNameLen = MAX_SYM_NAME;
IMAGEHLP_LINE64 line;
line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
std::string lineInformation;
std::string callInformation;
if (SymFromAddr(GetCurrentProcess(), addr, &displacement64, symbol)) {
callInformation.append(" ").append({symbol->Name, symbol->NameLen});
if (SymGetLineFromAddr64(GetCurrentProcess(), addr, &displacement, &line)) {
lineInformation.append("\t").append(line.FileName).append(" L: ");
lineInformation.append(std::to_string(line.LineNumber));
}
}
frame_dump.append(lineInformation).append(callInformation);
return frame_dump;
}
// Retrieves all the symbols for the stack frames, fills them witin a text representation and returns it
std::string convertFramesToText(std::vector<uint64_t> &frame_pointers) {
std::string dump; // slightly more efficient than ostringstream
const size_t kSize = frame_pointers.size();
for (size_t index = 0; index < kSize && frame_pointers[index]; ++index) {
dump += getSymbolInformation(index, frame_pointers);
dump += "\n";
}
return dump;
}
} // anonymous
namespace stacktrace {
const std::string kUnknown = {"UNKNOWN EXCEPTION"};
/// return the text description of a Windows exception code
/// From MSDN GetExceptionCode http://msdn.microsoft.com/en-us/library/windows/desktop/ms679356(v=vs.85).aspx
std::string exceptionIdToText(g3::SignalType id) {
const auto iter = kExceptionsAsText.find(id);
if ( iter == kExceptionsAsText.end()) {
std::string unknown = {kUnknown + ":" + std::to_string(id)};
return unknown;
}
return iter->second;
}
/// Yes a double lookup: first for isKnownException and then exceptionIdToText
/// for vectored exceptions we only deal with known exceptions so this tiny
/// overhead we can live with
bool isKnownException(g3::SignalType id) {
return (kExceptionsAsText.end() != kExceptionsAsText.find(id));
}
/// helper function: retrieve stackdump from no excisting exception pointer
std::string stackdump() {
CONTEXT current_context;
memset(¤t_context, 0, sizeof(CONTEXT));
RtlCaptureContext(¤t_context);
return stackdump(¤t_context);
}
/// helper function: retrieve stackdump, starting from an exception pointer
std::string stackdump(EXCEPTION_POINTERS *info) {
auto context = info->ContextRecord;
return stackdump(context);
}
/// main stackdump function. retrieve stackdump, from the given context
std::string stackdump(CONTEXT *context) {
if (g_thread_local_recursive_crash_check >= 2) { // In Debug scenarious we allow one extra pass
std::string recursive_crash = {"\n\n\n***** Recursive crash detected"};
recursive_crash.append(", cannot continue stackdump traversal. *****\n\n\n");
return recursive_crash;
}
++g_thread_local_recursive_crash_check;
static std::mutex m;
std::lock_guard<std::mutex> lock(m);
{
const BOOL kLoadSymModules = TRUE;
const auto initialized = SymInitialize(GetCurrentProcess(), nullptr, kLoadSymModules);
if (TRUE != initialized) {
return { "Error: Cannot call SymInitialize(...) for retrieving symbols in stack" };
}
std::shared_ptr<void> RaiiSymCleaner(nullptr, [&](void *) {
SymCleanup(GetCurrentProcess());
}); // Raii sym cleanup
const size_t kmax_frame_dump_size = 64;
std::vector<uint64_t> frame_pointers(kmax_frame_dump_size);
// C++11: size set and values are zeroed
assert(frame_pointers.size() == kmax_frame_dump_size);
captureStackTrace(context, frame_pointers);
return convertFramesToText(frame_pointers);
}
}
} // stacktrace
<commit_msg>Fixed ambiguous constructor error. (#262)<commit_after>/** ==========================================================================
* Original code made by Robert Engeln. Given as a PUBLIC DOMAIN dedication for
* the benefit of g3log. It was originally published at:
* http://code-freeze.blogspot.com/2012/01/generating-stack-traces-from-c.html
* 2014-2015: adapted for g3log by Kjell Hedstrom (KjellKod).
*
* This is PUBLIC DOMAIN to use at your own risk and comes
* with no warranties. This code is yours to share, use and modify with no
* strings attached and no restrictions or obligations.
*
* For more information see g3log/LICENSE or refer refer to http://unlicense.org
* ============================================================================*/
#include "g3log/stacktrace_windows.hpp"
#include <windows.h>
#include <dbghelp.h>
#include <map>
#include <memory>
#include <cassert>
#include <vector>
#include <mutex>
#include <g3log/g3log.hpp>
#pragma comment(lib, "dbghelp.lib")
#if !(defined(WIN32) || defined(_WIN32) || defined(__WIN32__))
#error "stacktrace_win.cpp used but not on a windows system"
#endif
#define g3_MAP_PAIR_STRINGIFY(x) {x, #x}
namespace {
thread_local size_t g_thread_local_recursive_crash_check = 0;
const std::map<g3::SignalType, std::string> kExceptionsAsText = {
g3_MAP_PAIR_STRINGIFY(EXCEPTION_ACCESS_VIOLATION)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_ARRAY_BOUNDS_EXCEEDED)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_DATATYPE_MISALIGNMENT)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_DENORMAL_OPERAND)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_DIVIDE_BY_ZERO)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_INEXACT_RESULT)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_INEXACT_RESULT)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_INVALID_OPERATION)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_OVERFLOW)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_STACK_CHECK)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_UNDERFLOW)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_ILLEGAL_INSTRUCTION)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_IN_PAGE_ERROR)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_INT_DIVIDE_BY_ZERO)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_INT_OVERFLOW)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_INVALID_DISPOSITION)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_NONCONTINUABLE_EXCEPTION)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_PRIV_INSTRUCTION)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_STACK_OVERFLOW)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_BREAKPOINT)
, g3_MAP_PAIR_STRINGIFY(EXCEPTION_SINGLE_STEP)
};
// Using the given context, fill in all the stack frames.
// Which then later can be interpreted to human readable text
void captureStackTrace(CONTEXT *context, std::vector<uint64_t> &frame_pointers) {
DWORD machine_type = 0;
STACKFRAME64 frame = {}; // force zeroeing
frame.AddrPC.Mode = AddrModeFlat;
frame.AddrFrame.Mode = AddrModeFlat;
frame.AddrStack.Mode = AddrModeFlat;
#ifdef _M_X64
frame.AddrPC.Offset = context->Rip;
frame.AddrFrame.Offset = context->Rbp;
frame.AddrStack.Offset = context->Rsp;
machine_type = IMAGE_FILE_MACHINE_AMD64;
#else
frame.AddrPC.Offset = context->Eip;
frame.AddrPC.Offset = context->Ebp;
frame.AddrPC.Offset = context->Esp;
machine_type = IMAGE_FILE_MACHINE_I386;
#endif
for (size_t index = 0; index < frame_pointers.size(); ++index)
{
if (StackWalk64(machine_type,
GetCurrentProcess(),
GetCurrentThread(),
&frame,
context,
NULL,
SymFunctionTableAccess64,
SymGetModuleBase64,
NULL)) {
frame_pointers[index] = frame.AddrPC.Offset;
} else {
break;
}
}
}
// extract readable text from a given stack frame. All thanks to
// using SymFromAddr and SymGetLineFromAddr64 with the stack pointer
std::string getSymbolInformation(const size_t index, const std::vector<uint64_t> &frame_pointers) {
auto addr = frame_pointers[index];
std::string frame_dump = "stack dump [" + std::to_string(index) + "]\t";
DWORD64 displacement64;
DWORD displacement;
char symbol_buffer[sizeof(SYMBOL_INFO) + 256];
SYMBOL_INFO *symbol = reinterpret_cast<SYMBOL_INFO *>(symbol_buffer);
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
symbol->MaxNameLen = MAX_SYM_NAME;
IMAGEHLP_LINE64 line;
line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
std::string lineInformation;
std::string callInformation;
if (SymFromAddr(GetCurrentProcess(), addr, &displacement64, symbol)) {
callInformation.append(" ").append({std::string(symbol->Name), symbol->NameLen});
if (SymGetLineFromAddr64(GetCurrentProcess(), addr, &displacement, &line)) {
lineInformation.append("\t").append(line.FileName).append(" L: ");
lineInformation.append(std::to_string(line.LineNumber));
}
}
frame_dump.append(lineInformation).append(callInformation);
return frame_dump;
}
// Retrieves all the symbols for the stack frames, fills them witin a text representation and returns it
std::string convertFramesToText(std::vector<uint64_t> &frame_pointers) {
std::string dump; // slightly more efficient than ostringstream
const size_t kSize = frame_pointers.size();
for (size_t index = 0; index < kSize && frame_pointers[index]; ++index) {
dump += getSymbolInformation(index, frame_pointers);
dump += "\n";
}
return dump;
}
} // anonymous
namespace stacktrace {
const std::string kUnknown = {"UNKNOWN EXCEPTION"};
/// return the text description of a Windows exception code
/// From MSDN GetExceptionCode http://msdn.microsoft.com/en-us/library/windows/desktop/ms679356(v=vs.85).aspx
std::string exceptionIdToText(g3::SignalType id) {
const auto iter = kExceptionsAsText.find(id);
if ( iter == kExceptionsAsText.end()) {
std::string unknown = {kUnknown + ":" + std::to_string(id)};
return unknown;
}
return iter->second;
}
/// Yes a double lookup: first for isKnownException and then exceptionIdToText
/// for vectored exceptions we only deal with known exceptions so this tiny
/// overhead we can live with
bool isKnownException(g3::SignalType id) {
return (kExceptionsAsText.end() != kExceptionsAsText.find(id));
}
/// helper function: retrieve stackdump from no excisting exception pointer
std::string stackdump() {
CONTEXT current_context;
memset(¤t_context, 0, sizeof(CONTEXT));
RtlCaptureContext(¤t_context);
return stackdump(¤t_context);
}
/// helper function: retrieve stackdump, starting from an exception pointer
std::string stackdump(EXCEPTION_POINTERS *info) {
auto context = info->ContextRecord;
return stackdump(context);
}
/// main stackdump function. retrieve stackdump, from the given context
std::string stackdump(CONTEXT *context) {
if (g_thread_local_recursive_crash_check >= 2) { // In Debug scenarious we allow one extra pass
std::string recursive_crash = {"\n\n\n***** Recursive crash detected"};
recursive_crash.append(", cannot continue stackdump traversal. *****\n\n\n");
return recursive_crash;
}
++g_thread_local_recursive_crash_check;
static std::mutex m;
std::lock_guard<std::mutex> lock(m);
{
const BOOL kLoadSymModules = TRUE;
const auto initialized = SymInitialize(GetCurrentProcess(), nullptr, kLoadSymModules);
if (TRUE != initialized) {
return { "Error: Cannot call SymInitialize(...) for retrieving symbols in stack" };
}
std::shared_ptr<void> RaiiSymCleaner(nullptr, [&](void *) {
SymCleanup(GetCurrentProcess());
}); // Raii sym cleanup
const size_t kmax_frame_dump_size = 64;
std::vector<uint64_t> frame_pointers(kmax_frame_dump_size);
// C++11: size set and values are zeroed
assert(frame_pointers.size() == kmax_frame_dump_size);
captureStackTrace(context, frame_pointers);
return convertFramesToText(frame_pointers);
}
}
} // stacktrace
<|endoftext|>
|
<commit_before>
//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// temp_table.cpp
//
// Identification: /peloton/src/storage/temp_table.cpp
//
// Copyright (c) 2015, 2016 Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "storage/temp_table.h"
#include "catalog/schema.h"
#include "common/exception.h"
#include "common/logger.h"
#include "storage/tile_group.h"
#include "storage/tile_group_header.h"
#include "storage/tuple.h"
namespace peloton {
namespace storage {
TempTable::TempTable(const oid_t &table_oid, catalog::Schema *schema,
const bool own_schema)
: AbstractTable(table_oid, schema, own_schema) {
// We only want to instantiate a single TileGroup
AddDefaultTileGroup();
}
TempTable::~TempTable() {
// Nothing to see, nothing to do
}
ItemPointer TempTable::InsertTuple(const Tuple *tuple,
concurrency::Transaction *transaction,
ItemPointer **index_entry_ptr) {
PL_ASSERT(tuple != nullptr);
PL_ASSERT(transaction == nullptr);
PL_ASSERT(index_entry_ptr == nullptr);
std::shared_ptr<storage::TileGroup> tile_group;
oid_t tuple_slot = INVALID_OID;
oid_t tile_group_id = INVALID_OID;
for (int i = 0, cnt = (int)tile_groups_.size(); i < cnt; i++) {
tile_group = tile_groups_[i];
tuple_slot = tile_group->InsertTuple(tuple);
// now we have already obtained a new tuple slot.
if (tuple_slot != INVALID_OID) {
tile_group_id = tile_group->GetTileGroupId();
LOG_TRACE("Inserted tuple into %s", GetName().c_str());
break;
}
}
// if this is the last tuple slot we can get
// then create a new tile group
if (tuple_slot == tile_group->GetAllocatedTupleCount() - 1) {
AddDefaultTileGroup();
}
if (tile_group_id == INVALID_OID) {
LOG_WARN("Failed to get tuple slot.");
return INVALID_ITEMPOINTER;
}
// Set tuple location and increase our counter
ItemPointer location(tile_group_id, tuple_slot);
IncreaseTupleCount(1);
// Make sure that we mark the tuple as active in the TileGroupHeader too
// If you don't do this, then anybody that tries to use a LogicalTile wrapper
// on this TempTable will not have any active tuples.
auto tile_group_header = tile_group->GetHeader();
tile_group_header->SetTransactionId(location.offset, INITIAL_TXN_ID);
return (location);
}
ItemPointer TempTable::InsertTuple(const Tuple *tuple) {
return (this->InsertTuple(tuple, nullptr, nullptr));
}
std::shared_ptr<storage::TileGroup> TempTable::GetTileGroup(
const std::size_t &tile_group_offset) const {
PL_ASSERT(tile_group_offset < GetTileGroupCount());
return (tile_groups_[tile_group_offset]);
}
std::shared_ptr<storage::TileGroup> TempTable::GetTileGroupById(
const oid_t &tile_group_id) const {
for (auto tg : tile_groups_) {
if (tg->GetTileGroupId() == tile_group_id) {
return (tg);
}
}
LOG_WARN("No TileGroup with id %d exists in %s", tile_group_id,
this->GetName().c_str());
return (nullptr);
}
oid_t TempTable::AddDefaultTileGroup() {
column_map_type column_map;
// Well, a TempTable doesn't really care about TileGroupIds
// And nobody else in the system should be referencing our boys directly,
// so we're just going to use a simple counter for these ids
// We need to do this because otherwise we will think that our inserts
// failed all the time if use INVALID_OID
oid_t tile_group_id =
TEMPTABLE_TILEGROUP_ID + static_cast<int>(tile_groups_.size());
// Figure out the partitioning for given tilegroup layout
column_map =
AbstractTable::GetTileGroupLayout((LayoutType)peloton_layout_mode);
// Create a tile group with that partitioning
std::shared_ptr<storage::TileGroup> tile_group(
AbstractTable::GetTileGroupWithLayout(
INVALID_OID, tile_group_id, column_map, TEMPTABLE_DEFAULT_SIZE));
PL_ASSERT(tile_group.get());
tile_groups_.push_back(tile_group);
LOG_TRACE("Created TileGroup for %s\n%s\n", GetName().c_str(),
tile_group->GetInfo().c_str());
return tile_group_id;
}
} // End storage namespace
} // End peloton namespace
<commit_msg>Switched to use UNUSED_ATTRIBUTE. Props to @jessesleeping<commit_after>
//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// temp_table.cpp
//
// Identification: /peloton/src/storage/temp_table.cpp
//
// Copyright (c) 2015, 2016 Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "storage/temp_table.h"
#include "catalog/schema.h"
#include "common/exception.h"
#include "common/logger.h"
#include "storage/tile_group.h"
#include "storage/tile_group_header.h"
#include "storage/tuple.h"
namespace peloton {
namespace storage {
TempTable::TempTable(const oid_t &table_oid, catalog::Schema *schema,
const bool own_schema)
: AbstractTable(table_oid, schema, own_schema) {
// We only want to instantiate a single TileGroup
AddDefaultTileGroup();
}
TempTable::~TempTable() {
// Nothing to see, nothing to do
}
ItemPointer TempTable::InsertTuple(
const Tuple *tuple, UNUSED_ATTRIBUTE concurrency::Transaction *transaction,
UNUSED_ATTRIBUTE ItemPointer **index_entry_ptr) {
PL_ASSERT(tuple != nullptr);
std::shared_ptr<storage::TileGroup> tile_group;
oid_t tuple_slot = INVALID_OID;
oid_t tile_group_id = INVALID_OID;
for (int i = 0, cnt = (int)tile_groups_.size(); i < cnt; i++) {
tile_group = tile_groups_[i];
tuple_slot = tile_group->InsertTuple(tuple);
// now we have already obtained a new tuple slot.
if (tuple_slot != INVALID_OID) {
tile_group_id = tile_group->GetTileGroupId();
LOG_TRACE("Inserted tuple into %s", GetName().c_str());
break;
}
}
// if this is the last tuple slot we can get
// then create a new tile group
if (tuple_slot == tile_group->GetAllocatedTupleCount() - 1) {
AddDefaultTileGroup();
}
if (tile_group_id == INVALID_OID) {
LOG_WARN("Failed to get tuple slot.");
return INVALID_ITEMPOINTER;
}
// Set tuple location and increase our counter
ItemPointer location(tile_group_id, tuple_slot);
IncreaseTupleCount(1);
// Make sure that we mark the tuple as active in the TileGroupHeader too
// If you don't do this, then anybody that tries to use a LogicalTile wrapper
// on this TempTable will not have any active tuples.
auto tile_group_header = tile_group->GetHeader();
tile_group_header->SetTransactionId(location.offset, INITIAL_TXN_ID);
return (location);
}
ItemPointer TempTable::InsertTuple(const Tuple *tuple) {
return (this->InsertTuple(tuple, nullptr, nullptr));
}
std::shared_ptr<storage::TileGroup> TempTable::GetTileGroup(
const std::size_t &tile_group_offset) const {
PL_ASSERT(tile_group_offset < GetTileGroupCount());
return (tile_groups_[tile_group_offset]);
}
std::shared_ptr<storage::TileGroup> TempTable::GetTileGroupById(
const oid_t &tile_group_id) const {
for (auto tg : tile_groups_) {
if (tg->GetTileGroupId() == tile_group_id) {
return (tg);
}
}
LOG_WARN("No TileGroup with id %d exists in %s", tile_group_id,
this->GetName().c_str());
return (nullptr);
}
oid_t TempTable::AddDefaultTileGroup() {
column_map_type column_map;
// Well, a TempTable doesn't really care about TileGroupIds
// And nobody else in the system should be referencing our boys directly,
// so we're just going to use a simple counter for these ids
// We need to do this because otherwise we will think that our inserts
// failed all the time if use INVALID_OID
oid_t tile_group_id =
TEMPTABLE_TILEGROUP_ID + static_cast<int>(tile_groups_.size());
// Figure out the partitioning for given tilegroup layout
column_map =
AbstractTable::GetTileGroupLayout((LayoutType)peloton_layout_mode);
// Create a tile group with that partitioning
std::shared_ptr<storage::TileGroup> tile_group(
AbstractTable::GetTileGroupWithLayout(
INVALID_OID, tile_group_id, column_map, TEMPTABLE_DEFAULT_SIZE));
PL_ASSERT(tile_group.get());
tile_groups_.push_back(tile_group);
LOG_TRACE("Created TileGroup for %s\n%s\n", GetName().c_str(),
tile_group->GetInfo().c_str());
return tile_group_id;
}
} // End storage namespace
} // End peloton namespace
<|endoftext|>
|
<commit_before>#include <gtest/gtest.h>
#include "streamblender_tests.h"
namespace streamblender {
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void StreamBlenderTest::SetUp() {
src_facility_ = new StreamBlender(tc_.get());
InitParameters();
SetUpStreamBlender();
}
void StreamBlenderTest::TearDown() {
delete src_facility_;
}
void StreamBlenderTest::InitParameters(){
in_c1 = "in_c1";
in_c2 = "in_c2";
in_c3 = "in_c3";
out_c1 = "out_c1";
ins.push_back(in_c1);
ins.push_back(in_c2);
ins.push_back(in_c3);
iso_1 = 92235;
iso_2 = 94240;
iso_3 = 95241;
src_11 = in_c1;
src_12 = in_c2;
src_21 = in_c1;
src_22 = in_c2;
src_31 = in_c3;
srcs.push_back(src_11);
srcs.push_back(src_12);
srcs.push_back(src_21);
srcs.push_back(src_22);
srcs.push_back(src_31);
process_time = 10;
max_inv_size = 200;
capacity = 20;
cost = 1;
cyclus::CompMap v;
v[922350000] = 1;
v[922380000] = 2;
cyclus::Composition::Ptr recipe = cyclus::Composition::CreateFromAtom(v);
tc_.get()->AddRecipe(src_11, recipe);
cyclus::CompMap w;
w[922350000] = 1;
recipe = cyclus::Composition::CreateFromAtom(w);
tc_.get()->AddRecipe(src_12, recipe);
w[942400000] = 1;
recipe = cyclus::Composition::CreateFromAtom(w);
tc_.get()->AddRecipe(src_21, recipe);
v[942400000] = 1;
recipe = cyclus::Composition::CreateFromAtom(v);
tc_.get()->AddRecipe(src_22, recipe);
cyclus::CompMap x;
x[952410000] = 0.25;
recipe = cyclus::Composition::CreateFromAtom(x);
tc_.get()->AddRecipe(src_31, recipe);
cyclus::CompMap y;
y[922350000] = 1;
y[942400000] = 2;
y[952410000] = 1;
recipe = cyclus::Composition::CreateFromAtom(y);
tc_.get()->AddRecipe(out_r1, recipe);
}
void StreamBlenderTest::SetUpStreamBlender(){
src_facility_->in_commods_(ins);
src_facility_->out_commod_(out_c1);
src_facility_->in_recipes_(srcs);
src_facility_->out_recipe_(out_r1);
src_facility_->process_time_(process_time);
src_facility_->max_inv_size_(max_inv_size);
src_facility_->capacity_(capacity);
}
void StreamBlenderTest::TestInitState(StreamBlender* fac){
EXPECT_EQ(process_time, fac->process_time_());
EXPECT_EQ(max_inv_size, fac->max_inv_size_());
EXPECT_EQ(capacity, fac->capacity_());
EXPECT_EQ(ins, fac->in_commods_());
EXPECT_EQ(out_c1, fac->out_commod_());
}
void StreamBlenderTest::TestRequest(StreamBlender* fac, double cap){
//cyclus::Material::Ptr req = fac->Request_();
//EXPECT_EQ(cap, req->quantity());
}
void StreamBlenderTest::TestAddMat(StreamBlender* fac,
cyclus::Material::Ptr mat){
double amt = mat->quantity();
double before = fac->blendbuff.quantity();
//fac->AddMat_(mat);
double after = fac->blendbuff.quantity();
EXPECT_EQ(amt, after - before);
}
void StreamBlenderTest::TestBuffers(StreamBlender* fac, double inv,
double proc, double rawbuffs){
double t = tc_.get()->time();
EXPECT_EQ(inv, fac->blendbuff.quantity());
EXPECT_EQ(rawbuffs, fac->rawbuffs_quantity());
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(StreamBlenderTest, clone) {
StreamBlender* cloned_fac =
dynamic_cast<StreamBlender*> (src_facility_->Clone());
TestInitState(cloned_fac);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(StreamBlenderTest, InitialState) {
// Test things about the initial state of the facility here
TestInitState(src_facility_);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(StreamBlenderTest, CurrentCapacity) {
EXPECT_EQ(capacity, src_facility_->current_capacity());
src_facility_->max_inv_size_(1e299);
EXPECT_EQ(1e299, src_facility_->max_inv_size_());
EXPECT_EQ(capacity, src_facility_->capacity_());
EXPECT_EQ(capacity, src_facility_->current_capacity());
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(StreamBlenderTest, Print) {
EXPECT_NO_THROW(std::string s = src_facility_->str());
// Test StreamBlender specific aspects of the print method here
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(StreamBlenderTest, Request) {
TestRequest(src_facility_, src_facility_->current_capacity());
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(StreamBlenderTest, AddMats) {
double cap = src_facility_->current_capacity();
cyclus::Material::Ptr mat = cyclus::NewBlankMaterial(0.5*cap);
TestAddMat(src_facility_, mat);
// cyclus::Composition::Ptr rec = tc_.get()->GetRecipe(in_r1);
// cyclus::Material::Ptr recmat = cyclus::Material::CreateUntracked(0.5*cap, rec);
//TestAddMat(src_facility_, recmat);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(StreamBlenderTest, Tick) {
ASSERT_NO_THROW(src_facility_->Tick());
// Test StreamBlender specific behaviors of the Tick function here
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(StreamBlenderTest, Tock) {
// initially, nothing in the buffers
TestBuffers(src_facility_,0,0,0);
double cap = src_facility_->current_capacity();
//cyclus::Composition::Ptr rec = tc_.get()->GetRecipe(in_r1);
//cyclus::Material::Ptr mat = cyclus::Material::CreateUntracked(cap, rec);
//TestAddMat(src_facility_, mat);
// affter add, the blendbuff has the material
TestBuffers(src_facility_,cap,0,0);
EXPECT_NO_THROW(src_facility_->Tock());
// after tock, the processing buffer has the material
TestBuffers(src_facility_,0,cap,0);
EXPECT_EQ(0, tc_.get()->time());
for( int i = 1; i < process_time-1; ++i){
tc_.get()->time(i);
EXPECT_NO_THROW(src_facility_->Tock());
TestBuffers(src_facility_,0,0,0);
}
tc_.get()->time(process_time);
EXPECT_EQ(process_time, tc_.get()->time());
EXPECT_EQ(0, src_facility_->ready());
src_facility_->Tock();
TestBuffers(src_facility_,0,0,cap);
tc_.get()->time(process_time+1);
EXPECT_EQ(1, src_facility_->ready());
src_facility_->Tock();
TestBuffers(src_facility_,0,0,cap);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(StreamBlenderTest, NoProcessTime) {
// tests what happens when the process time is zero
src_facility_->process_time_(0);
EXPECT_EQ(0, src_facility_->process_time_());
double cap = src_facility_->current_capacity();
//cyclus::Composition::Ptr rec = tc_.get()->GetRecipe(in_r1);
//cyclus::Material::Ptr mat = cyclus::Material::CreateUntracked(cap, rec);
//TestAddMat(src_facility_, mat);
// affter add, the blendbuff has the material
TestBuffers(src_facility_,cap,0,0);
EXPECT_NO_THROW(src_facility_->Tock());
// affter tock, the rawbuffs have the material
TestBuffers(src_facility_,0,0,cap);
}
} // namespace streamblender
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cyclus::Agent* StreamBlenderConstructor(cyclus::Context* ctx) {
return new streamblender::StreamBlender(ctx);
}
// required to get functionality in cyclus agent unit tests library
#ifndef CYCLUS_AGENT_TESTS_CONNECTED
int ConnectAgentTests();
static int cyclus_agent_tests_connected = ConnectAgentTests();
#define CYCLUS_AGENT_TESTS_CONNECTED cyclus_agent_tests_connected
#endif // CYCLUS_AGENT_TESTS_CONNECTED
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
INSTANTIATE_TEST_CASE_P(StreamBlenderFac, FacilityTests,
::testing::Values(&StreamBlenderConstructor));
INSTANTIATE_TEST_CASE_P(StreamBlenderFac, AgentTests,
::testing::Values(&StreamBlenderConstructor));
<commit_msg>adds recipes<commit_after>#include <gtest/gtest.h>
#include "streamblender_tests.h"
namespace streamblender {
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void StreamBlenderTest::SetUp() {
src_facility_ = new StreamBlender(tc_.get());
InitParameters();
SetUpStreamBlender();
}
void StreamBlenderTest::TearDown() {
delete src_facility_;
}
void StreamBlenderTest::InitParameters(){
in_c1 = "in_c1";
in_c2 = "in_c2";
in_c3 = "in_c3";
out_c1 = "out_c1";
ins.push_back(in_c1);
ins.push_back(in_c2);
ins.push_back(in_c3);
iso_1 = 92235;
iso_2 = 94240;
iso_3 = 95241;
src_11 = in_c1;
src_12 = in_c2;
src_21 = in_c1;
src_22 = in_c2;
src_31 = in_c3;
srcs.push_back(src_11);
srcs.push_back(src_12);
srcs.push_back(src_21);
srcs.push_back(src_22);
srcs.push_back(src_31);
process_time = 10;
max_inv_size = 200;
capacity = 20;
cost = 1;
cyclus::CompMap v;
v[922350000] = 1;
v[922380000] = 2;
cyclus::Composition::Ptr recipe = cyclus::Composition::CreateFromAtom(v);
tc_.get()->AddRecipe(src_11, recipe);
cyclus::CompMap w;
w[922350000] = 1;
recipe = cyclus::Composition::CreateFromAtom(w);
tc_.get()->AddRecipe(src_12, recipe);
w[942400000] = 1;
recipe = cyclus::Composition::CreateFromAtom(w);
tc_.get()->AddRecipe(src_21, recipe);
v[942400000] = 1;
recipe = cyclus::Composition::CreateFromAtom(v);
tc_.get()->AddRecipe(src_22, recipe);
cyclus::CompMap x;
x[952410000] = 0.25;
recipe = cyclus::Composition::CreateFromAtom(x);
tc_.get()->AddRecipe(src_31, recipe);
cyclus::CompMap y;
y[922350000] = 1;
y[942400000] = 2;
y[952410000] = 1;
recipe = cyclus::Composition::CreateFromAtom(y);
tc_.get()->AddRecipe(out_r1, recipe);
}
void StreamBlenderTest::SetUpStreamBlender(){
src_facility_->in_commods_(ins);
src_facility_->out_commod_(out_c1);
src_facility_->in_recipes_(srcs);
src_facility_->out_recipe_(out_r1);
src_facility_->process_time_(process_time);
src_facility_->max_inv_size_(max_inv_size);
src_facility_->capacity_(capacity);
src_facility_->cost_(cost);
src_facility_->isos_(isos);
src_facility_->sources_(srcs);
}
void StreamBlenderTest::TestInitState(StreamBlender* fac){
EXPECT_EQ(process_time, fac->process_time_());
EXPECT_EQ(max_inv_size, fac->max_inv_size_());
EXPECT_EQ(capacity, fac->capacity_());
EXPECT_EQ(ins, fac->in_commods_());
EXPECT_EQ(out_c1, fac->out_commod_());
}
void StreamBlenderTest::TestRequest(StreamBlender* fac, double cap){
//cyclus::Material::Ptr req = fac->Request_();
//EXPECT_EQ(cap, req->quantity());
}
void StreamBlenderTest::TestAddMat(StreamBlender* fac,
cyclus::Material::Ptr mat){
double amt = mat->quantity();
double before = fac->blendbuff.quantity();
//fac->AddMat_(mat);
double after = fac->blendbuff.quantity();
EXPECT_EQ(amt, after - before);
}
void StreamBlenderTest::TestBuffers(StreamBlender* fac, double inv,
double proc, double rawbuffs){
double t = tc_.get()->time();
EXPECT_EQ(inv, fac->blendbuff.quantity());
EXPECT_EQ(rawbuffs, fac->rawbuffs_quantity());
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(StreamBlenderTest, clone) {
StreamBlender* cloned_fac =
dynamic_cast<StreamBlender*> (src_facility_->Clone());
TestInitState(cloned_fac);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(StreamBlenderTest, InitialState) {
// Test things about the initial state of the facility here
TestInitState(src_facility_);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(StreamBlenderTest, CurrentCapacity) {
EXPECT_EQ(capacity, src_facility_->current_capacity());
src_facility_->max_inv_size_(1e299);
EXPECT_EQ(1e299, src_facility_->max_inv_size_());
EXPECT_EQ(capacity, src_facility_->capacity_());
EXPECT_EQ(capacity, src_facility_->current_capacity());
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(StreamBlenderTest, Print) {
EXPECT_NO_THROW(std::string s = src_facility_->str());
// Test StreamBlender specific aspects of the print method here
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(StreamBlenderTest, Request) {
TestRequest(src_facility_, src_facility_->current_capacity());
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(StreamBlenderTest, AddMats) {
double cap = src_facility_->current_capacity();
cyclus::Material::Ptr mat = cyclus::NewBlankMaterial(0.5*cap);
TestAddMat(src_facility_, mat);
// cyclus::Composition::Ptr rec = tc_.get()->GetRecipe(in_r1);
// cyclus::Material::Ptr recmat = cyclus::Material::CreateUntracked(0.5*cap, rec);
//TestAddMat(src_facility_, recmat);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(StreamBlenderTest, Tick) {
ASSERT_NO_THROW(src_facility_->Tick());
// Test StreamBlender specific behaviors of the Tick function here
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(StreamBlenderTest, Tock) {
// initially, nothing in the buffers
TestBuffers(src_facility_,0,0,0);
double cap = src_facility_->current_capacity();
//cyclus::Composition::Ptr rec = tc_.get()->GetRecipe(in_r1);
//cyclus::Material::Ptr mat = cyclus::Material::CreateUntracked(cap, rec);
//TestAddMat(src_facility_, mat);
// affter add, the blendbuff has the material
TestBuffers(src_facility_,cap,0,0);
EXPECT_NO_THROW(src_facility_->Tock());
// after tock, the processing buffer has the material
TestBuffers(src_facility_,0,cap,0);
EXPECT_EQ(0, tc_.get()->time());
for( int i = 1; i < process_time-1; ++i){
tc_.get()->time(i);
EXPECT_NO_THROW(src_facility_->Tock());
TestBuffers(src_facility_,0,0,0);
}
tc_.get()->time(process_time);
EXPECT_EQ(process_time, tc_.get()->time());
EXPECT_EQ(0, src_facility_->ready());
src_facility_->Tock();
TestBuffers(src_facility_,0,0,cap);
tc_.get()->time(process_time+1);
EXPECT_EQ(1, src_facility_->ready());
src_facility_->Tock();
TestBuffers(src_facility_,0,0,cap);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(StreamBlenderTest, NoProcessTime) {
// tests what happens when the process time is zero
src_facility_->process_time_(0);
EXPECT_EQ(0, src_facility_->process_time_());
double cap = src_facility_->current_capacity();
//cyclus::Composition::Ptr rec = tc_.get()->GetRecipe(in_r1);
//cyclus::Material::Ptr mat = cyclus::Material::CreateUntracked(cap, rec);
//TestAddMat(src_facility_, mat);
// affter add, the blendbuff has the material
TestBuffers(src_facility_,cap,0,0);
EXPECT_NO_THROW(src_facility_->Tock());
// affter tock, the rawbuffs have the material
TestBuffers(src_facility_,0,0,cap);
}
} // namespace streamblender
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cyclus::Agent* StreamBlenderConstructor(cyclus::Context* ctx) {
return new streamblender::StreamBlender(ctx);
}
// required to get functionality in cyclus agent unit tests library
#ifndef CYCLUS_AGENT_TESTS_CONNECTED
int ConnectAgentTests();
static int cyclus_agent_tests_connected = ConnectAgentTests();
#define CYCLUS_AGENT_TESTS_CONNECTED cyclus_agent_tests_connected
#endif // CYCLUS_AGENT_TESTS_CONNECTED
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
INSTANTIATE_TEST_CASE_P(StreamBlenderFac, FacilityTests,
::testing::Values(&StreamBlenderConstructor));
INSTANTIATE_TEST_CASE_P(StreamBlenderFac, AgentTests,
::testing::Values(&StreamBlenderConstructor));
<|endoftext|>
|
<commit_before>
/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include "canvas.h"
#include "linechart.h"
#include "rendertarget.h"
#include <fnordmetric/util/runtimeexception.h>
namespace fnordmetric {
namespace ui {
char LineChart::kDefaultLineStyle[] = "solid";
double LineChart::kDefaultLineWidth = 2.0f;
char LineChart::kDefaultPointStyle[] = "none";
double LineChart::kDefaultPointSize = 3.0f;
LineChart::LineChart(
Canvas* canvas,
NumericalDomain* x_domain /* = nullptr */,
NumericalDomain* y_domain /* = nullptr */) :
canvas_(canvas),
x_domain_(x_domain),
y_domain_(y_domain),
num_series_(0) {}
void LineChart::addSeries(
Series2D<double, double>* series,
const std::string& line_style /* = kDefaultLineStyle */,
double line_width /* = kDefaultLineWidth */,
const std::string& point_style /* = kDefaultLineStyle */,
double point_size /* = kDefaultPointsize */,
bool smooth /* = false */) {
Line line;
line.color = seriesColor(series);
line.line_style = line_style;
line.line_width = line_width;
line.point_style = point_style;
line.point_size = point_size;
line.smooth = smooth;
for (const auto& spoint : series->getData()) {
line.points.emplace_back(std::get<0>(spoint), std::get<1>(spoint));
}
lines_.emplace_back(line);
}
AxisDefinition* LineChart::addAxis(AxisDefinition::kPosition position) {
switch (position) {
case AxisDefinition::TOP:
return canvas_->addAxis(position, getXDomain());
case AxisDefinition::RIGHT:
return canvas_->addAxis(position, getYDomain());
case AxisDefinition::BOTTOM:
return canvas_->addAxis(position, getXDomain());
case AxisDefinition::LEFT:
return canvas_->addAxis(position, getYDomain());
}
}
NumericalDomain* LineChart::getXDomain() const {
if (x_domain_ != nullptr) {
return x_domain_;
}
if (x_domain_auto_.get() == nullptr) {
double x_min = 0.0f;
double x_max = 0.0f;
for (const auto& line : lines_) {
for (const auto& point : line.points) {
if (point.first > x_max) {
x_max = point.first;
}
if (point.first < x_min) {
x_min = point.first;
}
}
}
if (x_max > 0) {
x_max *= 1.1;
}
if (x_max < 0) {
x_max *= 0.9;
}
if (x_min > 0) {
x_min *= 0.9;
}
if (x_min < 0) {
x_min *= 1.1;
}
x_domain_auto_.reset(new NumericalDomain(x_min, x_max, false));
}
return x_domain_auto_.get();
}
NumericalDomain* LineChart::getYDomain() const {
if (y_domain_ != nullptr) {
return y_domain_;
}
if (y_domain_auto_.get() == nullptr) {
double y_min = 0.0f;
double y_max = 0.0f;
for (const auto& line : lines_) {
for (const auto& point : line.points) {
if (point.second > y_max) {
y_max = point.second;
}
if (point.second < y_min) {
y_min = point.second;
}
}
}
if (y_max > 0) {
y_max *= 1.1;
}
if (y_max < 0) {
y_max *= 0.9;
}
if (y_min > 0) {
y_min *= 0.9;
}
if (y_min < 0) {
y_min *= 1.1;
}
y_domain_auto_.reset(new NumericalDomain(y_min, y_max, false));
}
return y_domain_auto_.get();
}
void LineChart::render(
RenderTarget* target,
int width,
int height,
std::tuple<int, int, int, int>* padding) const {
auto padding_top = std::get<0>(*padding);
auto padding_right = std::get<1>(*padding);
auto padding_bottom = std::get<2>(*padding);
auto padding_left = std::get<3>(*padding);
auto inner_width = width - padding_right - padding_left;
auto inner_height = height - padding_top - padding_bottom;
auto x_domain = getXDomain();
auto y_domain = getYDomain();
target->beginGroup("lines");
for (const auto& line : lines_) {
std::vector<std::pair<double, double>> coords;
for (const auto& point : line.points) {
coords.emplace_back(
padding_left + x_domain->scale(point.first) * inner_width,
padding_top + (1.0 - y_domain->scale(point.second)) * inner_height);
}
target->drawPath(
coords,
line.line_style,
line.line_width,
line.smooth,
line.color,
"line");
if (line.point_style != "none") {
for (const auto& point : coords) {
target->drawPoint(
point.first,
point.second,
line.point_style,
line.point_size,
line.color,
"point");
}
}
}
target->finishGroup();
}
void LineChart::addSeries(Series2D<std::string, double>* series) {
RAISE(
util::RuntimeException,
"unsupported series format for LineChart: <string, float>");
}
void LineChart::addSeries(Series2D<std::string, std::string>* series) {
RAISE(
util::RuntimeException,
"unsupported series format for LineChart: <string, float>");
}
}
}
<commit_msg>csv backend rewind<commit_after>
/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include "canvas.h"
#include "linechart.h"
#include "rendertarget.h"
#include <fnordmetric/util/runtimeexception.h>
namespace fnordmetric {
namespace ui {
char LineChart::kDefaultLineStyle[] = "solid";
double LineChart::kDefaultLineWidth = 2.0f;
char LineChart::kDefaultPointStyle[] = "none";
double LineChart::kDefaultPointSize = 3.0f;
LineChart::LineChart(
Canvas* canvas,
NumericalDomain* x_domain /* = nullptr */,
NumericalDomain* y_domain /* = nullptr */) :
canvas_(canvas),
x_domain_(x_domain),
y_domain_(y_domain),
num_series_(0) {}
void LineChart::addSeries(
Series2D<double, double>* series,
const std::string& line_style /* = kDefaultLineStyle */,
double line_width /* = kDefaultLineWidth */,
const std::string& point_style /* = kDefaultLineStyle */,
double point_size /* = kDefaultPointsize */,
bool smooth /* = false */) {
Line line;
line.color = seriesColor(series);
line.line_style = line_style;
line.line_width = line_width;
line.point_style = point_style;
line.point_size = point_size;
line.smooth = smooth;
for (const auto& spoint : series->getData()) {
line.points.emplace_back(std::get<0>(spoint), std::get<1>(spoint));
}
lines_.emplace_back(line);
}
AxisDefinition* LineChart::addAxis(AxisDefinition::kPosition position) {
switch (position) {
case AxisDefinition::TOP:
return canvas_->addAxis(position, getXDomain());
case AxisDefinition::RIGHT:
return canvas_->addAxis(position, getYDomain());
case AxisDefinition::BOTTOM:
return canvas_->addAxis(position, getXDomain());
case AxisDefinition::LEFT:
return canvas_->addAxis(position, getYDomain());
}
}
NumericalDomain* LineChart::getXDomain() const {
if (x_domain_ != nullptr) {
return x_domain_;
}
if (x_domain_auto_.get() == nullptr) {
double x_min = 0.0f;
double x_max = 0.0f;
for (const auto& line : lines_) {
for (const auto& point : line.points) {
if (point.first > x_max) {
x_max = point.first;
}
if (point.first < x_min) {
x_min = point.first;
}
}
}
if (x_max > 0) {
x_max *= 1.1;
}
if (x_max < 0) {
x_max *= 0.9;
}
if (x_min > 0) {
x_min *= 0.9;
}
if (x_min < 0) {
x_min *= 1.1;
}
x_domain_auto_.reset(new NumericalDomain(x_min, x_max, false));
}
return x_domain_auto_.get();
}
NumericalDomain* LineChart::getYDomain() const {
if (y_domain_ != nullptr) {
return y_domain_;
}
if (y_domain_auto_.get() == nullptr) {
double y_min = 0.0f;
double y_max = 0.0f;
for (const auto& line : lines_) {
for (const auto& point : line.points) {
if (point.second > y_max) {
y_max = point.second;
}
if (point.second < y_min) {
y_min = point.second;
}
}
}
if (y_max > 0) {
y_max *= 1.1;
}
if (y_max < 0) {
y_max *= 0.9;
}
if (y_min > 0) {
y_min *= 0.9;
}
if (y_min < 0) {
y_min *= 1.1;
}
y_domain_auto_.reset(new NumericalDomain(y_min, y_max, false));
}
return y_domain_auto_.get();
}
void LineChart::render(
RenderTarget* target,
int width,
int height,
std::tuple<int, int, int, int>* padding) const {
auto padding_top = std::get<0>(*padding);
auto padding_right = std::get<1>(*padding);
auto padding_bottom = std::get<2>(*padding);
auto padding_left = std::get<3>(*padding);
auto inner_width = width - padding_right - padding_left;
auto inner_height = height - padding_top - padding_bottom;
auto x_domain = getXDomain();
auto y_domain = getYDomain();
target->beginGroup("lines");
for (const auto& line : lines_) {
std::vector<std::pair<double, double>> coords;
for (const auto& point : line.points) {
coords.emplace_back(
padding_left + x_domain->scale(point.first) * inner_width,
padding_top + (1.0 - y_domain->scale(point.second)) * inner_height);
}
target->drawPath(
coords,
line.line_style,
line.line_width,
line.smooth,
line.color,
"line");
if (line.point_style != "none") {
for (const auto& point : coords) {
target->drawPoint(
point.first,
point.second,
line.point_style,
line.point_size,
line.color,
"point");
}
}
}
target->finishGroup();
}
void LineChart::addSeries(Series2D<std::string, double>* series) {
RAISE(
util::RuntimeException,
"unsupported series format for LineChart: <string, float>");
}
void LineChart::addSeries(Series2D<std::string, std::string>* series) {
RAISE(
util::RuntimeException,
"unsupported series format for LineChart: <string, float>");
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2016 zenghur
#include "Epoll.h"
#include <string.h>
#include "Error.h"
#include "DateTime.h"
#include "IOEvent.h"
using vanilla::printError;
using vanilla::PollerEvent;
using vanilla::IOEvent;
using vanilla::DateTime;
#ifdef __linux__
#include <sys/epoll.h>
Epoll::Epoll(): epollfd_(-1), events_(MAX_EVENTS) {
}
Epoll::~Epoll() {
if (epollfd_ >= 0) {
close(epollfd_);
}
}
void Epoll::init() {
if ((epollfd_ = epoll_create(1)) == -1) {
printError();
}
}
void Epoll::addFd(int fd, PollerEventType mask, void *udata) {
struct epoll_event event;
memset(&event, 0, sizeof(event);
if (mask & static_cast<PollerEventType>(PollerEvent::POLLER_IN)) {
event.events |= EPOLLIN;
}
if (mask & static_cast<PollerEventType>(PollerEvent::POLLER_OUT)) {
event.events |= EPOLLOUT;
}
event.data.ptr = udata;
if (epoll_ctl(epollfd_, EPOLL_CTL_ADD, fd, &events) == -1) {
printError();
}
}
void Epoll::deleteFd(int fd, PollerEventType mask) {
epoll_ctl(epollfd_, EPOLL_CTL_DEL, fd, NULL);
}
void Epoll::modFd(int fd, PollerEventType mask, void *udata) {
struct epoll_event event;
memset(&event, 0, sizeof(event);
if (mask & static_cast<PollerEventType>(PollerEvent::POLLER_IN)) {
event.events |= EPOLLIN;
}
if (mask & static_cast<PollerEventType>(PollerEvent::POLLER_OUT)) {
event.events |= EPOLLOUT;
}
event.data.ptr = udata;
epoll_ctl(epollfd_, EPOLL_CTL_MOD, fd, &events);
}
void Epoll::poll() {
int n = 0;
if ((n = epoll_wait(epollfd_, &*events_.begin(), MAX_EVENTS, timeout)) == -1) {
printError();
}
for (auto i = 0; i < n; ++i) {
IOEvent *io = events_[i].data.ptr;
if (!io) {
continue;
}
if (events[i].events & EPOLLIN) {
io->canRead();
}
if (events[i].events & EPOLLIN || events[i].events & EPOLLERR) {
io->canWrite();
}
}
}
#endif
<commit_msg>damn macro<commit_after>// Copyright (c) 2016 zenghur
#include "Epoll.h"
#include <string.h>
#include "Error.h"
#include "DateTime.h"
#include "IOEvent.h"
using vanilla::printError;
using vanilla::PollerEvent;
using vanilla::IOEvent;
using vanilla::DateTime;
#ifdef __linux__
#include <sys/epoll.h>
Epoll::Epoll(): epollfd_(-1), events_(MAX_EVENTS) {
}
Epoll::~Epoll() {
if (epollfd_ >= 0) {
close(epollfd_);
}
}
void Epoll::init() {
if ((epollfd_ = epoll_create(1)) == -1) {
printError();
}
}
void Epoll::addFd(int fd, PollerEventType mask, void *udata) {
struct epoll_event event;
memset(&event, 0, sizeof(event));
if (mask & static_cast<PollerEventType>(PollerEvent::POLLER_IN)) {
event.events |= EPOLLIN;
}
if (mask & static_cast<PollerEventType>(PollerEvent::POLLER_OUT)) {
event.events |= EPOLLOUT;
}
event.data.ptr = udata;
if (epoll_ctl(epollfd_, EPOLL_CTL_ADD, fd, &event) == -1) {
printError();
}
}
void Epoll::deleteFd(int fd, PollerEventType mask) {
epoll_ctl(epollfd_, EPOLL_CTL_DEL, fd, NULL);
}
void Epoll::modFd(int fd, PollerEventType mask, void *udata) {
struct epoll_event event;
memset(&event, 0, sizeof(event));
if (mask & static_cast<PollerEventType>(PollerEvent::POLLER_IN)) {
event.events |= EPOLLIN;
}
if (mask & static_cast<PollerEventType>(PollerEvent::POLLER_OUT)) {
event.events |= EPOLLOUT;
}
event.data.ptr = udata;
epoll_ctl(epollfd_, EPOLL_CTL_MOD, fd, &event);
}
void Epoll::poll() {
int n = 0;
if ((n = epoll_wait(epollfd_, &*events_.begin(), MAX_EVENTS, timeout)) == -1) {
printError();
}
for (auto i = 0; i < n; ++i) {
IOEvent *io = reinterpret_cast<IOEvent*>(events_[i].data.ptr);
if (!io) {
continue;
}
if (events_[i].events & EPOLLIN) {
io->canRead();
}
if (events_[i].events & EPOLLIN || events[i].events & EPOLLERR) {
io->canWrite();
}
}
}
#endif
<|endoftext|>
|
<commit_before>#include "nimplugin.h"
#include "nimpluginconstants.h"
#include "editor/nimeditor.h"
#include "editor/nimhighlighter.h"
#include "project/nimprojectmanager.h"
#include "project/nimimportprojectwizardfactory.h"
#include "project/nimnewprojectwizardfactory.h"
#include "project/nimnewfilewizardfactory.h"
#include "project/nimbuildconfigurationfactory.h"
#include "project/nimrunconfigurationfactory.h"
#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/fileiconprovider.h>
#include <coreplugin/id.h>
#include <coreplugin/editormanager/editormanager.h>
#include <extensionsystem/pluginmanager.h>
#include <texteditor/texteditorconstants.h>
#include <utils/mimetypes/mimedatabase.h>
#include <QtPlugin>
using namespace NimPlugin::Constants;
namespace NimPlugin {
static NimPlugin *m_instance = 0;
NimPlugin::NimPlugin()
{
m_instance = this;
}
NimPlugin::~NimPlugin()
{
m_instance = 0;
}
bool NimPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
Q_UNUSED(arguments)
Q_UNUSED(errorMessage)
Utils::MimeDatabase::addMimeTypes(QLatin1String(":/NimPlugin.mimetypes.xml"));
addAutoReleasedObject(new NimEditorFactory);
addAutoReleasedObject(new NimProjectManager);
addAutoReleasedObject(new NimImportProjectWizardFactory);
addAutoReleasedObject(new NimNewProjectWizardFactory);
addAutoReleasedObject(new NimNewFileWizardFactory);
addAutoReleasedObject(new NimBuildConfigurationFactory);
addAutoReleasedObject(new NimRunConfigurationFactory);
// Initialize editor actions handler
// Add MIME overlay icons (these icons displayed at Project dock panel)
const QIcon icon (QLatin1String(Constants::C_NIM_ICON_PATH));
if (!icon.isNull())
Core::FileIconProvider::registerIconOverlayForMimeType(icon, C_NIM_MIMETYPE);
return true;
}
} // namespace NimEditor
<commit_msg>Fixed missing visualization of the nim wizards<commit_after>#include "nimplugin.h"
#include "nimpluginconstants.h"
#include "editor/nimeditor.h"
#include "editor/nimhighlighter.h"
#include "project/nimprojectmanager.h"
#include "project/nimimportprojectwizardfactory.h"
#include "project/nimnewprojectwizardfactory.h"
#include "project/nimnewfilewizardfactory.h"
#include "project/nimbuildconfigurationfactory.h"
#include "project/nimrunconfigurationfactory.h"
#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/fileiconprovider.h>
#include <coreplugin/id.h>
#include <coreplugin/iwizardfactory.h>
#include <coreplugin/editormanager/editormanager.h>
#include <extensionsystem/pluginmanager.h>
#include <texteditor/texteditorconstants.h>
#include <utils/mimetypes/mimedatabase.h>
#include <QtPlugin>
using namespace NimPlugin::Constants;
namespace NimPlugin {
static NimPlugin *m_instance = 0;
NimPlugin::NimPlugin()
{
m_instance = this;
}
NimPlugin::~NimPlugin()
{
m_instance = 0;
}
bool NimPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
Q_UNUSED(arguments)
Q_UNUSED(errorMessage)
Utils::MimeDatabase::addMimeTypes(QLatin1String(":/NimPlugin.mimetypes.xml"));
addAutoReleasedObject(new NimEditorFactory);
addAutoReleasedObject(new NimProjectManager);
addAutoReleasedObject(new NimBuildConfigurationFactory);
addAutoReleasedObject(new NimRunConfigurationFactory);
Core::IWizardFactory::registerFactoryCreator([]() {
return QList<Core::IWizardFactory *>{
new NimNewFileWizardFactory,
new NimNewProjectWizardFactory,
new NimImportProjectWizardFactory
};
});
// Initialize editor actions handler
// Add MIME overlay icons (these icons displayed at Project dock panel)
const QIcon icon (QLatin1String(Constants::C_NIM_ICON_PATH));
if (!icon.isNull())
Core::FileIconProvider::registerIconOverlayForMimeType(icon, C_NIM_MIMETYPE);
return true;
}
} // namespace NimEditor
<|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 "webkit/glue/ftp_directory_listing_response_delegate.h"
#include <vector>
#include "base/i18n/icu_string_conversions.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/sys_string_conversions.h"
#include "base/time.h"
#include "net/base/escape.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/ftp/ftp_directory_listing_parser.h"
#include "net/ftp/ftp_server_type_histograms.h"
#include "unicode/ucsdet.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURL.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURLLoaderClient.h"
using WebKit::WebURLLoader;
using WebKit::WebURLLoaderClient;
using WebKit::WebURLResponse;
namespace {
// A very simple-minded character encoding detection.
// TODO(jungshik): We can apply more heuristics here (e.g. using various hints
// like TLD, the UI language/default encoding of a client, etc). In that case,
// this should be pulled out of here and moved somewhere in base because there
// can be other use cases.
std::string DetectEncoding(const std::string& text) {
if (IsStringASCII(text))
return std::string();
UErrorCode status = U_ZERO_ERROR;
UCharsetDetector* detector = ucsdet_open(&status);
ucsdet_setText(detector, text.data(), static_cast<int32_t>(text.length()),
&status);
const UCharsetMatch* match = ucsdet_detect(detector, &status);
const char* encoding = ucsdet_getName(match, &status);
ucsdet_close(detector);
// Should we check the quality of the match? A rather arbitrary number is
// assigned by ICU and it's hard to come up with a lower limit.
if (U_FAILURE(status))
return std::string();
return encoding;
}
string16 RawByteSequenceToFilename(const char* raw_filename,
const std::string& encoding) {
if (encoding.empty())
return ASCIIToUTF16(raw_filename);
// Try the detected encoding before falling back to the native codepage.
// Using the native codepage does not make much sense, but we don't have
// much else to resort to.
string16 filename;
if (!base::CodepageToUTF16(raw_filename, encoding.c_str(),
base::OnStringConversionError::SUBSTITUTE,
&filename))
filename = WideToUTF16Hack(base::SysNativeMBToWide(raw_filename));
return filename;
}
void ExtractFullLinesFromBuffer(std::string* buffer,
std::vector<std::string>* lines) {
int cut_pos = 0;
for (size_t i = 0; i < buffer->length(); i++) {
if ((*buffer)[i] != '\n')
continue;
size_t line_length = i - cut_pos;
if (line_length > 0 && (*buffer)[i - 1] == '\r')
line_length--;
lines->push_back(buffer->substr(cut_pos, line_length));
cut_pos = i + 1;
}
buffer->erase(0, cut_pos);
}
void LogFtpServerType(char server_type) {
switch (server_type) {
case 'E':
net::UpdateFtpServerTypeHistograms(net::SERVER_MOZ_EPLF);
break;
case 'V':
net::UpdateFtpServerTypeHistograms(net::SERVER_MOZ_VMS);
break;
case 'C':
net::UpdateFtpServerTypeHistograms(net::SERVER_MOZ_CMS);
break;
case 'W':
net::UpdateFtpServerTypeHistograms(net::SERVER_MOZ_DOS);
break;
case 'O':
net::UpdateFtpServerTypeHistograms(net::SERVER_MOZ_OS2);
break;
case 'U':
net::UpdateFtpServerTypeHistograms(net::SERVER_MOZ_LSL);
break;
case 'w':
net::UpdateFtpServerTypeHistograms(net::SERVER_MOZ_W16);
break;
case 'D':
net::UpdateFtpServerTypeHistograms(net::SERVER_MOZ_DLS);
break;
default:
net::UpdateFtpServerTypeHistograms(net::SERVER_UNKNOWN);
break;
}
}
} // namespace
namespace webkit_glue {
FtpDirectoryListingResponseDelegate::FtpDirectoryListingResponseDelegate(
WebURLLoaderClient* client,
WebURLLoader* loader,
const WebURLResponse& response)
: client_(client),
loader_(loader),
original_response_(response),
parser_fallback_(false) {
Init();
}
void FtpDirectoryListingResponseDelegate::OnReceivedData(const char* data,
int data_len) {
// Keep the raw data in case we have to use the old parser later.
input_buffer_.append(data, data_len);
if (!parser_fallback_) {
if (buffer_.ConsumeData(data, data_len) == net::OK)
return;
parser_fallback_ = true;
}
FeedFallbackParser();
SendResponseBufferToClient();
}
void FtpDirectoryListingResponseDelegate::OnCompletedRequest() {
if (!parser_fallback_) {
if (buffer_.ProcessRemainingData() == net::OK) {
while (buffer_.EntryAvailable())
AppendEntryToResponseBuffer(buffer_.PopEntry());
SendResponseBufferToClient();
net::UpdateFtpServerTypeHistograms(buffer_.GetServerType());
return;
}
parser_fallback_ = true;
}
FeedFallbackParser();
SendResponseBufferToClient();
// Only log the server type if we got enough data to reliably detect it.
if (parse_state_.parsed_one)
LogFtpServerType(parse_state_.lstyle);
}
void FtpDirectoryListingResponseDelegate::Init() {
memset(&parse_state_, 0, sizeof(parse_state_));
GURL response_url(original_response_.url());
UnescapeRule::Type unescape_rules = UnescapeRule::SPACES |
UnescapeRule::URL_SPECIAL_CHARS;
std::string unescaped_path = UnescapeURLComponent(response_url.path(),
unescape_rules);
string16 path_utf16;
// Per RFC 2640, FTP servers should use UTF-8 or its proper subset ASCII,
// but many old FTP servers use legacy encodings. Try UTF-8 first and
// detect the encoding.
if (IsStringUTF8(unescaped_path)) {
path_utf16 = UTF8ToUTF16(unescaped_path);
} else {
std::string encoding = DetectEncoding(unescaped_path);
// Try the detected encoding. If it fails, resort to the
// OS native encoding.
if (encoding.empty() ||
!base::CodepageToUTF16(unescaped_path, encoding.c_str(),
base::OnStringConversionError::SUBSTITUTE,
&path_utf16))
path_utf16 = WideToUTF16Hack(base::SysNativeMBToWide(unescaped_path));
}
response_buffer_ = net::GetDirectoryListingHeader(path_utf16);
// If this isn't top level directory (i.e. the path isn't "/",)
// add a link to the parent directory.
if (response_url.path().length() > 1) {
response_buffer_.append(
net::GetDirectoryListingEntry(ASCIIToUTF16(".."),
std::string(),
false, 0,
base::Time()));
}
}
void FtpDirectoryListingResponseDelegate::FeedFallbackParser() {
// If all we've seen so far is ASCII, encoding_ is empty. Try to detect the
// encoding. We don't do the separate UTF-8 check here because the encoding
// detection with a longer chunk (as opposed to the relatively short path
// component of the url) is unlikely to mistake UTF-8 for a legacy encoding.
// If it turns out to be wrong, a separate UTF-8 check has to be added.
//
// TODO(jungshik): UTF-8 has to be 'enforced' without any heuristics when
// we're talking to an FTP server compliant to RFC 2640 (that is, its response
// to FEAT command includes 'UTF8').
// See http://wiki.filezilla-project.org/Character_Set
if (encoding_.empty())
encoding_ = DetectEncoding(input_buffer_);
std::vector<std::string> lines;
ExtractFullLinesFromBuffer(&input_buffer_, &lines);
for (std::vector<std::string>::const_iterator line = lines.begin();
line != lines.end(); ++line) {
struct net::list_result result;
int line_type = net::ParseFTPList(line->c_str(), &parse_state_, &result);
// The original code assumed months are in range 0-11 (PRExplodedTime),
// but our Time class expects a 1-12 range. Adjust it here, because
// the third-party parsing code uses bit-shifting on the month,
// and it'd be too easy to break that logic.
result.fe_time.month++;
DCHECK_LE(1, result.fe_time.month);
DCHECK_GE(12, result.fe_time.month);
int64 file_size;
switch (line_type) {
case 'd': // Directory entry.
response_buffer_.append(net::GetDirectoryListingEntry(
RawByteSequenceToFilename(result.fe_fname, encoding_),
result.fe_fname, true, 0,
base::Time::FromLocalExploded(result.fe_time)));
break;
case 'f': // File entry.
if (StringToInt64(result.fe_size, &file_size)) {
response_buffer_.append(net::GetDirectoryListingEntry(
RawByteSequenceToFilename(result.fe_fname, encoding_),
result.fe_fname, false, file_size,
base::Time::FromLocalExploded(result.fe_time)));
}
break;
case 'l': { // Symlink entry.
std::string filename(result.fe_fname, result.fe_fnlen);
// Parsers for styles 'U' and 'W' handle " -> " themselves.
if (parse_state_.lstyle != 'U' && parse_state_.lstyle != 'W') {
std::string::size_type offset = filename.find(" -> ");
if (offset != std::string::npos)
filename = filename.substr(0, offset);
}
if (StringToInt64(result.fe_size, &file_size)) {
response_buffer_.append(net::GetDirectoryListingEntry(
RawByteSequenceToFilename(filename.c_str(), encoding_),
filename, false, file_size,
base::Time::FromLocalExploded(result.fe_time)));
}
}
break;
case '?': // Junk entry.
case '"': // Comment entry.
break;
default:
NOTREACHED();
break;
}
}
}
void FtpDirectoryListingResponseDelegate::AppendEntryToResponseBuffer(
const net::FtpDirectoryListingEntry& entry) {
switch (entry.type) {
case net::FtpDirectoryListingEntry::FILE:
response_buffer_.append(
net::GetDirectoryListingEntry(entry.name, std::string(), false,
entry.size, entry.last_modified));
break;
case net::FtpDirectoryListingEntry::DIRECTORY:
response_buffer_.append(
net::GetDirectoryListingEntry(entry.name, std::string(), true,
0, entry.last_modified));
break;
case net::FtpDirectoryListingEntry::SYMLINK:
response_buffer_.append(
net::GetDirectoryListingEntry(entry.name, std::string(), false,
0, entry.last_modified));
break;
default:
NOTREACHED();
break;
}
}
void FtpDirectoryListingResponseDelegate::SendResponseBufferToClient() {
if (!response_buffer_.empty()) {
client_->didReceiveData(loader_, response_buffer_.data(),
response_buffer_.length());
response_buffer_.clear();
}
}
} // namespace webkit_glue
<commit_msg>New FTP LIST response parsing code: only record histogram data if the listing wasn't empty (otherwise we'd record a useless and misleading "unknown server" entry).<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 "webkit/glue/ftp_directory_listing_response_delegate.h"
#include <vector>
#include "base/i18n/icu_string_conversions.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/sys_string_conversions.h"
#include "base/time.h"
#include "net/base/escape.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/ftp/ftp_directory_listing_parser.h"
#include "net/ftp/ftp_server_type_histograms.h"
#include "unicode/ucsdet.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURL.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURLLoaderClient.h"
using WebKit::WebURLLoader;
using WebKit::WebURLLoaderClient;
using WebKit::WebURLResponse;
namespace {
// A very simple-minded character encoding detection.
// TODO(jungshik): We can apply more heuristics here (e.g. using various hints
// like TLD, the UI language/default encoding of a client, etc). In that case,
// this should be pulled out of here and moved somewhere in base because there
// can be other use cases.
std::string DetectEncoding(const std::string& text) {
if (IsStringASCII(text))
return std::string();
UErrorCode status = U_ZERO_ERROR;
UCharsetDetector* detector = ucsdet_open(&status);
ucsdet_setText(detector, text.data(), static_cast<int32_t>(text.length()),
&status);
const UCharsetMatch* match = ucsdet_detect(detector, &status);
const char* encoding = ucsdet_getName(match, &status);
ucsdet_close(detector);
// Should we check the quality of the match? A rather arbitrary number is
// assigned by ICU and it's hard to come up with a lower limit.
if (U_FAILURE(status))
return std::string();
return encoding;
}
string16 RawByteSequenceToFilename(const char* raw_filename,
const std::string& encoding) {
if (encoding.empty())
return ASCIIToUTF16(raw_filename);
// Try the detected encoding before falling back to the native codepage.
// Using the native codepage does not make much sense, but we don't have
// much else to resort to.
string16 filename;
if (!base::CodepageToUTF16(raw_filename, encoding.c_str(),
base::OnStringConversionError::SUBSTITUTE,
&filename))
filename = WideToUTF16Hack(base::SysNativeMBToWide(raw_filename));
return filename;
}
void ExtractFullLinesFromBuffer(std::string* buffer,
std::vector<std::string>* lines) {
int cut_pos = 0;
for (size_t i = 0; i < buffer->length(); i++) {
if ((*buffer)[i] != '\n')
continue;
size_t line_length = i - cut_pos;
if (line_length > 0 && (*buffer)[i - 1] == '\r')
line_length--;
lines->push_back(buffer->substr(cut_pos, line_length));
cut_pos = i + 1;
}
buffer->erase(0, cut_pos);
}
void LogFtpServerType(char server_type) {
switch (server_type) {
case 'E':
net::UpdateFtpServerTypeHistograms(net::SERVER_MOZ_EPLF);
break;
case 'V':
net::UpdateFtpServerTypeHistograms(net::SERVER_MOZ_VMS);
break;
case 'C':
net::UpdateFtpServerTypeHistograms(net::SERVER_MOZ_CMS);
break;
case 'W':
net::UpdateFtpServerTypeHistograms(net::SERVER_MOZ_DOS);
break;
case 'O':
net::UpdateFtpServerTypeHistograms(net::SERVER_MOZ_OS2);
break;
case 'U':
net::UpdateFtpServerTypeHistograms(net::SERVER_MOZ_LSL);
break;
case 'w':
net::UpdateFtpServerTypeHistograms(net::SERVER_MOZ_W16);
break;
case 'D':
net::UpdateFtpServerTypeHistograms(net::SERVER_MOZ_DLS);
break;
default:
net::UpdateFtpServerTypeHistograms(net::SERVER_UNKNOWN);
break;
}
}
} // namespace
namespace webkit_glue {
FtpDirectoryListingResponseDelegate::FtpDirectoryListingResponseDelegate(
WebURLLoaderClient* client,
WebURLLoader* loader,
const WebURLResponse& response)
: client_(client),
loader_(loader),
original_response_(response),
parser_fallback_(false) {
Init();
}
void FtpDirectoryListingResponseDelegate::OnReceivedData(const char* data,
int data_len) {
// Keep the raw data in case we have to use the old parser later.
input_buffer_.append(data, data_len);
if (!parser_fallback_) {
if (buffer_.ConsumeData(data, data_len) == net::OK)
return;
parser_fallback_ = true;
}
FeedFallbackParser();
SendResponseBufferToClient();
}
void FtpDirectoryListingResponseDelegate::OnCompletedRequest() {
if (!parser_fallback_) {
if (buffer_.ProcessRemainingData() == net::OK) {
if (buffer_.EntryAvailable()) {
// Only log the server type if we got enough data to reliably detect it.
net::UpdateFtpServerTypeHistograms(buffer_.GetServerType());
}
while (buffer_.EntryAvailable())
AppendEntryToResponseBuffer(buffer_.PopEntry());
SendResponseBufferToClient();
return;
}
parser_fallback_ = true;
}
FeedFallbackParser();
SendResponseBufferToClient();
// Only log the server type if we got enough data to reliably detect it.
if (parse_state_.parsed_one)
LogFtpServerType(parse_state_.lstyle);
}
void FtpDirectoryListingResponseDelegate::Init() {
memset(&parse_state_, 0, sizeof(parse_state_));
GURL response_url(original_response_.url());
UnescapeRule::Type unescape_rules = UnescapeRule::SPACES |
UnescapeRule::URL_SPECIAL_CHARS;
std::string unescaped_path = UnescapeURLComponent(response_url.path(),
unescape_rules);
string16 path_utf16;
// Per RFC 2640, FTP servers should use UTF-8 or its proper subset ASCII,
// but many old FTP servers use legacy encodings. Try UTF-8 first and
// detect the encoding.
if (IsStringUTF8(unescaped_path)) {
path_utf16 = UTF8ToUTF16(unescaped_path);
} else {
std::string encoding = DetectEncoding(unescaped_path);
// Try the detected encoding. If it fails, resort to the
// OS native encoding.
if (encoding.empty() ||
!base::CodepageToUTF16(unescaped_path, encoding.c_str(),
base::OnStringConversionError::SUBSTITUTE,
&path_utf16))
path_utf16 = WideToUTF16Hack(base::SysNativeMBToWide(unescaped_path));
}
response_buffer_ = net::GetDirectoryListingHeader(path_utf16);
// If this isn't top level directory (i.e. the path isn't "/",)
// add a link to the parent directory.
if (response_url.path().length() > 1) {
response_buffer_.append(
net::GetDirectoryListingEntry(ASCIIToUTF16(".."),
std::string(),
false, 0,
base::Time()));
}
}
void FtpDirectoryListingResponseDelegate::FeedFallbackParser() {
// If all we've seen so far is ASCII, encoding_ is empty. Try to detect the
// encoding. We don't do the separate UTF-8 check here because the encoding
// detection with a longer chunk (as opposed to the relatively short path
// component of the url) is unlikely to mistake UTF-8 for a legacy encoding.
// If it turns out to be wrong, a separate UTF-8 check has to be added.
//
// TODO(jungshik): UTF-8 has to be 'enforced' without any heuristics when
// we're talking to an FTP server compliant to RFC 2640 (that is, its response
// to FEAT command includes 'UTF8').
// See http://wiki.filezilla-project.org/Character_Set
if (encoding_.empty())
encoding_ = DetectEncoding(input_buffer_);
std::vector<std::string> lines;
ExtractFullLinesFromBuffer(&input_buffer_, &lines);
for (std::vector<std::string>::const_iterator line = lines.begin();
line != lines.end(); ++line) {
struct net::list_result result;
int line_type = net::ParseFTPList(line->c_str(), &parse_state_, &result);
// The original code assumed months are in range 0-11 (PRExplodedTime),
// but our Time class expects a 1-12 range. Adjust it here, because
// the third-party parsing code uses bit-shifting on the month,
// and it'd be too easy to break that logic.
result.fe_time.month++;
DCHECK_LE(1, result.fe_time.month);
DCHECK_GE(12, result.fe_time.month);
int64 file_size;
switch (line_type) {
case 'd': // Directory entry.
response_buffer_.append(net::GetDirectoryListingEntry(
RawByteSequenceToFilename(result.fe_fname, encoding_),
result.fe_fname, true, 0,
base::Time::FromLocalExploded(result.fe_time)));
break;
case 'f': // File entry.
if (StringToInt64(result.fe_size, &file_size)) {
response_buffer_.append(net::GetDirectoryListingEntry(
RawByteSequenceToFilename(result.fe_fname, encoding_),
result.fe_fname, false, file_size,
base::Time::FromLocalExploded(result.fe_time)));
}
break;
case 'l': { // Symlink entry.
std::string filename(result.fe_fname, result.fe_fnlen);
// Parsers for styles 'U' and 'W' handle " -> " themselves.
if (parse_state_.lstyle != 'U' && parse_state_.lstyle != 'W') {
std::string::size_type offset = filename.find(" -> ");
if (offset != std::string::npos)
filename = filename.substr(0, offset);
}
if (StringToInt64(result.fe_size, &file_size)) {
response_buffer_.append(net::GetDirectoryListingEntry(
RawByteSequenceToFilename(filename.c_str(), encoding_),
filename, false, file_size,
base::Time::FromLocalExploded(result.fe_time)));
}
}
break;
case '?': // Junk entry.
case '"': // Comment entry.
break;
default:
NOTREACHED();
break;
}
}
}
void FtpDirectoryListingResponseDelegate::AppendEntryToResponseBuffer(
const net::FtpDirectoryListingEntry& entry) {
switch (entry.type) {
case net::FtpDirectoryListingEntry::FILE:
response_buffer_.append(
net::GetDirectoryListingEntry(entry.name, std::string(), false,
entry.size, entry.last_modified));
break;
case net::FtpDirectoryListingEntry::DIRECTORY:
response_buffer_.append(
net::GetDirectoryListingEntry(entry.name, std::string(), true,
0, entry.last_modified));
break;
case net::FtpDirectoryListingEntry::SYMLINK:
response_buffer_.append(
net::GetDirectoryListingEntry(entry.name, std::string(), false,
0, entry.last_modified));
break;
default:
NOTREACHED();
break;
}
}
void FtpDirectoryListingResponseDelegate::SendResponseBufferToClient() {
if (!response_buffer_.empty()) {
client_->didReceiveData(loader_, response_buffer_.data(),
response_buffer_.length());
response_buffer_.clear();
}
}
} // namespace webkit_glue
<|endoftext|>
|
<commit_before>/*
* =====================================================================
* Version: 1.0
* Created: 22.08.2012 15:15:54
* Author: Miroslav Bendík
* Company: LinuxOS.sk
* =====================================================================
*/
#include <cstdlib>
#include <fstream>
#include <getopt.h>
#include <iostream>
#include <map>
#include <stdint.h>
#include <string>
using namespace std;
struct Color {
uint8_t r;
uint8_t g;
uint8_t b;
};
map<string, Color> parse_colors()
{
map<string, Color> parsed;
ifstream in;
in.open("colors.txt", ifstream::in);
if (!in.is_open()) {
std::cerr << "File colors.txt does not exist" << std::endl;
exit(-2);
}
while (in.good()) {
string name;
Color color;
in >> name;
if (name[0] == '#') {
in.ignore(65536, '\n');
in >> name;
}
while (name == "\n" && in.good()) {
in >> name;
}
int r, g, b;
in >> r;
in >> g;
in >> b;
if (in.good()) {
parsed[name] = color;
color.r = r;
color.g = g;
color.b = b;
}
}
return parsed;
}
void usage()
{
const char *usage_text = "minetestmapper.py [options]\n\
-i/--input <world_path>\n\
-o/--output <output_image.png>\n\
--bgcolor <color>\n\
--scalecolor <color>\n\
--playercolor <color>\n\
--origincolor <color>\n\
--drawscale\n\
--drawplayers\n\
--draworigin\n\
--drawunderground\n\
Color format: '#000000'\n";
std::cout << usage_text;
}
int main(int argc, char *argv[])
{
static struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"input", required_argument, 0, 'i'},
{"output", required_argument, 0, 'o'},
{"bgcolor", required_argument, 0, 'b'},
{"scalecolor", required_argument, 0, 's'},
{"origincolor", required_argument, 0, 'r'},
{"playercolor", required_argument, 0, 'p'},
{"draworigin", no_argument, 0, 'R'},
{"drawplayers", no_argument, 0, 'P'},
{"drawscale", no_argument, 0, 'S'},
{"drawunderground", no_argument, 0, 'U'}
};
string input;
string output;
string bgcolor = "#ffffff";
string scalecolor = "#000000";
string origincolor = "#ff0000";
string playercolor = "#ff0000";
bool draworigin = false;
bool drawplayers = false;
bool drawscale = false;
bool drawunderground = false;
int option_index = 0;
int c = 0;
while (1) {
c = getopt_long(argc, argv, "hi:o:", long_options, &option_index);
if (c == -1) {
if (input.empty() || output.empty()) {
usage();
exit(-1);
}
break;
}
switch (c) {
case 'h':
usage();
exit(0);
break;
case 'i':
input = optarg;
break;
case 'o':
output = optarg;
break;
case 'b':
bgcolor = optarg;
break;
case 's':
scalecolor = optarg;
break;
case 'r':
origincolor = optarg;
break;
case 'p':
playercolor = optarg;
break;
case 'R':
draworigin = true;
break;
case 'P':
drawplayers = true;
break;
case 'S':
drawscale = true;
break;
case 'U':
drawunderground = true;
break;
default:
abort();
}
}
map<string, Color> colors = parse_colors();
}
<commit_msg>Added ColorMap definition.<commit_after>/*
* =====================================================================
* Version: 1.0
* Created: 22.08.2012 15:15:54
* Author: Miroslav Bendík
* Company: LinuxOS.sk
* =====================================================================
*/
#include <cstdlib>
#include <fstream>
#include <getopt.h>
#include <iostream>
#include <map>
#include <stdint.h>
#include <string>
using namespace std;
struct Color {
uint8_t r;
uint8_t g;
uint8_t b;
};
typedef map<string, Color> ColorMap;
ColorMap parse_colors()
{
ColorMap parsed;
ifstream in;
in.open("colors.txt", ifstream::in);
if (!in.is_open()) {
std::cerr << "File colors.txt does not exist" << std::endl;
exit(-2);
}
while (in.good()) {
string name;
Color color;
in >> name;
if (name[0] == '#') {
in.ignore(65536, '\n');
in >> name;
}
while (name == "\n" && in.good()) {
in >> name;
}
int r, g, b;
in >> r;
in >> g;
in >> b;
if (in.good()) {
parsed[name] = color;
color.r = r;
color.g = g;
color.b = b;
}
}
return parsed;
}
void usage()
{
const char *usage_text = "minetestmapper.py [options]\n\
-i/--input <world_path>\n\
-o/--output <output_image.png>\n\
--bgcolor <color>\n\
--scalecolor <color>\n\
--playercolor <color>\n\
--origincolor <color>\n\
--drawscale\n\
--drawplayers\n\
--draworigin\n\
--drawunderground\n\
Color format: '#000000'\n";
std::cout << usage_text;
}
int main(int argc, char *argv[])
{
static struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"input", required_argument, 0, 'i'},
{"output", required_argument, 0, 'o'},
{"bgcolor", required_argument, 0, 'b'},
{"scalecolor", required_argument, 0, 's'},
{"origincolor", required_argument, 0, 'r'},
{"playercolor", required_argument, 0, 'p'},
{"draworigin", no_argument, 0, 'R'},
{"drawplayers", no_argument, 0, 'P'},
{"drawscale", no_argument, 0, 'S'},
{"drawunderground", no_argument, 0, 'U'}
};
string input;
string output;
string bgcolor = "#ffffff";
string scalecolor = "#000000";
string origincolor = "#ff0000";
string playercolor = "#ff0000";
bool draworigin = false;
bool drawplayers = false;
bool drawscale = false;
bool drawunderground = false;
int option_index = 0;
int c = 0;
while (1) {
c = getopt_long(argc, argv, "hi:o:", long_options, &option_index);
if (c == -1) {
if (input.empty() || output.empty()) {
usage();
exit(-1);
}
break;
}
switch (c) {
case 'h':
usage();
exit(0);
break;
case 'i':
input = optarg;
break;
case 'o':
output = optarg;
break;
case 'b':
bgcolor = optarg;
break;
case 's':
scalecolor = optarg;
break;
case 'r':
origincolor = optarg;
break;
case 'p':
playercolor = optarg;
break;
case 'R':
draworigin = true;
break;
case 'P':
drawplayers = true;
break;
case 'S':
drawscale = true;
break;
case 'U':
drawunderground = true;
break;
default:
abort();
}
}
ColorMap colors = parse_colors();
}
<|endoftext|>
|
<commit_before>#pragma once
#include "Grappa.hpp"
#include "GlobalAllocator.hpp"
#include "ParallelLoop.hpp"
#include "AsyncDelegate.hpp"
#include "BufferVector.hpp"
#include "Statistics.hpp"
#include "Array.hpp"
#include "FlatCombiner.hpp"
#include <vector>
#include <unordered_set>
// for all hash tables
// GRAPPA_DECLARE_STAT(MaxStatistic<uint64_t>, max_cell_length);
GRAPPA_DECLARE_STAT(SummarizingStatistic<uint64_t>, cell_traversal_length);
GRAPPA_DECLARE_STAT(SimpleStatistic<size_t>, hashset_insert_ops);
GRAPPA_DECLARE_STAT(SimpleStatistic<size_t>, hashset_insert_msgs);
namespace Grappa {
// Hash table for joins
// * allows multiple copies of a Key
// * lookups return all Key matches
template <typename K>
// size_t NREQUESTS = 128, size_t HASH_SIZE = NREQUESTS<<3 >
class GlobalHashSet {
protected:
struct Entry {
K key;
Entry(){}
Entry(K key) : key(key) {}
};
struct Cell { // TODO: keep first few in the 64-byte block, then go to secondary storage
std::vector<Entry> entries;
char padding[64-sizeof(std::vector<Entry>)];
Cell() { entries.reserve(16); }
};
struct Proxy {
GlobalHashSet * owner;
// size_t reqs[NREQUESTS];
// size_t nreq;
std::unordered_set<K> keys_to_insert; // K keys_to_insert[HASH_SIZE];
Proxy(GlobalHashSet * owner): owner(owner), keys_to_insert(1<<14) {}
Proxy * clone_fresh() { return locale_new<Proxy>(owner); }
bool is_full() { return false; }
void insert(const K& newk) {
++hashset_insert_ops;
if (keys_to_insert.count(newk) == 0) {
keys_to_insert.insert(newk);
}
}
void sync() {
CompletionEvent ce(keys_to_insert.size());
auto cea = make_global(&ce);
for (auto& k : keys_to_insert) {
++hashset_insert_msgs;
auto cell = owner->base+owner->computeIndex(k);
send_heap_message(cell.core(), [cell,k,cea]{
Cell * c = cell.localize();
bool found = false;
for (auto& e : c->entries) if (e.key == k) { found = true; break; }
if (!found) c->entries.emplace_back(k);
complete(cea);
});
}
ce.wait();
}
};
// private members
GlobalAddress<GlobalHashSet> self;
GlobalAddress< Cell > base;
size_t capacity;
size_t count; // not maintained, just need storage for size()
FlatCombiner<Proxy> proxy;
char _pad[block_size - sizeof(self)-sizeof(base)-sizeof(capacity)-sizeof(proxy)-sizeof(count)];
uint64_t computeIndex( K key ) {
static std::hash<K> hasher;
return hasher(key) % capacity;
}
// for creating local GlobalHashSet
GlobalHashSet( GlobalAddress<GlobalHashSet> self, GlobalAddress<Cell> base, size_t capacity )
: self(self), base(base), capacity(capacity)
, proxy(locale_new<Proxy>(this))
{ }
public:
static GlobalAddress<GlobalHashSet> create(size_t total_capacity) {
auto base = global_alloc<Cell>(total_capacity);
auto self = mirrored_global_alloc<GlobalHashSet>();
call_on_all_cores([self,base,total_capacity]{
new (self.localize()) GlobalHashSet(self, base, total_capacity);
});
forall_localized(base, total_capacity, [](int64_t i, Cell& c) { new (&c) Cell(); });
return self;
}
void destroy() {
auto self = this->self;
forall_localized(this->base, this->capacity, [](Cell& c){ c.~Cell(); });
global_free(this->base);
call_on_all_cores([self]{ self->~GlobalHashSet(); });
global_free(self);
}
bool lookup ( K key ) {
uint64_t index = computeIndex( key );
GlobalAddress< Cell > target = base + index;
return delegate::call(target, [key](Cell* c) {
int64_t i;
int64_t sz = c->entries.size();
for (i = 0; i<sz; ++i) {
if ( c->entries[i].key == key ) { // typename K must implement operator==
return true;
}
}
return false;
});
}
// Inserts the key if not already in the set
//
// returns true if the set already contains the key
//
// synchronous operation
void insert( K key ) {
if (FLAGS_flat_combining) {
proxy.combine([key](Proxy& p){ p.insert(key); });
} else {
++hashset_insert_ops;
++hashset_insert_msgs;
delegate::call(base+computeIndex(key), [key](Cell * c) {
// find matching key in the list, if found, no insert necessary
for (auto& e : c->entries) if (e.key == key) return;
// this is the first time the key has been seen so add it to the list
c->entries.emplace_back( key );
return;
});
}
}
// Inserts the key if not already in the set
//
// asynchronous operation
template< typename F >
void insert_async( K key, F sync) {
proxy->insert(key);
if (proxy->is_full()) {
privateTask([this,sync]{
this->proxy.combine([](Proxy& p){});
sync();
});
}
sync();
}
void sync_all_cores() {
auto self = this->self;
on_all_cores([self]{
self->proxy.combine([](Proxy& p){});
});
}
template< GlobalCompletionEvent * GCE = &impl::local_gce, typename F = decltype(nullptr) >
void forall_keys(F visit) {
forall_localized<GCE>(base, capacity, [visit](int64_t i, Cell& c){
for (auto& e : c.entries) {
visit(e.key);
}
});
}
size_t size() {
auto self = this->self;
call_on_all_cores([self]{ self->count = 0; });
forall_keys([self](K& k){ self->count++; });
on_all_cores([self]{ self->count = allreduce<size_t,collective_add>(self->count); });
return count;
}
};
} // namespace Grappa
<commit_msg>Set fixed size for Proxy unordered_set.<commit_after>#pragma once
#include "Grappa.hpp"
#include "GlobalAllocator.hpp"
#include "ParallelLoop.hpp"
#include "AsyncDelegate.hpp"
#include "BufferVector.hpp"
#include "Statistics.hpp"
#include "Array.hpp"
#include "FlatCombiner.hpp"
#include <vector>
#include <unordered_set>
// for all hash tables
// GRAPPA_DECLARE_STAT(MaxStatistic<uint64_t>, max_cell_length);
GRAPPA_DECLARE_STAT(SummarizingStatistic<uint64_t>, cell_traversal_length);
GRAPPA_DECLARE_STAT(SimpleStatistic<size_t>, hashset_insert_ops);
GRAPPA_DECLARE_STAT(SimpleStatistic<size_t>, hashset_insert_msgs);
namespace Grappa {
// Hash table for joins
// * allows multiple copies of a Key
// * lookups return all Key matches
template <typename K>
// size_t NREQUESTS = 128, size_t HASH_SIZE = NREQUESTS<<3 >
class GlobalHashSet {
protected:
struct Entry {
K key;
Entry(){}
Entry(K key) : key(key) {}
};
struct Cell { // TODO: keep first few in the 64-byte block, then go to secondary storage
std::vector<Entry> entries;
char padding[64-sizeof(std::vector<Entry>)];
Cell() { entries.reserve(16); }
};
struct Proxy {
const size_t LOCAL_HASH_SIZE = 1<<13;
GlobalHashSet * owner;
// size_t reqs[NREQUESTS];
// size_t nreq;
std::unordered_set<K> keys_to_insert; // K keys_to_insert[HASH_SIZE];
Proxy(GlobalHashSet * owner): owner(owner), keys_to_insert(LOCAL_HASH_SIZE) {}
Proxy * clone_fresh() { return locale_new<Proxy>(owner); }
bool is_full() { return keys_to_insert.size() >= LOCAL_HASH_SIZE; }
void insert(const K& newk) {
++hashset_insert_ops;
if (keys_to_insert.count(newk) == 0) {
keys_to_insert.insert(newk);
}
}
void sync() {
CompletionEvent ce(keys_to_insert.size());
auto cea = make_global(&ce);
for (auto& k : keys_to_insert) {
++hashset_insert_msgs;
auto cell = owner->base+owner->computeIndex(k);
send_heap_message(cell.core(), [cell,k,cea]{
Cell * c = cell.localize();
bool found = false;
for (auto& e : c->entries) if (e.key == k) { found = true; break; }
if (!found) c->entries.emplace_back(k);
complete(cea);
});
}
ce.wait();
}
};
// private members
GlobalAddress<GlobalHashSet> self;
GlobalAddress< Cell > base;
size_t capacity;
size_t count; // not maintained, just need storage for size()
FlatCombiner<Proxy> proxy;
char _pad[block_size - sizeof(self)-sizeof(base)-sizeof(capacity)-sizeof(proxy)-sizeof(count)];
uint64_t computeIndex( K key ) {
static std::hash<K> hasher;
return hasher(key) % capacity;
}
// for creating local GlobalHashSet
GlobalHashSet( GlobalAddress<GlobalHashSet> self, GlobalAddress<Cell> base, size_t capacity )
: self(self), base(base), capacity(capacity)
, proxy(locale_new<Proxy>(this))
{ }
public:
static GlobalAddress<GlobalHashSet> create(size_t total_capacity) {
auto base = global_alloc<Cell>(total_capacity);
auto self = mirrored_global_alloc<GlobalHashSet>();
call_on_all_cores([self,base,total_capacity]{
new (self.localize()) GlobalHashSet(self, base, total_capacity);
});
forall_localized(base, total_capacity, [](int64_t i, Cell& c) { new (&c) Cell(); });
return self;
}
void destroy() {
auto self = this->self;
forall_localized(this->base, this->capacity, [](Cell& c){ c.~Cell(); });
global_free(this->base);
call_on_all_cores([self]{ self->~GlobalHashSet(); });
global_free(self);
}
bool lookup ( K key ) {
uint64_t index = computeIndex( key );
GlobalAddress< Cell > target = base + index;
return delegate::call(target, [key](Cell* c) {
int64_t i;
int64_t sz = c->entries.size();
for (i = 0; i<sz; ++i) {
if ( c->entries[i].key == key ) { // typename K must implement operator==
return true;
}
}
return false;
});
}
// Inserts the key if not already in the set
//
// returns true if the set already contains the key
//
// synchronous operation
void insert( K key ) {
if (FLAGS_flat_combining) {
proxy.combine([key](Proxy& p){ p.insert(key); });
} else {
++hashset_insert_ops;
++hashset_insert_msgs;
delegate::call(base+computeIndex(key), [key](Cell * c) {
// find matching key in the list, if found, no insert necessary
for (auto& e : c->entries) if (e.key == key) return;
// this is the first time the key has been seen so add it to the list
c->entries.emplace_back( key );
return;
});
}
}
// Inserts the key if not already in the set
//
// asynchronous operation
template< typename F >
void insert_async( K key, F sync) {
proxy->insert(key);
if (proxy->is_full()) {
privateTask([this,sync]{
this->proxy.combine([](Proxy& p){});
sync();
});
}
sync();
}
void sync_all_cores() {
auto self = this->self;
on_all_cores([self]{
self->proxy.combine([](Proxy& p){});
});
}
template< GlobalCompletionEvent * GCE = &impl::local_gce, typename F = decltype(nullptr) >
void forall_keys(F visit) {
forall_localized<GCE>(base, capacity, [visit](int64_t i, Cell& c){
for (auto& e : c.entries) {
visit(e.key);
}
});
}
size_t size() {
auto self = this->self;
call_on_all_cores([self]{ self->count = 0; });
forall_keys([self](K& k){ self->count++; });
on_all_cores([self]{ self->count = allreduce<size_t,collective_add>(self->count); });
return count;
}
};
} // namespace Grappa
<|endoftext|>
|
<commit_before>//===- bugpoint.cpp - The LLVM Bugpoint utility ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program is an automated compiler debugger tool. It is used to narrow
// down miscompilations and crash problems to a specific pass in the compiler,
// and the specific Module or Function input that is causing the problem.
//
//===----------------------------------------------------------------------===//
#include "BugDriver.h"
#include "llvm/Support/PassNameParser.h"
#include "Support/CommandLine.h"
#include "Config/unistd.h"
#include <sys/resource.h>
using namespace llvm;
static cl::list<std::string>
InputFilenames(cl::Positional, cl::OneOrMore,
cl::desc("<input llvm ll/bc files>"));
// The AnalysesList is automatically populated with registered Passes by the
// PassNameParser.
//
static cl::list<const PassInfo*, bool, PassNameParser>
PassList(cl::desc("Passes available:"), cl::ZeroOrMore);
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv,
" LLVM automatic testcase reducer. See\nhttp://"
"llvm.cs.uiuc.edu/docs/CommandGuide/bugpoint.html"
" for more information.\n");
BugDriver D(argv[0]);
if (D.addSources(InputFilenames)) return 1;
D.addPasses(PassList.begin(), PassList.end());
// Bugpoint has the ability of generating a plethora of core files, so to
// avoid filling up the disk, set the max core file size to 0.
struct rlimit rlim;
rlim.rlim_cur = rlim.rlim_max = 0;
int res = setrlimit(RLIMIT_CORE, &rlim);
if (res < 0) {
// setrlimit() may have failed, but we're not going to let that stop us
perror("setrlimit: RLIMIT_CORE");
}
try {
return D.run();
} catch (...) {
std::cerr << "Whoops, an exception leaked out of bugpoint. "
<< "This is a bug in bugpoint!\n";
return 1;
}
}
<commit_msg>Catch exception and print message as appropriate<commit_after>//===- bugpoint.cpp - The LLVM Bugpoint utility ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program is an automated compiler debugger tool. It is used to narrow
// down miscompilations and crash problems to a specific pass in the compiler,
// and the specific Module or Function input that is causing the problem.
//
//===----------------------------------------------------------------------===//
#include "BugDriver.h"
#include "llvm/Support/PassNameParser.h"
#include "llvm/Support/ToolRunner.h"
#include "Support/CommandLine.h"
#include "Config/unistd.h"
#include <sys/resource.h>
using namespace llvm;
static cl::list<std::string>
InputFilenames(cl::Positional, cl::OneOrMore,
cl::desc("<input llvm ll/bc files>"));
// The AnalysesList is automatically populated with registered Passes by the
// PassNameParser.
//
static cl::list<const PassInfo*, bool, PassNameParser>
PassList(cl::desc("Passes available:"), cl::ZeroOrMore);
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv,
" LLVM automatic testcase reducer. See\nhttp://"
"llvm.cs.uiuc.edu/docs/CommandGuide/bugpoint.html"
" for more information.\n");
BugDriver D(argv[0]);
if (D.addSources(InputFilenames)) return 1;
D.addPasses(PassList.begin(), PassList.end());
// Bugpoint has the ability of generating a plethora of core files, so to
// avoid filling up the disk, set the max core file size to 0.
struct rlimit rlim;
rlim.rlim_cur = rlim.rlim_max = 0;
int res = setrlimit(RLIMIT_CORE, &rlim);
if (res < 0) {
// setrlimit() may have failed, but we're not going to let that stop us
perror("setrlimit: RLIMIT_CORE");
}
try {
return D.run();
} catch (ToolExecutionError &TEE) {
std::cerr << "Tool execution error: " << TEE.getMessage() << "\n";
return 1;
} catch (...) {
std::cerr << "Whoops, an exception leaked out of bugpoint. "
<< "This is a bug in bugpoint!\n";
return 1;
}
}
<|endoftext|>
|
<commit_before>// Copyright 2019 The Bazel 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 "tools/common/file_system.h"
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string>
#ifdef __APPLE__
#include <copyfile.h>
#include <removefile.h>
#else
#include <fcntl.h>
#include <sys/sendfile.h>
#endif
#include "tools/common/path_utils.h"
std::string GetCurrentDirectory() {
// Passing null,0 causes getcwd to allocate the buffer of the correct size.
char *buffer = getcwd(nullptr, 0);
std::string cwd(buffer);
free(buffer);
return cwd;
}
bool FileExists(const std::string &path) {
return access(path.c_str(), 0) == 0;
}
bool RemoveFile(const std::string &path) {
#ifdef __APPLE__
return removefile(path.c_str(), nullptr, 0);
#elif __unix__
return remove(path.c_str());
#else
#error Only macOS and Unix are supported at this time.
#endif
}
bool CopyFile(const std::string &src, const std::string &dest) {
#ifdef __APPLE__
// The `copyfile` function with `COPYFILE_ALL` mode preserves permissions and
// modification time.
return copyfile(src.c_str(), dest.c_str(), nullptr,
COPYFILE_ALL | COPYFILE_CLONE) == 0;
#elif __unix__
// On Linux, we can use `sendfile` to copy it more easily than calling
// `read`/`write` in a loop.
struct stat stat_buf;
bool success = false;
int src_fd = open(src.c_str(), O_RDONLY);
if (src_fd) {
fstat(src_fd, &stat_buf);
int dest_fd = open(dest.c_str(), O_WRONLY | O_CREAT, stat_buf.st_mode);
if (dest_fd) {
off_t offset = 0;
if (sendfile(dest_fd, src_fd, &offset, stat_buf.st_size) != -1) {
struct timespec timespecs[2] = {stat_buf.st_atim, stat_buf.st_mtim};
futimens(dest_fd, timespecs);
success = true;
}
close(dest_fd);
}
close(src_fd);
}
return success;
#else
// TODO(allevato): If we want to support Windows in the future, we'll need to
// use something like `CopyFileA`.
#error Only macOS and Unix are supported at this time.
#endif
}
bool MakeDirs(const std::string &path, int mode) {
// If we got an empty string, we've recursed past the first segment in the
// path. Assume it exists (if it doesn't, we'll fail when we try to create a
// directory inside it).
if (path.empty()) {
return true;
}
struct stat dir_stats;
if (stat(path.c_str(), &dir_stats) == 0) {
// Return true if the directory already exists.
return S_ISDIR(dir_stats.st_mode);
}
// Recurse to create the parent directory.
if (!MakeDirs(Dirname(path).c_str(), mode)) {
return false;
}
// Create the directory that was requested.
return mkdir(path.c_str(), mode) == 0;
}
<commit_msg>Avoid the race condition if multiple calls to `MakeDirs` occur simultaneously with overlapping paths.<commit_after>// Copyright 2019 The Bazel 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 "tools/common/file_system.h"
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <cerrno>
#include <iostream>
#include <string>
#ifdef __APPLE__
#include <copyfile.h>
#include <removefile.h>
#else
#include <fcntl.h>
#include <sys/sendfile.h>
#endif
#include "tools/common/path_utils.h"
std::string GetCurrentDirectory() {
// Passing null,0 causes getcwd to allocate the buffer of the correct size.
char *buffer = getcwd(nullptr, 0);
std::string cwd(buffer);
free(buffer);
return cwd;
}
bool FileExists(const std::string &path) {
return access(path.c_str(), 0) == 0;
}
bool RemoveFile(const std::string &path) {
#ifdef __APPLE__
return removefile(path.c_str(), nullptr, 0);
#elif __unix__
return remove(path.c_str());
#else
#error Only macOS and Unix are supported at this time.
#endif
}
bool CopyFile(const std::string &src, const std::string &dest) {
#ifdef __APPLE__
// The `copyfile` function with `COPYFILE_ALL` mode preserves permissions and
// modification time.
return copyfile(src.c_str(), dest.c_str(), nullptr,
COPYFILE_ALL | COPYFILE_CLONE) == 0;
#elif __unix__
// On Linux, we can use `sendfile` to copy it more easily than calling
// `read`/`write` in a loop.
struct stat stat_buf;
bool success = false;
int src_fd = open(src.c_str(), O_RDONLY);
if (src_fd) {
fstat(src_fd, &stat_buf);
int dest_fd = open(dest.c_str(), O_WRONLY | O_CREAT, stat_buf.st_mode);
if (dest_fd) {
off_t offset = 0;
if (sendfile(dest_fd, src_fd, &offset, stat_buf.st_size) != -1) {
struct timespec timespecs[2] = {stat_buf.st_atim, stat_buf.st_mtim};
futimens(dest_fd, timespecs);
success = true;
}
close(dest_fd);
}
close(src_fd);
}
return success;
#else
// TODO(allevato): If we want to support Windows in the future, we'll need to
// use something like `CopyFileA`.
#error Only macOS and Unix are supported at this time.
#endif
}
bool MakeDirs(const std::string &path, int mode) {
// If we got an empty string, we've recursed past the first segment in the
// path. Assume it exists (if it doesn't, we'll fail when we try to create a
// directory inside it).
if (path.empty()) {
return true;
}
struct stat dir_stats;
if (stat(path.c_str(), &dir_stats) == 0) {
// Return true if the directory already exists.
if (S_ISDIR(dir_stats.st_mode)) {
return true;
}
std::cerr << "error: path already exists but is not a directory: "
<< path << "\n";
return false;
}
// Recurse to create the parent directory.
if (!MakeDirs(Dirname(path).c_str(), mode)) {
return false;
}
// Create the directory that was requested.
if (mkdir(path.c_str(), mode) == 0) {
return true;
}
// Race condition: The above call to `mkdir` could fail if there are multiple
// calls to `MakeDirs` running at the same time with overlapping paths, so
// check again to see if the directory exists despite the call failing. If it
// does, that's ok.
if (errno == EEXIST && stat(path.c_str(), &dir_stats) == 0) {
if (S_ISDIR(dir_stats.st_mode)) {
return true;
}
std::cerr << "error: path already exists but is not a directory: "
<< path << "\n";
return false;
}
std::cerr << "error: could not create directory: " << path
<< " (" << strerror(errno) << ")\n";
return false;
}
<|endoftext|>
|
<commit_before>//===- dsymutil.cpp - Debug info dumping utility for llvm -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program is a utility that aims to be a dropin replacement for
// Darwin's dsymutil.
//
//===----------------------------------------------------------------------===//
#include "dsymutil.h"
#include "DebugMap.h"
#include "MachOUtils.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Object/MachO.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/ThreadPool.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/thread.h"
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#include <string>
#include <system_error>
using namespace llvm;
using namespace llvm::cl;
using namespace llvm::dsymutil;
static OptionCategory DsymCategory("Specific Options");
static opt<bool> Help("h", desc("Alias for -help"), Hidden);
static opt<bool> Version("v", desc("Alias for -version"), Hidden);
static list<std::string> InputFiles(Positional, OneOrMore,
desc("<input files>"), cat(DsymCategory));
static opt<std::string>
OutputFileOpt("o",
desc("Specify the output file. default: <input file>.dwarf"),
value_desc("filename"), cat(DsymCategory));
static opt<std::string> OsoPrependPath(
"oso-prepend-path",
desc("Specify a directory to prepend to the paths of object files."),
value_desc("path"), cat(DsymCategory));
static opt<bool> DumpStab(
"symtab",
desc("Dumps the symbol table found in executable or object file(s) and\n"
"exits."),
init(false), cat(DsymCategory));
static alias DumpStabA("s", desc("Alias for --symtab"), aliasopt(DumpStab));
static opt<bool> FlatOut("flat",
desc("Produce a flat dSYM file (not a bundle)."),
init(false), cat(DsymCategory));
static alias FlatOutA("f", desc("Alias for --flat"), aliasopt(FlatOut));
static opt<unsigned> NumThreads(
"num-threads",
desc("Specifies the maximum number (n) of simultaneous threads to use\n"
"when linking multiple architectures."),
value_desc("n"), init(0), cat(DsymCategory));
static alias NumThreadsA("j", desc("Alias for --num-threads"),
aliasopt(NumThreads));
static opt<bool> Verbose("verbose", desc("Verbosity level"), init(false),
cat(DsymCategory));
static opt<bool>
NoOutput("no-output",
desc("Do the link in memory, but do not emit the result file."),
init(false), cat(DsymCategory));
static opt<bool>
NoTimestamp("no-swiftmodule-timestamp",
desc("Don't check timestamp for swiftmodule files."),
init(false), cat(DsymCategory));
static list<std::string> ArchFlags(
"arch",
desc("Link DWARF debug information only for specified CPU architecture\n"
"types. This option can be specified multiple times, once for each\n"
"desired architecture. All CPU architectures will be linked by\n"
"default."), value_desc("arch"),
ZeroOrMore, cat(DsymCategory));
static opt<bool>
NoODR("no-odr",
desc("Do not use ODR (One Definition Rule) for type uniquing."),
init(false), cat(DsymCategory));
static opt<bool> DumpDebugMap(
"dump-debug-map",
desc("Parse and dump the debug map to standard output. Not DWARF link "
"will take place."),
init(false), cat(DsymCategory));
static opt<bool> InputIsYAMLDebugMap(
"y", desc("Treat the input file is a YAML debug map rather than a binary."),
init(false), cat(DsymCategory));
static bool createPlistFile(llvm::StringRef BundleRoot) {
if (NoOutput)
return true;
// Create plist file to write to.
llvm::SmallString<128> InfoPlist(BundleRoot);
llvm::sys::path::append(InfoPlist, "Contents/Info.plist");
std::error_code EC;
llvm::raw_fd_ostream PL(InfoPlist, EC, llvm::sys::fs::F_Text);
if (EC) {
llvm::errs() << "error: cannot create plist file " << InfoPlist << ": "
<< EC.message() << '\n';
return false;
}
// FIXME: Use CoreFoundation to get executable bundle info. Use
// dummy values for now.
std::string bundleVersionStr = "1", bundleShortVersionStr = "1.0",
bundleIDStr;
llvm::StringRef BundleID = *llvm::sys::path::rbegin(BundleRoot);
if (llvm::sys::path::extension(BundleRoot) == ".dSYM")
bundleIDStr = llvm::sys::path::stem(BundleID);
else
bundleIDStr = BundleID;
// Print out information to the plist file.
PL << "<?xml version=\"1.0\" encoding=\"UTF-8\"\?>\n"
<< "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" "
<< "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
<< "<plist version=\"1.0\">\n"
<< "\t<dict>\n"
<< "\t\t<key>CFBundleDevelopmentRegion</key>\n"
<< "\t\t<string>English</string>\n"
<< "\t\t<key>CFBundleIdentifier</key>\n"
<< "\t\t<string>com.apple.xcode.dsym." << bundleIDStr << "</string>\n"
<< "\t\t<key>CFBundleInfoDictionaryVersion</key>\n"
<< "\t\t<string>6.0</string>\n"
<< "\t\t<key>CFBundlePackageType</key>\n"
<< "\t\t<string>dSYM</string>\n"
<< "\t\t<key>CFBundleSignature</key>\n"
<< "\t\t<string>\?\?\?\?</string>\n"
<< "\t\t<key>CFBundleShortVersionString</key>\n"
<< "\t\t<string>" << bundleShortVersionStr << "</string>\n"
<< "\t\t<key>CFBundleVersion</key>\n"
<< "\t\t<string>" << bundleVersionStr << "</string>\n"
<< "\t</dict>\n"
<< "</plist>\n";
PL.close();
return true;
}
static bool createBundleDir(llvm::StringRef BundleBase) {
if (NoOutput)
return true;
llvm::SmallString<128> Bundle(BundleBase);
llvm::sys::path::append(Bundle, "Contents", "Resources", "DWARF");
if (std::error_code EC = create_directories(Bundle.str(), true,
llvm::sys::fs::perms::all_all)) {
llvm::errs() << "error: cannot create directory " << Bundle << ": "
<< EC.message() << "\n";
return false;
}
return true;
}
static std::string getOutputFileName(llvm::StringRef InputFile) {
if (FlatOut) {
// If a flat dSYM has been requested, things are pretty simple.
if (OutputFileOpt.empty()) {
if (InputFile == "-")
return "a.out.dwarf";
return (InputFile + ".dwarf").str();
}
return OutputFileOpt;
}
// We need to create/update a dSYM bundle.
// A bundle hierarchy looks like this:
// <bundle name>.dSYM/
// Contents/
// Info.plist
// Resources/
// DWARF/
// <DWARF file(s)>
std::string DwarfFile =
InputFile == "-" ? llvm::StringRef("a.out") : InputFile;
llvm::SmallString<128> BundleDir(OutputFileOpt);
if (BundleDir.empty())
BundleDir = DwarfFile + ".dSYM";
if (!createBundleDir(BundleDir) || !createPlistFile(BundleDir))
return "";
llvm::sys::path::append(BundleDir, "Contents", "Resources", "DWARF",
llvm::sys::path::filename(DwarfFile));
return BundleDir.str();
}
static Expected<sys::fs::TempFile> createTempFile() {
llvm::SmallString<128> TmpModel;
llvm::sys::path::system_temp_directory(true, TmpModel);
llvm::sys::path::append(TmpModel, "dsym.tmp%%%%%.dwarf");
return sys::fs::TempFile::create(TmpModel);
}
namespace {
struct TempFileVector {
std::vector<sys::fs::TempFile> Files;
~TempFileVector() {
for (sys::fs::TempFile &Tmp : Files) {
if (Error E = Tmp.discard())
errs() << toString(std::move(E));
}
}
};
} // namespace
int main(int argc, char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
llvm::PrettyStackTraceProgram StackPrinter(argc, argv);
llvm::llvm_shutdown_obj Shutdown;
LinkOptions Options;
void *P = (void *)(intptr_t)getOutputFileName;
std::string SDKPath = llvm::sys::fs::getMainExecutable(argv[0], P);
SDKPath = llvm::sys::path::parent_path(SDKPath);
HideUnrelatedOptions(DsymCategory);
llvm::cl::ParseCommandLineOptions(
argc, argv,
"manipulate archived DWARF debug symbol files.\n\n"
"dsymutil links the DWARF debug information found in the object files\n"
"for the executable <input file> by using debug symbols information\n"
"contained in its symbol table.\n");
if (Help) {
PrintHelpMessage();
return 0;
}
if (Version) {
llvm::cl::PrintVersionMessage();
return 0;
}
Options.Verbose = Verbose;
Options.NoOutput = NoOutput;
Options.NoODR = NoODR;
Options.NoTimestamp = NoTimestamp;
Options.PrependPath = OsoPrependPath;
llvm::InitializeAllTargetInfos();
llvm::InitializeAllTargetMCs();
llvm::InitializeAllTargets();
llvm::InitializeAllAsmPrinters();
if (!FlatOut && OutputFileOpt == "-") {
llvm::errs() << "error: cannot emit to standard output without --flat\n";
return 1;
}
if (InputFiles.size() > 1 && FlatOut && !OutputFileOpt.empty()) {
llvm::errs() << "error: cannot use -o with multiple inputs in flat mode\n";
return 1;
}
for (const auto &Arch : ArchFlags)
if (Arch != "*" && Arch != "all" &&
!llvm::object::MachOObjectFile::isValidArch(Arch)) {
llvm::errs() << "error: Unsupported cpu architecture: '" << Arch << "'\n";
return 1;
}
for (auto &InputFile : InputFiles) {
// Dump the symbol table for each input file and requested arch
if (DumpStab) {
if (!dumpStab(InputFile, ArchFlags, OsoPrependPath))
return 1;
continue;
}
auto DebugMapPtrsOrErr = parseDebugMap(InputFile, ArchFlags, OsoPrependPath,
Verbose, InputIsYAMLDebugMap);
if (auto EC = DebugMapPtrsOrErr.getError()) {
llvm::errs() << "error: cannot parse the debug map for \"" << InputFile
<< "\": " << EC.message() << '\n';
return 1;
}
if (DebugMapPtrsOrErr->empty()) {
llvm::errs() << "error: no architecture to link\n";
return 1;
}
if (NumThreads == 0)
NumThreads = llvm::thread::hardware_concurrency();
if (DumpDebugMap || Verbose)
NumThreads = 1;
NumThreads = std::min<unsigned>(NumThreads, DebugMapPtrsOrErr->size());
// If there is more than one link to execute, we need to generate
// temporary files.
bool NeedsTempFiles = !DumpDebugMap && (*DebugMapPtrsOrErr).size() != 1;
llvm::SmallVector<MachOUtils::ArchAndFilename, 4> TempFiles;
TempFileVector TempFileStore;
for (auto &Map : *DebugMapPtrsOrErr) {
if (Verbose || DumpDebugMap)
Map->print(llvm::outs());
if (DumpDebugMap)
continue;
if (Map->begin() == Map->end())
llvm::errs() << "warning: no debug symbols in executable (-arch "
<< MachOUtils::getArchName(Map->getTriple().getArchName())
<< ")\n";
std::string OutputFile = getOutputFileName(InputFile);
std::unique_ptr<raw_fd_ostream> OS;
if (NeedsTempFiles) {
Expected<sys::fs::TempFile> T = createTempFile();
if (!T) {
errs() << toString(T.takeError());
return 1;
}
OS = make_unique<raw_fd_ostream>(T->FD, /*shouldClose*/ false);
OutputFile = T->TmpName;
TempFileStore.Files.push_back(std::move(*T));
} else {
std::error_code EC;
OS = make_unique<raw_fd_ostream>(NoOutput ? "-" : OutputFile, EC,
sys::fs::F_None);
if (EC) {
errs() << OutputFile << ": " << EC.message();
return 1;
}
}
std::atomic_char AllOK(1);
auto LinkLambda = [&]() {
AllOK.fetch_and(linkDwarf(*OS, *Map, Options));
};
// FIXME: The DwarfLinker can have some very deep recursion that can max
// out the (significantly smaller) stack when using threads. We don't
// want this limitation when we only have a single thread.
if (NumThreads == 1) {
LinkLambda();
} else {
llvm::ThreadPool Threads(NumThreads);
Threads.async(LinkLambda);
Threads.wait();
}
if (!AllOK)
return 1;
if (NeedsTempFiles)
TempFiles.emplace_back(Map->getTriple().getArchName().str(),
OutputFile);
}
if (NeedsTempFiles &&
!MachOUtils::generateUniversalBinary(
TempFiles, getOutputFileName(InputFile), Options, SDKPath))
return 1;
}
return 0;
}
<commit_msg>Try to fix the windows build.<commit_after>//===- dsymutil.cpp - Debug info dumping utility for llvm -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program is a utility that aims to be a dropin replacement for
// Darwin's dsymutil.
//
//===----------------------------------------------------------------------===//
#include "dsymutil.h"
#include "DebugMap.h"
#include "MachOUtils.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Object/MachO.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/ThreadPool.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/thread.h"
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#include <string>
#include <system_error>
using namespace llvm;
using namespace llvm::cl;
using namespace llvm::dsymutil;
static OptionCategory DsymCategory("Specific Options");
static opt<bool> Help("h", desc("Alias for -help"), Hidden);
static opt<bool> Version("v", desc("Alias for -version"), Hidden);
static list<std::string> InputFiles(Positional, OneOrMore,
desc("<input files>"), cat(DsymCategory));
static opt<std::string>
OutputFileOpt("o",
desc("Specify the output file. default: <input file>.dwarf"),
value_desc("filename"), cat(DsymCategory));
static opt<std::string> OsoPrependPath(
"oso-prepend-path",
desc("Specify a directory to prepend to the paths of object files."),
value_desc("path"), cat(DsymCategory));
static opt<bool> DumpStab(
"symtab",
desc("Dumps the symbol table found in executable or object file(s) and\n"
"exits."),
init(false), cat(DsymCategory));
static alias DumpStabA("s", desc("Alias for --symtab"), aliasopt(DumpStab));
static opt<bool> FlatOut("flat",
desc("Produce a flat dSYM file (not a bundle)."),
init(false), cat(DsymCategory));
static alias FlatOutA("f", desc("Alias for --flat"), aliasopt(FlatOut));
static opt<unsigned> NumThreads(
"num-threads",
desc("Specifies the maximum number (n) of simultaneous threads to use\n"
"when linking multiple architectures."),
value_desc("n"), init(0), cat(DsymCategory));
static alias NumThreadsA("j", desc("Alias for --num-threads"),
aliasopt(NumThreads));
static opt<bool> Verbose("verbose", desc("Verbosity level"), init(false),
cat(DsymCategory));
static opt<bool>
NoOutput("no-output",
desc("Do the link in memory, but do not emit the result file."),
init(false), cat(DsymCategory));
static opt<bool>
NoTimestamp("no-swiftmodule-timestamp",
desc("Don't check timestamp for swiftmodule files."),
init(false), cat(DsymCategory));
static list<std::string> ArchFlags(
"arch",
desc("Link DWARF debug information only for specified CPU architecture\n"
"types. This option can be specified multiple times, once for each\n"
"desired architecture. All CPU architectures will be linked by\n"
"default."), value_desc("arch"),
ZeroOrMore, cat(DsymCategory));
static opt<bool>
NoODR("no-odr",
desc("Do not use ODR (One Definition Rule) for type uniquing."),
init(false), cat(DsymCategory));
static opt<bool> DumpDebugMap(
"dump-debug-map",
desc("Parse and dump the debug map to standard output. Not DWARF link "
"will take place."),
init(false), cat(DsymCategory));
static opt<bool> InputIsYAMLDebugMap(
"y", desc("Treat the input file is a YAML debug map rather than a binary."),
init(false), cat(DsymCategory));
static bool createPlistFile(llvm::StringRef BundleRoot) {
if (NoOutput)
return true;
// Create plist file to write to.
llvm::SmallString<128> InfoPlist(BundleRoot);
llvm::sys::path::append(InfoPlist, "Contents/Info.plist");
std::error_code EC;
llvm::raw_fd_ostream PL(InfoPlist, EC, llvm::sys::fs::F_Text);
if (EC) {
llvm::errs() << "error: cannot create plist file " << InfoPlist << ": "
<< EC.message() << '\n';
return false;
}
// FIXME: Use CoreFoundation to get executable bundle info. Use
// dummy values for now.
std::string bundleVersionStr = "1", bundleShortVersionStr = "1.0",
bundleIDStr;
llvm::StringRef BundleID = *llvm::sys::path::rbegin(BundleRoot);
if (llvm::sys::path::extension(BundleRoot) == ".dSYM")
bundleIDStr = llvm::sys::path::stem(BundleID);
else
bundleIDStr = BundleID;
// Print out information to the plist file.
PL << "<?xml version=\"1.0\" encoding=\"UTF-8\"\?>\n"
<< "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" "
<< "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
<< "<plist version=\"1.0\">\n"
<< "\t<dict>\n"
<< "\t\t<key>CFBundleDevelopmentRegion</key>\n"
<< "\t\t<string>English</string>\n"
<< "\t\t<key>CFBundleIdentifier</key>\n"
<< "\t\t<string>com.apple.xcode.dsym." << bundleIDStr << "</string>\n"
<< "\t\t<key>CFBundleInfoDictionaryVersion</key>\n"
<< "\t\t<string>6.0</string>\n"
<< "\t\t<key>CFBundlePackageType</key>\n"
<< "\t\t<string>dSYM</string>\n"
<< "\t\t<key>CFBundleSignature</key>\n"
<< "\t\t<string>\?\?\?\?</string>\n"
<< "\t\t<key>CFBundleShortVersionString</key>\n"
<< "\t\t<string>" << bundleShortVersionStr << "</string>\n"
<< "\t\t<key>CFBundleVersion</key>\n"
<< "\t\t<string>" << bundleVersionStr << "</string>\n"
<< "\t</dict>\n"
<< "</plist>\n";
PL.close();
return true;
}
static bool createBundleDir(llvm::StringRef BundleBase) {
if (NoOutput)
return true;
llvm::SmallString<128> Bundle(BundleBase);
llvm::sys::path::append(Bundle, "Contents", "Resources", "DWARF");
if (std::error_code EC = create_directories(Bundle.str(), true,
llvm::sys::fs::perms::all_all)) {
llvm::errs() << "error: cannot create directory " << Bundle << ": "
<< EC.message() << "\n";
return false;
}
return true;
}
static std::string getOutputFileName(llvm::StringRef InputFile) {
if (FlatOut) {
// If a flat dSYM has been requested, things are pretty simple.
if (OutputFileOpt.empty()) {
if (InputFile == "-")
return "a.out.dwarf";
return (InputFile + ".dwarf").str();
}
return OutputFileOpt;
}
// We need to create/update a dSYM bundle.
// A bundle hierarchy looks like this:
// <bundle name>.dSYM/
// Contents/
// Info.plist
// Resources/
// DWARF/
// <DWARF file(s)>
std::string DwarfFile =
InputFile == "-" ? llvm::StringRef("a.out") : InputFile;
llvm::SmallString<128> BundleDir(OutputFileOpt);
if (BundleDir.empty())
BundleDir = DwarfFile + ".dSYM";
if (!createBundleDir(BundleDir) || !createPlistFile(BundleDir))
return "";
llvm::sys::path::append(BundleDir, "Contents", "Resources", "DWARF",
llvm::sys::path::filename(DwarfFile));
return BundleDir.str();
}
static Expected<sys::fs::TempFile> createTempFile() {
llvm::SmallString<128> TmpModel;
llvm::sys::path::system_temp_directory(true, TmpModel);
llvm::sys::path::append(TmpModel, "dsym.tmp%%%%%.dwarf");
return sys::fs::TempFile::create(TmpModel);
}
namespace {
struct TempFileVector {
std::vector<sys::fs::TempFile> Files;
~TempFileVector() {
for (sys::fs::TempFile &Tmp : Files) {
if (Error E = Tmp.discard())
errs() << toString(std::move(E));
}
}
};
} // namespace
int main(int argc, char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
llvm::PrettyStackTraceProgram StackPrinter(argc, argv);
llvm::llvm_shutdown_obj Shutdown;
LinkOptions Options;
void *P = (void *)(intptr_t)getOutputFileName;
std::string SDKPath = llvm::sys::fs::getMainExecutable(argv[0], P);
SDKPath = llvm::sys::path::parent_path(SDKPath);
HideUnrelatedOptions(DsymCategory);
llvm::cl::ParseCommandLineOptions(
argc, argv,
"manipulate archived DWARF debug symbol files.\n\n"
"dsymutil links the DWARF debug information found in the object files\n"
"for the executable <input file> by using debug symbols information\n"
"contained in its symbol table.\n");
if (Help) {
PrintHelpMessage();
return 0;
}
if (Version) {
llvm::cl::PrintVersionMessage();
return 0;
}
Options.Verbose = Verbose;
Options.NoOutput = NoOutput;
Options.NoODR = NoODR;
Options.NoTimestamp = NoTimestamp;
Options.PrependPath = OsoPrependPath;
llvm::InitializeAllTargetInfos();
llvm::InitializeAllTargetMCs();
llvm::InitializeAllTargets();
llvm::InitializeAllAsmPrinters();
if (!FlatOut && OutputFileOpt == "-") {
llvm::errs() << "error: cannot emit to standard output without --flat\n";
return 1;
}
if (InputFiles.size() > 1 && FlatOut && !OutputFileOpt.empty()) {
llvm::errs() << "error: cannot use -o with multiple inputs in flat mode\n";
return 1;
}
for (const auto &Arch : ArchFlags)
if (Arch != "*" && Arch != "all" &&
!llvm::object::MachOObjectFile::isValidArch(Arch)) {
llvm::errs() << "error: Unsupported cpu architecture: '" << Arch << "'\n";
return 1;
}
for (auto &InputFile : InputFiles) {
// Dump the symbol table for each input file and requested arch
if (DumpStab) {
if (!dumpStab(InputFile, ArchFlags, OsoPrependPath))
return 1;
continue;
}
auto DebugMapPtrsOrErr = parseDebugMap(InputFile, ArchFlags, OsoPrependPath,
Verbose, InputIsYAMLDebugMap);
if (auto EC = DebugMapPtrsOrErr.getError()) {
llvm::errs() << "error: cannot parse the debug map for \"" << InputFile
<< "\": " << EC.message() << '\n';
return 1;
}
if (DebugMapPtrsOrErr->empty()) {
llvm::errs() << "error: no architecture to link\n";
return 1;
}
if (NumThreads == 0)
NumThreads = llvm::thread::hardware_concurrency();
if (DumpDebugMap || Verbose)
NumThreads = 1;
NumThreads = std::min<unsigned>(NumThreads, DebugMapPtrsOrErr->size());
// If there is more than one link to execute, we need to generate
// temporary files.
bool NeedsTempFiles = !DumpDebugMap && (*DebugMapPtrsOrErr).size() != 1;
llvm::SmallVector<MachOUtils::ArchAndFilename, 4> TempFiles;
TempFileVector TempFileStore;
for (auto &Map : *DebugMapPtrsOrErr) {
if (Verbose || DumpDebugMap)
Map->print(llvm::outs());
if (DumpDebugMap)
continue;
if (Map->begin() == Map->end())
llvm::errs() << "warning: no debug symbols in executable (-arch "
<< MachOUtils::getArchName(Map->getTriple().getArchName())
<< ")\n";
std::string OutputFile = getOutputFileName(InputFile);
std::unique_ptr<raw_fd_ostream> OS;
if (NeedsTempFiles) {
Expected<sys::fs::TempFile> T = createTempFile();
if (!T) {
errs() << toString(T.takeError());
return 1;
}
OS = llvm::make_unique<raw_fd_ostream>(T->FD, /*shouldClose*/ false);
OutputFile = T->TmpName;
TempFileStore.Files.push_back(std::move(*T));
} else {
std::error_code EC;
OS = llvm::make_unique<raw_fd_ostream>(NoOutput ? "-" : OutputFile, EC,
sys::fs::F_None);
if (EC) {
errs() << OutputFile << ": " << EC.message();
return 1;
}
}
std::atomic_char AllOK(1);
auto LinkLambda = [&]() {
AllOK.fetch_and(linkDwarf(*OS, *Map, Options));
};
// FIXME: The DwarfLinker can have some very deep recursion that can max
// out the (significantly smaller) stack when using threads. We don't
// want this limitation when we only have a single thread.
if (NumThreads == 1) {
LinkLambda();
} else {
llvm::ThreadPool Threads(NumThreads);
Threads.async(LinkLambda);
Threads.wait();
}
if (!AllOK)
return 1;
if (NeedsTempFiles)
TempFiles.emplace_back(Map->getTriple().getArchName().str(),
OutputFile);
}
if (NeedsTempFiles &&
!MachOUtils::generateUniversalBinary(
TempFiles, getOutputFileName(InputFile), Options, SDKPath))
return 1;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: DataPointItemConverter.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: bm $ $Date: 2003-12-17 16:43:07 $
*
* 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: 2003 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CHART_DATAPOINTITEMCONVERTER_HXX
#define CHART_DATAPOINTITEMCONVERTER_HXX
#include "ItemConverter.hxx"
#include "GraphicPropertyItemConverter.hxx"
#include "chartview/NumberFormatterWrapper.hxx"
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_
#include <com/sun/star/awt/Size.hpp>
#endif
#include <memory>
#include <vector>
class SdrModel;
namespace chart
{
namespace wrapper
{
class DataPointItemConverter :
public ::comphelper::ItemConverter
{
public:
DataPointItemConverter(
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XModel > & xChartModel,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet > & rPropertySet,
SfxItemPool& rItemPool,
SdrModel& rDrawModel,
NumberFormatterWrapper * pNumFormatter,
GraphicPropertyItemConverter::eGraphicObjectType eMapTo =
GraphicPropertyItemConverter::FILLED_DATA_POINT,
::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize =
::std::auto_ptr< ::com::sun::star::awt::Size >(),
bool bIncludeStatistics = false );
virtual ~DataPointItemConverter();
virtual void FillItemSet( SfxItemSet & rOutItemSet ) const;
virtual bool ApplyItemSet( const SfxItemSet & rItemSet );
protected:
virtual const USHORT * GetWhichPairs() const;
virtual bool GetItemPropertyName( USHORT nWhichId, ::rtl::OUString & rOutName ) const;
virtual void FillSpecialItem( USHORT nWhichId, SfxItemSet & rOutItemSet ) const
throw( ::com::sun::star::uno::Exception );
virtual bool ApplySpecialItem( USHORT nWhichId, const SfxItemSet & rItemSet )
throw( ::com::sun::star::uno::Exception );
private:
::std::vector< ItemConverter * > m_aConverters;
NumberFormatterWrapper * m_pNumberFormatterWrapper;
bool m_bIncludeStatistics;
};
} // namespace wrapper
} // namespace chart
// CHART_DATAPOINTITEMCONVERTER_HXX
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.110); FILE MERGED 2005/09/05 18:42:32 rt 1.7.110.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DataPointItemConverter.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-08 00:22:09 $
*
* 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 CHART_DATAPOINTITEMCONVERTER_HXX
#define CHART_DATAPOINTITEMCONVERTER_HXX
#include "ItemConverter.hxx"
#include "GraphicPropertyItemConverter.hxx"
#include "chartview/NumberFormatterWrapper.hxx"
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_
#include <com/sun/star/awt/Size.hpp>
#endif
#include <memory>
#include <vector>
class SdrModel;
namespace chart
{
namespace wrapper
{
class DataPointItemConverter :
public ::comphelper::ItemConverter
{
public:
DataPointItemConverter(
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XModel > & xChartModel,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet > & rPropertySet,
SfxItemPool& rItemPool,
SdrModel& rDrawModel,
NumberFormatterWrapper * pNumFormatter,
GraphicPropertyItemConverter::eGraphicObjectType eMapTo =
GraphicPropertyItemConverter::FILLED_DATA_POINT,
::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize =
::std::auto_ptr< ::com::sun::star::awt::Size >(),
bool bIncludeStatistics = false );
virtual ~DataPointItemConverter();
virtual void FillItemSet( SfxItemSet & rOutItemSet ) const;
virtual bool ApplyItemSet( const SfxItemSet & rItemSet );
protected:
virtual const USHORT * GetWhichPairs() const;
virtual bool GetItemPropertyName( USHORT nWhichId, ::rtl::OUString & rOutName ) const;
virtual void FillSpecialItem( USHORT nWhichId, SfxItemSet & rOutItemSet ) const
throw( ::com::sun::star::uno::Exception );
virtual bool ApplySpecialItem( USHORT nWhichId, const SfxItemSet & rItemSet )
throw( ::com::sun::star::uno::Exception );
private:
::std::vector< ItemConverter * > m_aConverters;
NumberFormatterWrapper * m_pNumberFormatterWrapper;
bool m_bIncludeStatistics;
};
} // namespace wrapper
} // namespace chart
// CHART_DATAPOINTITEMCONVERTER_HXX
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DataPointItemConverter.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: ihi $ $Date: 2007-11-23 11:50:30 $
*
* 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 CHART_DATAPOINTITEMCONVERTER_HXX
#define CHART_DATAPOINTITEMCONVERTER_HXX
#include "ItemConverter.hxx"
#include "GraphicPropertyItemConverter.hxx"
#include "chartview/NumberFormatterWrapper.hxx"
#include <com/sun/star/chart2/XDataSeries.hpp>
#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_
#include <com/sun/star/awt/Size.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#include <memory>
#include <vector>
class SdrModel;
namespace chart
{
namespace wrapper
{
class DataPointItemConverter :
public ::comphelper::ItemConverter
{
public:
DataPointItemConverter(
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XModel > & xChartModel,
const ::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext > & xContext,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet > & rPropertySet,
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataSeries > & xSeries,
SfxItemPool& rItemPool,
SdrModel& rDrawModel,
NumberFormatterWrapper * pNumFormatter,
const ::com::sun::star::uno::Reference<
::com::sun::star::lang::XMultiServiceFactory > & xNamedPropertyContainerFactory,
GraphicPropertyItemConverter::eGraphicObjectType eMapTo =
GraphicPropertyItemConverter::FILLED_DATA_POINT,
::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize =
::std::auto_ptr< ::com::sun::star::awt::Size >(),
bool bDataSeries = false,
bool bUseSpecialFillColor = false,
sal_Int32 nSpecialFillColor = 0,
bool bOverwriteLabelsForAttributedDataPointsAlso=false,
sal_Int32 nNumberFormat=0,
sal_Int32 nPercentNumberFormat=0);
virtual ~DataPointItemConverter();
virtual void FillItemSet( SfxItemSet & rOutItemSet ) const;
virtual bool ApplyItemSet( const SfxItemSet & rItemSet );
protected:
virtual const USHORT * GetWhichPairs() const;
virtual bool GetItemProperty( tWhichIdType nWhichId, tPropertyNameWithMemberId & rOutProperty ) const;
virtual void FillSpecialItem( USHORT nWhichId, SfxItemSet & rOutItemSet ) const
throw( ::com::sun::star::uno::Exception );
virtual bool ApplySpecialItem( USHORT nWhichId, const SfxItemSet & rItemSet )
throw( ::com::sun::star::uno::Exception );
private:
::std::vector< ItemConverter * > m_aConverters;
NumberFormatterWrapper * m_pNumberFormatterWrapper;
bool m_bDataSeries;
bool m_bOverwriteLabelsForAttributedDataPointsAlso;
bool m_bColorPerPoint;
bool m_bUseSpecialFillColor;
sal_Int32 m_nSpecialFillColor;
sal_Int32 m_nNumberFormat;
sal_Int32 m_nPercentNumberFormat;
::com::sun::star::uno::Sequence< sal_Int32 > m_aAvailableLabelPlacements;
};
} // namespace wrapper
} // namespace chart
// CHART_DATAPOINTITEMCONVERTER_HXX
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.12.60); FILE MERGED 2008/04/01 10:50:21 thb 1.12.60.2: #i85898# Stripping all external header guards 2008/03/28 16:43:43 rt 1.12.60.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: DataPointItemConverter.hxx,v $
* $Revision: 1.13 $
*
* 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 CHART_DATAPOINTITEMCONVERTER_HXX
#define CHART_DATAPOINTITEMCONVERTER_HXX
#include "ItemConverter.hxx"
#include "GraphicPropertyItemConverter.hxx"
#include "chartview/NumberFormatterWrapper.hxx"
#include <com/sun/star/chart2/XDataSeries.hpp>
#include <com/sun/star/awt/Size.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <memory>
#include <vector>
class SdrModel;
namespace chart
{
namespace wrapper
{
class DataPointItemConverter :
public ::comphelper::ItemConverter
{
public:
DataPointItemConverter(
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XModel > & xChartModel,
const ::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext > & xContext,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet > & rPropertySet,
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataSeries > & xSeries,
SfxItemPool& rItemPool,
SdrModel& rDrawModel,
NumberFormatterWrapper * pNumFormatter,
const ::com::sun::star::uno::Reference<
::com::sun::star::lang::XMultiServiceFactory > & xNamedPropertyContainerFactory,
GraphicPropertyItemConverter::eGraphicObjectType eMapTo =
GraphicPropertyItemConverter::FILLED_DATA_POINT,
::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize =
::std::auto_ptr< ::com::sun::star::awt::Size >(),
bool bDataSeries = false,
bool bUseSpecialFillColor = false,
sal_Int32 nSpecialFillColor = 0,
bool bOverwriteLabelsForAttributedDataPointsAlso=false,
sal_Int32 nNumberFormat=0,
sal_Int32 nPercentNumberFormat=0);
virtual ~DataPointItemConverter();
virtual void FillItemSet( SfxItemSet & rOutItemSet ) const;
virtual bool ApplyItemSet( const SfxItemSet & rItemSet );
protected:
virtual const USHORT * GetWhichPairs() const;
virtual bool GetItemProperty( tWhichIdType nWhichId, tPropertyNameWithMemberId & rOutProperty ) const;
virtual void FillSpecialItem( USHORT nWhichId, SfxItemSet & rOutItemSet ) const
throw( ::com::sun::star::uno::Exception );
virtual bool ApplySpecialItem( USHORT nWhichId, const SfxItemSet & rItemSet )
throw( ::com::sun::star::uno::Exception );
private:
::std::vector< ItemConverter * > m_aConverters;
NumberFormatterWrapper * m_pNumberFormatterWrapper;
bool m_bDataSeries;
bool m_bOverwriteLabelsForAttributedDataPointsAlso;
bool m_bColorPerPoint;
bool m_bUseSpecialFillColor;
sal_Int32 m_nSpecialFillColor;
sal_Int32 m_nNumberFormat;
sal_Int32 m_nPercentNumberFormat;
::com::sun::star::uno::Sequence< sal_Int32 > m_aAvailableLabelPlacements;
};
} // namespace wrapper
} // namespace chart
// CHART_DATAPOINTITEMCONVERTER_HXX
#endif
<|endoftext|>
|
<commit_before>#ifndef RS_LAZY_FLAT_SET
#define RS_LAZY_FLAT_SET
#include <vector>
#include <algorithm>
#include <type_traits>
namespace rs {
template <class Key, class Less = std::less<Key>, class Equal = std::equal_to<Key>, class Alloc = std::allocator<Key>>
class LazyFlatSet {
public:
using size_type = typename std::vector<Key>::size_type;
using value_type = Key;
using reference = typename std::conditional<std::is_fundamental<Key>::value || std::is_pointer<Key>::value, value_type, value_type&>::type;
using const_reference = typename std::conditional<std::is_fundamental<Key>::value || std::is_pointer<Key>::value, value_type, const value_type&>::type;
LazyFlatSet(unsigned maxUnsortedEntries = 32) : maxUnsortedEntries_(maxUnsortedEntries) {
tempColl_.reserve(maxUnsortedEntries);
}
void insert(const value_type& k) {
auto found = std::lower_bound(coll_.begin(), coll_.end(), k, Less{});
if (found != coll_.end() && Equal{}(*found, k)) {
*found = k;
} else {
auto found = std::search_n(tempColl_.begin(), tempColl_.end(), 1, k, Equal{});
if (found != tempColl_.end()) {
*found = k;
} else {
if (tempColl_.size() == maxUnsortedEntries_) {
flush();
}
tempColl_.push_back(k);
}
}
}
bool empty() {
return coll_.empty() && tempColl_.empty();
}
void clear() {
coll_.clear();
tempColl_.clear();
}
void reserve(size_type n) {
coll_.reserve(n);
}
size_type size() {
return coll_.size() + tempColl_.size();
}
const_reference operator[](size_type n) const {
flush();
return coll_[n];
}
private:
void flush() const {
if (tempColl_.size() > 0) {
std::sort(tempColl_.begin(), tempColl_.end(), Less{});
// TODO: optimize the range insert
auto targetIter1 = coll_.cend();
auto start = tempColl_.cbegin(), sourceIter = start;
for (; sourceIter != tempColl_.cend(); ++sourceIter) {
auto targetIter2 = std::upper_bound(coll_.cbegin(), coll_.cend(), *sourceIter, Less{});
if (targetIter1 != targetIter2) {
coll_.insert(targetIter1, start, sourceIter);
start = sourceIter;
targetIter1 = targetIter2;
}
}
if (start != sourceIter) {
coll_.insert(targetIter1, start, sourceIter);
}
tempColl_.clear();
}
}
const unsigned maxUnsortedEntries_;
mutable std::vector<Key, Alloc> coll_;
mutable std::vector<Key, Alloc> tempColl_;
};
}
#endif<commit_msg>Added find/empty and a few other set-like methods<commit_after>#ifndef RS_LAZY_FLAT_SET
#define RS_LAZY_FLAT_SET
#include <vector>
#include <algorithm>
#include <type_traits>
namespace rs {
template <class Key, class Less = std::less<Key>, class Equal = std::equal_to<Key>, class Alloc = std::allocator<Key>>
class LazyFlatSet {
public:
using size_type = typename std::vector<Key>::size_type;
using value_type = Key;
using reference = typename std::conditional<std::is_fundamental<Key>::value || std::is_pointer<Key>::value, value_type, value_type&>::type;
using const_reference = typename std::conditional<std::is_fundamental<Key>::value || std::is_pointer<Key>::value, value_type, const value_type&>::type;
LazyFlatSet(unsigned maxUnsortedEntries = 32) : maxUnsortedEntries_(maxUnsortedEntries) {
tempColl_.reserve(maxUnsortedEntries);
}
void insert(const value_type& k) {
auto iter = std::lower_bound(coll_.begin(), coll_.end(), k, Less{});
if (iter != coll_.end() && Equal{}(*iter, k)) {
*iter = k;
} else {
iter = std::search_n(tempColl_.begin(), tempColl_.end(), 1, k, Equal{});
if (iter != tempColl_.end()) {
*iter = k;
} else {
if (tempColl_.size() == maxUnsortedEntries_) {
flush();
}
tempColl_.push_back(k);
}
}
}
bool empty() const {
return coll_.empty() && tempColl_.empty();
}
void clear() {
coll_.clear();
tempColl_.clear();
}
void reserve(size_type n) {
coll_.reserve(n);
}
size_type size() const {
return coll_.size() + tempColl_.size();
}
size_type count(const value_type& k) const {
size_type found = 0;
auto iter = std::lower_bound(coll_.begin(), coll_.end(), k, Less{});
if (iter != coll_.end() && Equal{}(*iter, k)) {
found = 1;
} else {
iter = std::search_n(tempColl_.begin(), tempColl_.end(), 1, k, Equal{});
if (iter != tempColl_.end()) {
found = 1;
}
}
return found;
}
bool find(const value_type& k, value_type& v) {
auto found = false;
auto iter = std::lower_bound(coll_.begin(), coll_.end(), k, Less{});
if (iter != coll_.end() && Equal{}(*iter, k)) {
v = *iter;
found = true;
} else {
iter = std::search_n(tempColl_.begin(), tempColl_.end(), 1, k, Equal{});
if (iter != tempColl_.end()) {
v = *iter;
found = true;
}
}
return found;
}
const_reference operator[](size_type n) const {
flush();
return coll_[n];
}
private:
void flush() const {
if (tempColl_.size() > 0) {
std::sort(tempColl_.begin(), tempColl_.end(), Less{});
// TODO: optimize the range insert
auto start = tempColl_.cbegin(), sourceIter = start;
auto targetIter1 = std::upper_bound(coll_.cbegin(), coll_.cend(), *sourceIter++, Less{});
for (; sourceIter != tempColl_.cend(); ++sourceIter) {
auto targetIter2 = std::upper_bound(coll_.cbegin(), coll_.cend(), *sourceIter, Less{});
if (targetIter1 != targetIter2) {
coll_.insert(targetIter1, start, sourceIter);
start = sourceIter;
targetIter1 = targetIter2;
}
}
if (start != sourceIter) {
coll_.insert(targetIter1, start, sourceIter);
}
tempColl_.clear();
}
}
const unsigned maxUnsortedEntries_;
mutable std::vector<Key, Alloc> coll_;
mutable std::vector<Key, Alloc> tempColl_;
};
}
#endif<|endoftext|>
|
<commit_before>/* Copyright 2015 Peter Goodman (peter@trailofbits.com), all rights reserved. */
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <sstream>
#include <system_error>
#include <llvm/Bitcode/ReaderWriter.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Module.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/ToolOutputFile.h>
#include "mcsema/BC/Util.h"
DECLARE_string(os);
namespace mcsema {
llvm::Function *&BlockMap::operator[](uintptr_t pc) {
return this->std::unordered_map<uintptr_t, llvm::Function *>::operator[](pc);
}
llvm::Function *BlockMap::operator[](uintptr_t pc) const {
const auto block_it = this->find(pc);
if (this->end() == block_it) {
LOG(WARNING) << "No block associated with PC " << pc;
return nullptr;
} else {
return block_it->second;
}
}
// Initialize the attributes for a lifted function.
void InitFunctionAttributes(llvm::Function *F) {
// This affects code generation. Our functions only take one argument (the
// machine state pointer) and they all tail-call to each-other. Therefore,
// it makes no sense to save/restore callee-saved registers because there
// are no real callers to care about!
F->addFnAttr(llvm::Attribute::Naked);
// Make sure functions are treated as if they return. LLVM doesn't like
// mixing must-tail-calls with no-return.
F->removeFnAttr(llvm::Attribute::NoReturn);
// Don't use any exception stuff.
F->addFnAttr(llvm::Attribute::NoUnwind);
F->removeFnAttr(llvm::Attribute::UWTable);
// To use must-tail-calls everywhere we need to use the `fast` calling
// convention, where it's up the LLVM to decide how to pass arguments.
F->setCallingConv(llvm::CallingConv::Fast);
// Mark everything for inlining.
F->addFnAttr(llvm::Attribute::InlineHint);
}
// Create a tail-call from one lifted function to another.
void AddTerminatingTailCall(llvm::Function *From, llvm::Function *To) {
if (From->isDeclaration()) {
llvm::BasicBlock::Create(From->getContext(), "entry", From);
}
AddTerminatingTailCall(&(From->back()), To);
}
void AddTerminatingTailCall(llvm::BasicBlock *B, llvm::Function *To) {
LOG_IF(ERROR, B->getTerminator() || B->getTerminatingMustTailCall())
<< "Block already has a terminator; not adding fall-through call to: "
<< (To ? To->getName().str() : "<unreachable>");
LOG_IF(FATAL, !To) << "Target block does not exist!";
llvm::IRBuilder<> ir(B);
llvm::Function *F = B->getParent();
llvm::CallInst *C = ir.CreateCall(To, {FindStatePointer(F)});
// Make sure we tail-call from one block method to another.
C->setTailCallKind(llvm::CallInst::TCK_MustTail);
C->setCallingConv(llvm::CallingConv::Fast);
ir.CreateRetVoid();
}
// Find a local variable defined in the entry block of the function. We use
// this to find register variables.
llvm::Value *FindVarInFunction(llvm::Function *F, std::string name) {
for (auto &I : F->getEntryBlock()) {
if (I.getName() == name) {
return &I;
}
}
LOG(FATAL) << "Could not find variable " << name << " in function "
<< F->getName().str();
return nullptr;
}
// Find the machine state pointer.
llvm::Value *FindStatePointer(llvm::Function *F) {
return &*F->getArgumentList().begin();
}
namespace {
// Returns a symbol name that is "correct" for the host OS.
std::string CanonicalName(const llvm::Module *M, std::string name) {
std::stringstream name_ss;
if (FLAGS_os == "mac") {
name_ss << "_";
}
name_ss << name;
return name_ss.str();
}
} // namespace
// Find a function with name `name` in the module `M`.
llvm::Function *FindFunction(const llvm::Module *M, std::string name) {
auto func_name = CanonicalName(M, name);
return M->getFunction(func_name);
}
// Find a global variable with name `name` in the module `M`.
llvm::GlobalVariable *FindGlobaVariable(const llvm::Module *M,
std::string name) {
auto var_name = CanonicalName(M, name);
return M->getGlobalVariable(var_name);
}
// Reads an LLVM module from a file.
llvm::Module *LoadModuleFromFile(std::string file_name) {
llvm::SMDiagnostic err;
auto mod_ptr = llvm::parseIRFile(file_name, err, llvm::getGlobalContext());
auto module = mod_ptr.get();
mod_ptr.release();
CHECK(nullptr != module) << "Unable to parse module file: " << file_name;
module->materializeAll(); // Just in case.
return module;
}
// Store an LLVM module into a file.
void StoreModuleToFile(llvm::Module *module, std::string file_name) {
std::error_code ec;
llvm::tool_output_file bc(file_name.c_str(), ec, llvm::sys::fs::F_None);
CHECK(!ec)
<< "Unable to open output bitcode file for writing: " << file_name;
llvm::WriteBitcodeToFile(module, bc.os());
bc.keep();
CHECK(!ec)
<< "Error writing bitcode to file: " << file_name;
}
} // namespace mcsema
<commit_msg>Don't add leading underscore to underscored symbol on mac.<commit_after>/* Copyright 2015 Peter Goodman (peter@trailofbits.com), all rights reserved. */
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <sstream>
#include <system_error>
#include <llvm/Bitcode/ReaderWriter.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Module.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/ToolOutputFile.h>
#include "mcsema/BC/Util.h"
DECLARE_string(os);
namespace mcsema {
llvm::Function *&BlockMap::operator[](uintptr_t pc) {
return this->std::unordered_map<uintptr_t, llvm::Function *>::operator[](pc);
}
llvm::Function *BlockMap::operator[](uintptr_t pc) const {
const auto block_it = this->find(pc);
if (this->end() == block_it) {
LOG(WARNING) << "No block associated with PC " << pc;
return nullptr;
} else {
return block_it->second;
}
}
// Initialize the attributes for a lifted function.
void InitFunctionAttributes(llvm::Function *F) {
// This affects code generation. Our functions only take one argument (the
// machine state pointer) and they all tail-call to each-other. Therefore,
// it makes no sense to save/restore callee-saved registers because there
// are no real callers to care about!
F->addFnAttr(llvm::Attribute::Naked);
// Make sure functions are treated as if they return. LLVM doesn't like
// mixing must-tail-calls with no-return.
F->removeFnAttr(llvm::Attribute::NoReturn);
// Don't use any exception stuff.
F->addFnAttr(llvm::Attribute::NoUnwind);
F->removeFnAttr(llvm::Attribute::UWTable);
// To use must-tail-calls everywhere we need to use the `fast` calling
// convention, where it's up the LLVM to decide how to pass arguments.
F->setCallingConv(llvm::CallingConv::Fast);
// Mark everything for inlining.
F->addFnAttr(llvm::Attribute::InlineHint);
}
// Create a tail-call from one lifted function to another.
void AddTerminatingTailCall(llvm::Function *From, llvm::Function *To) {
if (From->isDeclaration()) {
llvm::BasicBlock::Create(From->getContext(), "entry", From);
}
AddTerminatingTailCall(&(From->back()), To);
}
void AddTerminatingTailCall(llvm::BasicBlock *B, llvm::Function *To) {
LOG_IF(ERROR, B->getTerminator() || B->getTerminatingMustTailCall())
<< "Block already has a terminator; not adding fall-through call to: "
<< (To ? To->getName().str() : "<unreachable>");
LOG_IF(FATAL, !To) << "Target block does not exist!";
llvm::IRBuilder<> ir(B);
llvm::Function *F = B->getParent();
llvm::CallInst *C = ir.CreateCall(To, {FindStatePointer(F)});
// Make sure we tail-call from one block method to another.
C->setTailCallKind(llvm::CallInst::TCK_MustTail);
C->setCallingConv(llvm::CallingConv::Fast);
ir.CreateRetVoid();
}
// Find a local variable defined in the entry block of the function. We use
// this to find register variables.
llvm::Value *FindVarInFunction(llvm::Function *F, std::string name) {
for (auto &I : F->getEntryBlock()) {
if (I.getName() == name) {
return &I;
}
}
LOG(FATAL) << "Could not find variable " << name << " in function "
<< F->getName().str();
return nullptr;
}
// Find the machine state pointer.
llvm::Value *FindStatePointer(llvm::Function *F) {
return &*F->getArgumentList().begin();
}
namespace {
// Returns a symbol name that is "correct" for the host OS.
std::string CanonicalName(const llvm::Module *M, std::string name) {
std::stringstream name_ss;
if (FLAGS_os == "mac" && '_' != name[0]) {
name_ss << "_";
}
name_ss << name;
return name_ss.str();
}
} // namespace
// Find a function with name `name` in the module `M`.
llvm::Function *FindFunction(const llvm::Module *M, std::string name) {
auto func_name = CanonicalName(M, name);
return M->getFunction(func_name);
}
// Find a global variable with name `name` in the module `M`.
llvm::GlobalVariable *FindGlobaVariable(const llvm::Module *M,
std::string name) {
auto var_name = CanonicalName(M, name);
return M->getGlobalVariable(var_name);
}
// Reads an LLVM module from a file.
llvm::Module *LoadModuleFromFile(std::string file_name) {
llvm::SMDiagnostic err;
auto mod_ptr = llvm::parseIRFile(file_name, err, llvm::getGlobalContext());
auto module = mod_ptr.get();
mod_ptr.release();
CHECK(nullptr != module) << "Unable to parse module file: " << file_name;
module->materializeAll(); // Just in case.
return module;
}
// Store an LLVM module into a file.
void StoreModuleToFile(llvm::Module *module, std::string file_name) {
std::error_code ec;
llvm::tool_output_file bc(file_name.c_str(), ec, llvm::sys::fs::F_None);
CHECK(!ec)
<< "Unable to open output bitcode file for writing: " << file_name;
llvm::WriteBitcodeToFile(module, bc.os());
bc.keep();
CHECK(!ec)
<< "Error writing bitcode to file: " << file_name;
}
} // namespace mcsema
<|endoftext|>
|
<commit_before>#include "LargeRAWFile.h"
#include <sstream>
using namespace std;
LargeRAWFile::LargeRAWFile(const std::string& strFilename, uint64_t iHeaderSize):
m_StreamFile(NULL),
m_strFilename(strFilename),
m_bIsOpen(false),
m_bWritable(false),
m_iHeaderSize(iHeaderSize)
{
}
LargeRAWFile::LargeRAWFile(const std::wstring& wstrFilename, uint64_t iHeaderSize):
m_bIsOpen(false),
m_bWritable(false),
m_iHeaderSize(iHeaderSize)
{
string strFilename(wstrFilename.begin(), wstrFilename.end());
m_strFilename = strFilename;
}
LargeRAWFile::LargeRAWFile(const LargeRAWFile &other) :
m_StreamFile(NULL),
m_strFilename(other.m_strFilename),
m_bIsOpen(other.m_bIsOpen),
m_bWritable(other.m_bWritable),
m_iHeaderSize(other.m_iHeaderSize)
{
/// @todo !?!? need a better fix, a copy constructor shouldn't be expensive.
assert(!m_bWritable && "Copying a file in write mode is too expensive.");
if(m_bIsOpen) {
Open(false);
}
}
bool LargeRAWFile::Open(bool bReadWrite) {
#ifdef _WIN32
m_StreamFile = CreateFileA(m_strFilename.c_str(),
(bReadWrite) ? GENERIC_READ | GENERIC_WRITE
: GENERIC_READ,
FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
m_bIsOpen = m_StreamFile != INVALID_HANDLE_VALUE;
#else
m_StreamFile = fopen(m_strFilename.c_str(), (bReadWrite) ? "r+b" : "rb");
if(m_StreamFile == NULL) {
std::ostringstream err_file;
err_file << "fopen '" << m_strFilename << "'";
perror(err_file.str().c_str());
}
m_bIsOpen = m_StreamFile != NULL;
#endif
if (m_bIsOpen && m_iHeaderSize != 0) SeekStart();
m_bWritable = (m_bIsOpen) ? bReadWrite : false;
return m_bIsOpen;
}
bool LargeRAWFile::Create(uint64_t iInitialSize) {
#ifdef _WIN32
m_StreamFile = CreateFileA(m_strFilename.c_str(),
GENERIC_READ | GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, 0, NULL);
m_bIsOpen = m_StreamFile != INVALID_HANDLE_VALUE;
#else
m_StreamFile = fopen(m_strFilename.c_str(), "w+b");
m_bIsOpen = m_StreamFile != NULL;
#endif
if (m_bIsOpen && iInitialSize>0) {
SeekPos(iInitialSize-1);
WriteData<unsigned char>(0,false);
SeekStart();
}
m_bWritable = m_bIsOpen;
return m_bIsOpen;
}
bool LargeRAWFile::Append() {
#ifdef _WIN32
m_StreamFile = CreateFileA(m_strFilename.c_str(),
GENERIC_READ | GENERIC_WRITE, 0, NULL,
OPEN_ALWAYS, 0, NULL);
m_bIsOpen = m_StreamFile != INVALID_HANDLE_VALUE;
#else
m_StreamFile = fopen(m_strFilename.c_str(), "a+b");
m_bIsOpen = m_StreamFile != NULL;
#endif
if (m_bIsOpen) SeekEnd();
m_bWritable = m_bIsOpen;
return m_bIsOpen;
}
void LargeRAWFile::Close() {
if (m_bIsOpen) {
#ifdef _WIN32
CloseHandle(m_StreamFile);
#else
fclose(m_StreamFile);
#endif
m_bIsOpen =false;
}
}
uint64_t LargeRAWFile::GetCurrentSize() {
uint64_t iPrevPos = GetPos();
SeekStart();
uint64_t ulStart = GetPos();
uint64_t ulEnd = SeekEnd();
uint64_t ulFileLength = ulEnd - ulStart;
SeekPos(iPrevPos);
return ulFileLength;
}
void LargeRAWFile::SeekStart() {
SeekPos(0);
}
uint64_t LargeRAWFile::SeekEnd() {
#ifdef _WIN32
LARGE_INTEGER liTarget, liRealTarget; liTarget.QuadPart = 0;
SetFilePointerEx(m_StreamFile, liTarget, &liRealTarget, FILE_END);
return uint64_t(liRealTarget.QuadPart)-m_iHeaderSize;
#else
// get current position=file size!
if(fseeko(m_StreamFile, 0, SEEK_END)==0)
return ftello(m_StreamFile)-m_iHeaderSize;
else
return 0;
#endif
}
uint64_t LargeRAWFile::GetPos() {
#ifdef _WIN32
LARGE_INTEGER liTarget, liRealTarget; liTarget.QuadPart = 0;
SetFilePointerEx(m_StreamFile, liTarget, &liRealTarget, FILE_CURRENT);
return uint64_t(liRealTarget.QuadPart)-m_iHeaderSize;
#else
//get current position=file size!
return ftello(m_StreamFile)-m_iHeaderSize;
#endif
}
void LargeRAWFile::SeekPos(uint64_t iPos) {
#ifdef _WIN32
LARGE_INTEGER liTarget; liTarget.QuadPart = LONGLONG(iPos+m_iHeaderSize);
SetFilePointerEx(m_StreamFile, liTarget, NULL, FILE_BEGIN);
#else
fseeko(m_StreamFile, off_t(iPos+m_iHeaderSize), SEEK_SET);
#endif
}
size_t LargeRAWFile::ReadRAW(unsigned char* pData, uint64_t iCount) {
#ifdef _WIN32
DWORD dwReadBytes;
ReadFile(m_StreamFile, pData, DWORD(iCount), &dwReadBytes, NULL);
return dwReadBytes;
#else
return fread(pData,1,iCount,m_StreamFile);
#endif
}
size_t LargeRAWFile::WriteRAW(const unsigned char* pData, uint64_t iCount) {
#ifdef _WIN32
DWORD dwWrittenBytes;
WriteFile(m_StreamFile, pData, DWORD(iCount), &dwWrittenBytes, NULL);
return dwWrittenBytes;
#else
return fwrite(pData,1,iCount,m_StreamFile);
#endif
}
bool LargeRAWFile::CopyRAW(uint64_t iCount, uint64_t iSourcePos, uint64_t iTargetPos,
unsigned char* pBuffer, uint64_t iBufferSize) {
uint64_t iBytesRead = 0;
do {
SeekPos(iSourcePos+iBytesRead);
uint64_t iBytesJustRead = ReadRAW(pBuffer,min(iBufferSize,iCount-iBytesRead));
SeekPos(iTargetPos+iBytesRead);
uint64_t iBytesJustWritten = WriteRAW(pBuffer, iBytesJustRead);
if (iBytesJustRead != iBytesJustWritten) return false;
iBytesRead += iBytesJustRead;
} while(iBytesRead < iCount);
return true;
}
void LargeRAWFile::Delete() {
if (m_bIsOpen) Close();
remove(m_strFilename.c_str());
}
bool LargeRAWFile::Truncate() {
#ifdef _WIN32
return 0 != SetEndOfFile(m_StreamFile);
#else
uint64_t iPos = GetPos();
return 0 == ftruncate(fileno(m_StreamFile), off_t(iPos));
#endif
}
bool LargeRAWFile::Truncate(uint64_t iPos) {
#ifdef _WIN32
SeekPos(iPos);
return 0 != SetEndOfFile(m_StreamFile);
#else
return 0 == ftruncate(fileno(m_StreamFile), off_t(iPos+m_iHeaderSize));
#endif
}
// no-op, but I want to leave the argument names in the header so it's nicer to
// implement it here.
void LargeRAWFile::Hint(IOHint, uint64_t, uint64_t) const { }
bool LargeRAWFile::Copy(const std::string& strSource,
const std::string& strTarget, uint64_t iSourceHeaderSkip,
std::string* strMessage) {
std::wstring wstrSource(strSource.begin(), strSource.end());
std::wstring wstrTarget(strTarget.begin(), strTarget.end());
if (!strMessage)
return Copy(wstrSource, wstrTarget, iSourceHeaderSkip, NULL);
else {
std::wstring wstrMessage;
bool bResult = Copy(wstrSource, wstrTarget, iSourceHeaderSkip,
&wstrMessage);
(*strMessage) = string(wstrMessage.begin(), wstrMessage.end());
return bResult;
}
}
bool LargeRAWFile::Copy(const std::wstring& wstrSource,
const std::wstring& wstrTarget,
uint64_t iSourceHeaderSkip, std::wstring* wstrMessage) {
LargeRAWFile source(wstrSource, iSourceHeaderSkip);
LargeRAWFile target(wstrTarget);
source.Open(false);
if (!source.IsOpen()) {
if (wstrMessage) (*wstrMessage) = L"Unable to open source file " +
wstrSource;
return false;
}
target.Create();
if (!target.IsOpen()) {
if (wstrMessage) (*wstrMessage) = L"Unable to open target file " +
wstrTarget;
source.Close();
return false;
}
uint64_t iFileSize = source.GetCurrentSize();
uint64_t iCopySize = min(iFileSize,BLOCK_COPY_SIZE);
unsigned char* pBuffer = new unsigned char[size_t(iCopySize)];
do {
iCopySize = source.ReadRAW(pBuffer, iCopySize);
target.WriteRAW(pBuffer, iCopySize);
} while (iCopySize>0);
target.Close();
source.Close();
return true;
}
bool LargeRAWFile::Compare(const std::string& strFirstFile,
const std::string& strSecondFile,
std::string* strMessage) {
std::wstring wstrFirstFile(strFirstFile.begin(), strFirstFile.end());
std::wstring wstrSecondFile(strSecondFile.begin(), strSecondFile.end());
if (!strMessage)
return Compare(wstrFirstFile, wstrSecondFile, NULL);
else {
std::wstring wstrMessage;
bool bResult = Compare(wstrFirstFile, wstrSecondFile, &wstrMessage);
(*strMessage) = string(wstrMessage.begin(), wstrMessage.end());
return bResult;
}
}
bool LargeRAWFile::Compare(const std::wstring& wstrFirstFile,
const std::wstring& wstrSecondFile,
std::wstring* wstrMessage) {
LargeRAWFile first(wstrFirstFile);
LargeRAWFile second(wstrSecondFile);
first.Open(false);
if (!first.IsOpen()) {
if (wstrMessage) (*wstrMessage) = L"Unable to open input file " +
wstrFirstFile;
return false;
}
second.Open(false);
if (!second.IsOpen()) {
if (wstrMessage) (*wstrMessage) = L"Unable to open input file " +
wstrSecondFile;
first.Close();
return false;
}
if (first.GetCurrentSize() != second.GetCurrentSize()) {
first.Close();
second.Close();
if (wstrMessage) (*wstrMessage) = L"Files differ in size";
return false;
}
uint64_t iFileSize = first.GetCurrentSize();
uint64_t iCopySize = min(iFileSize,BLOCK_COPY_SIZE/2);
unsigned char* pBuffer1 = new unsigned char[size_t(iCopySize)];
unsigned char* pBuffer2 = new unsigned char[size_t(iCopySize)];
uint64_t iCopiedSize = 0;
uint64_t iDiffCount = 0;
if (wstrMessage) (*wstrMessage) = L"";
do {
iCopySize = first.ReadRAW(pBuffer1, iCopySize);
second.ReadRAW(pBuffer2, iCopySize);
for (uint64_t i = 0;i<iCopySize;i++) {
if (pBuffer1[i] != pBuffer2[i]) {
if (wstrMessage) {
wstringstream ss;
if (iDiffCount == 0) {
ss << L"Files differ at address " << i+iCopiedSize;
iDiffCount = 1;
} else {
// don't report more than 10 differences.
if (++iDiffCount == 10) {
(*wstrMessage) += L" and more";
delete [] pBuffer1;
delete [] pBuffer2;
first.Close();
second.Close();
return false;
} else {
ss << L", " << i+iCopiedSize;
}
}
(*wstrMessage) +=ss.str();
}
}
}
iCopiedSize += iCopySize;
} while (iCopySize > 0);
first.Close();
second.Close();
delete [] pBuffer1;
delete [] pBuffer2;
return iDiffCount == 0;
}
<commit_msg>Use a shared_ptr to fix a memory leak.<commit_after>#include <sstream>
#ifdef _MSC_VER
# include <memory>
#else
# include <tr1/memory>
#endif
#include "LargeRAWFile.h"
#include "nonstd.h"
using namespace std;
LargeRAWFile::LargeRAWFile(const std::string& strFilename, uint64_t iHeaderSize):
m_StreamFile(NULL),
m_strFilename(strFilename),
m_bIsOpen(false),
m_bWritable(false),
m_iHeaderSize(iHeaderSize)
{
}
LargeRAWFile::LargeRAWFile(const std::wstring& wstrFilename, uint64_t iHeaderSize):
m_bIsOpen(false),
m_bWritable(false),
m_iHeaderSize(iHeaderSize)
{
string strFilename(wstrFilename.begin(), wstrFilename.end());
m_strFilename = strFilename;
}
LargeRAWFile::LargeRAWFile(const LargeRAWFile &other) :
m_StreamFile(NULL),
m_strFilename(other.m_strFilename),
m_bIsOpen(other.m_bIsOpen),
m_bWritable(other.m_bWritable),
m_iHeaderSize(other.m_iHeaderSize)
{
/// @todo !?!? need a better fix, a copy constructor shouldn't be expensive.
assert(!m_bWritable && "Copying a file in write mode is too expensive.");
if(m_bIsOpen) {
Open(false);
}
}
bool LargeRAWFile::Open(bool bReadWrite) {
#ifdef _WIN32
m_StreamFile = CreateFileA(m_strFilename.c_str(),
(bReadWrite) ? GENERIC_READ | GENERIC_WRITE
: GENERIC_READ,
FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
m_bIsOpen = m_StreamFile != INVALID_HANDLE_VALUE;
#else
m_StreamFile = fopen(m_strFilename.c_str(), (bReadWrite) ? "r+b" : "rb");
if(m_StreamFile == NULL) {
std::ostringstream err_file;
err_file << "fopen '" << m_strFilename << "'";
perror(err_file.str().c_str());
}
m_bIsOpen = m_StreamFile != NULL;
#endif
if (m_bIsOpen && m_iHeaderSize != 0) SeekStart();
m_bWritable = (m_bIsOpen) ? bReadWrite : false;
return m_bIsOpen;
}
bool LargeRAWFile::Create(uint64_t iInitialSize) {
#ifdef _WIN32
m_StreamFile = CreateFileA(m_strFilename.c_str(),
GENERIC_READ | GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, 0, NULL);
m_bIsOpen = m_StreamFile != INVALID_HANDLE_VALUE;
#else
m_StreamFile = fopen(m_strFilename.c_str(), "w+b");
m_bIsOpen = m_StreamFile != NULL;
#endif
if (m_bIsOpen && iInitialSize>0) {
SeekPos(iInitialSize-1);
WriteData<unsigned char>(0,false);
SeekStart();
}
m_bWritable = m_bIsOpen;
return m_bIsOpen;
}
bool LargeRAWFile::Append() {
#ifdef _WIN32
m_StreamFile = CreateFileA(m_strFilename.c_str(),
GENERIC_READ | GENERIC_WRITE, 0, NULL,
OPEN_ALWAYS, 0, NULL);
m_bIsOpen = m_StreamFile != INVALID_HANDLE_VALUE;
#else
m_StreamFile = fopen(m_strFilename.c_str(), "a+b");
m_bIsOpen = m_StreamFile != NULL;
#endif
if (m_bIsOpen) SeekEnd();
m_bWritable = m_bIsOpen;
return m_bIsOpen;
}
void LargeRAWFile::Close() {
if (m_bIsOpen) {
#ifdef _WIN32
CloseHandle(m_StreamFile);
#else
fclose(m_StreamFile);
#endif
m_bIsOpen =false;
}
}
uint64_t LargeRAWFile::GetCurrentSize() {
uint64_t iPrevPos = GetPos();
SeekStart();
uint64_t ulStart = GetPos();
uint64_t ulEnd = SeekEnd();
uint64_t ulFileLength = ulEnd - ulStart;
SeekPos(iPrevPos);
return ulFileLength;
}
void LargeRAWFile::SeekStart() {
SeekPos(0);
}
uint64_t LargeRAWFile::SeekEnd() {
#ifdef _WIN32
LARGE_INTEGER liTarget, liRealTarget; liTarget.QuadPart = 0;
SetFilePointerEx(m_StreamFile, liTarget, &liRealTarget, FILE_END);
return uint64_t(liRealTarget.QuadPart)-m_iHeaderSize;
#else
// get current position=file size!
if(fseeko(m_StreamFile, 0, SEEK_END)==0)
return ftello(m_StreamFile)-m_iHeaderSize;
else
return 0;
#endif
}
uint64_t LargeRAWFile::GetPos() {
#ifdef _WIN32
LARGE_INTEGER liTarget, liRealTarget; liTarget.QuadPart = 0;
SetFilePointerEx(m_StreamFile, liTarget, &liRealTarget, FILE_CURRENT);
return uint64_t(liRealTarget.QuadPart)-m_iHeaderSize;
#else
//get current position=file size!
return ftello(m_StreamFile)-m_iHeaderSize;
#endif
}
void LargeRAWFile::SeekPos(uint64_t iPos) {
#ifdef _WIN32
LARGE_INTEGER liTarget; liTarget.QuadPart = LONGLONG(iPos+m_iHeaderSize);
SetFilePointerEx(m_StreamFile, liTarget, NULL, FILE_BEGIN);
#else
fseeko(m_StreamFile, off_t(iPos+m_iHeaderSize), SEEK_SET);
#endif
}
size_t LargeRAWFile::ReadRAW(unsigned char* pData, uint64_t iCount) {
#ifdef _WIN32
DWORD dwReadBytes;
ReadFile(m_StreamFile, pData, DWORD(iCount), &dwReadBytes, NULL);
return dwReadBytes;
#else
return fread(pData,1,iCount,m_StreamFile);
#endif
}
size_t LargeRAWFile::WriteRAW(const unsigned char* pData, uint64_t iCount) {
#ifdef _WIN32
DWORD dwWrittenBytes;
WriteFile(m_StreamFile, pData, DWORD(iCount), &dwWrittenBytes, NULL);
return dwWrittenBytes;
#else
return fwrite(pData,1,iCount,m_StreamFile);
#endif
}
bool LargeRAWFile::CopyRAW(uint64_t iCount, uint64_t iSourcePos, uint64_t iTargetPos,
unsigned char* pBuffer, uint64_t iBufferSize) {
uint64_t iBytesRead = 0;
do {
SeekPos(iSourcePos+iBytesRead);
uint64_t iBytesJustRead = ReadRAW(pBuffer,min(iBufferSize,iCount-iBytesRead));
SeekPos(iTargetPos+iBytesRead);
uint64_t iBytesJustWritten = WriteRAW(pBuffer, iBytesJustRead);
if (iBytesJustRead != iBytesJustWritten) return false;
iBytesRead += iBytesJustRead;
} while(iBytesRead < iCount);
return true;
}
void LargeRAWFile::Delete() {
if (m_bIsOpen) Close();
remove(m_strFilename.c_str());
}
bool LargeRAWFile::Truncate() {
#ifdef _WIN32
return 0 != SetEndOfFile(m_StreamFile);
#else
uint64_t iPos = GetPos();
return 0 == ftruncate(fileno(m_StreamFile), off_t(iPos));
#endif
}
bool LargeRAWFile::Truncate(uint64_t iPos) {
#ifdef _WIN32
SeekPos(iPos);
return 0 != SetEndOfFile(m_StreamFile);
#else
return 0 == ftruncate(fileno(m_StreamFile), off_t(iPos+m_iHeaderSize));
#endif
}
// no-op, but I want to leave the argument names in the header so it's nicer to
// implement it here.
void LargeRAWFile::Hint(IOHint, uint64_t, uint64_t) const { }
bool LargeRAWFile::Copy(const std::string& strSource,
const std::string& strTarget, uint64_t iSourceHeaderSkip,
std::string* strMessage) {
std::wstring wstrSource(strSource.begin(), strSource.end());
std::wstring wstrTarget(strTarget.begin(), strTarget.end());
if (!strMessage)
return Copy(wstrSource, wstrTarget, iSourceHeaderSkip, NULL);
else {
std::wstring wstrMessage;
bool bResult = Copy(wstrSource, wstrTarget, iSourceHeaderSkip,
&wstrMessage);
(*strMessage) = string(wstrMessage.begin(), wstrMessage.end());
return bResult;
}
}
bool LargeRAWFile::Copy(const std::wstring& wstrSource,
const std::wstring& wstrTarget,
uint64_t iSourceHeaderSkip, std::wstring* wstrMessage) {
LargeRAWFile source(wstrSource, iSourceHeaderSkip);
LargeRAWFile target(wstrTarget);
source.Open(false);
if (!source.IsOpen()) {
if (wstrMessage) (*wstrMessage) = L"Unable to open source file " +
wstrSource;
return false;
}
target.Create();
if (!target.IsOpen()) {
if (wstrMessage) (*wstrMessage) = L"Unable to open target file " +
wstrTarget;
source.Close();
return false;
}
uint64_t iFileSize = source.GetCurrentSize();
uint64_t iCopySize = min(iFileSize,BLOCK_COPY_SIZE);
std::tr1::shared_ptr<unsigned char> pBuffer(
new unsigned char[size_t(iCopySize)],
nonstd::DeleteArray<unsigned char>()
);
do {
iCopySize = source.ReadRAW(pBuffer.get(), iCopySize);
target.WriteRAW(pBuffer.get(), iCopySize);
} while (iCopySize>0);
target.Close();
source.Close();
return true;
}
bool LargeRAWFile::Compare(const std::string& strFirstFile,
const std::string& strSecondFile,
std::string* strMessage) {
std::wstring wstrFirstFile(strFirstFile.begin(), strFirstFile.end());
std::wstring wstrSecondFile(strSecondFile.begin(), strSecondFile.end());
if (!strMessage)
return Compare(wstrFirstFile, wstrSecondFile, NULL);
else {
std::wstring wstrMessage;
bool bResult = Compare(wstrFirstFile, wstrSecondFile, &wstrMessage);
(*strMessage) = string(wstrMessage.begin(), wstrMessage.end());
return bResult;
}
}
bool LargeRAWFile::Compare(const std::wstring& wstrFirstFile,
const std::wstring& wstrSecondFile,
std::wstring* wstrMessage) {
LargeRAWFile first(wstrFirstFile);
LargeRAWFile second(wstrSecondFile);
first.Open(false);
if (!first.IsOpen()) {
if (wstrMessage) (*wstrMessage) = L"Unable to open input file " +
wstrFirstFile;
return false;
}
second.Open(false);
if (!second.IsOpen()) {
if (wstrMessage) (*wstrMessage) = L"Unable to open input file " +
wstrSecondFile;
first.Close();
return false;
}
if (first.GetCurrentSize() != second.GetCurrentSize()) {
first.Close();
second.Close();
if (wstrMessage) (*wstrMessage) = L"Files differ in size";
return false;
}
uint64_t iFileSize = first.GetCurrentSize();
uint64_t iCopySize = min(iFileSize,BLOCK_COPY_SIZE/2);
unsigned char* pBuffer1 = new unsigned char[size_t(iCopySize)];
unsigned char* pBuffer2 = new unsigned char[size_t(iCopySize)];
uint64_t iCopiedSize = 0;
uint64_t iDiffCount = 0;
if (wstrMessage) (*wstrMessage) = L"";
do {
iCopySize = first.ReadRAW(pBuffer1, iCopySize);
second.ReadRAW(pBuffer2, iCopySize);
for (uint64_t i = 0;i<iCopySize;i++) {
if (pBuffer1[i] != pBuffer2[i]) {
if (wstrMessage) {
wstringstream ss;
if (iDiffCount == 0) {
ss << L"Files differ at address " << i+iCopiedSize;
iDiffCount = 1;
} else {
// don't report more than 10 differences.
if (++iDiffCount == 10) {
(*wstrMessage) += L" and more";
delete [] pBuffer1;
delete [] pBuffer2;
first.Close();
second.Close();
return false;
} else {
ss << L", " << i+iCopiedSize;
}
}
(*wstrMessage) +=ss.str();
}
}
}
iCopiedSize += iCopySize;
} while (iCopySize > 0);
first.Close();
second.Close();
delete [] pBuffer1;
delete [] pBuffer2;
return iDiffCount == 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/test/unit_test.hpp>
#include <iostream>
#include "main.h"
#include "util.h"
#include "serialize.h"
#include "version.h"
#include "data/sighash.json.h"
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_utils.h"
#include "json/json_spirit_writer_template.h"
using namespace json_spirit;
extern Array read_json(const std::string& jsondata);
extern uint256 SignatureHash(const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
// Old script.cpp SignatureHash function
uint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
{
if (nIn >= txTo.vin.size())
{
printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
return 1;
}
CTransaction txTmp(txTo);
// In case concatenating two scripts ends up with two codeseparators,
// or an extra one at the end, this prevents all those possible incompatibilities.
scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
// Blank out other inputs' signatures
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
txTmp.vin[i].scriptSig = CScript();
txTmp.vin[nIn].scriptSig = scriptCode;
// Blank out some of the outputs
if ((nHashType & 0x1f) == SIGHASH_NONE)
{
// Wildcard payee
txTmp.vout.clear();
// Let the others update at will
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
if (i != nIn)
txTmp.vin[i].nSequence = 0;
}
else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
{
// Only lock-in the txout payee at same index as txin
unsigned int nOut = nIn;
if (nOut >= txTmp.vout.size())
{
printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
return 1;
}
txTmp.vout.resize(nOut+1);
for (unsigned int i = 0; i < nOut; i++)
txTmp.vout[i].SetNull();
// Let the others update at will
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
if (i != nIn)
txTmp.vin[i].nSequence = 0;
}
// Blank out other inputs completely, not recommended for open transactions
if (nHashType & SIGHASH_ANYONECANPAY)
{
txTmp.vin[0] = txTmp.vin[nIn];
txTmp.vin.resize(1);
}
// Serialize and hash
CHashWriter ss(SER_GETHASH, 0);
ss << txTmp << nHashType;
return ss.GetHash();
}
void static RandomScript(CScript &script) {
static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR};
script = CScript();
int ops = (insecure_rand() % 10);
for (int i=0; i<ops; i++)
script << oplist[insecure_rand() % (sizeof(oplist)/sizeof(oplist[0]))];
}
void static RandomTransaction(CTransaction &tx, bool fSingle) {
tx.nVersion = insecure_rand();
tx.vin.clear();
tx.vout.clear();
tx.nLockTime = (insecure_rand() % 2) ? insecure_rand() : 0;
int ins = (insecure_rand() % 4) + 1;
int outs = fSingle ? ins : (insecure_rand() % 4) + 1;
for (int in = 0; in < ins; in++) {
tx.vin.push_back(CTxIn());
CTxIn &txin = tx.vin.back();
txin.prevout.hash = GetRandHash();
txin.prevout.n = insecure_rand() % 4;
RandomScript(txin.scriptSig);
txin.nSequence = (insecure_rand() % 2) ? insecure_rand() : (unsigned int)-1;
}
for (int out = 0; out < outs; out++) {
tx.vout.push_back(CTxOut());
CTxOut &txout = tx.vout.back();
txout.nValue = insecure_rand() % 100000000;
RandomScript(txout.scriptPubKey);
}
}
BOOST_AUTO_TEST_SUITE(sighash_tests)
BOOST_AUTO_TEST_CASE(sighash_test)
{
seed_insecure_rand(false);
#if defined(PRINT_SIGHASH_JSON)
std::cout << "[\n";
std::cout << "\t[\"raw_transaction, script, input_index, hashType, signature_hash (result)\"],\n";
#endif
int nRandomTests = 50000;
#if defined(PRINT_SIGHASH_JSON)
nRandomTests = 500;
#endif
for (int i=0; i<nRandomTests; i++) {
int nHashType = insecure_rand();
CTransaction txTo;
RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE);
CScript scriptCode;
RandomScript(scriptCode);
int nIn = insecure_rand() % txTo.vin.size();
uint256 sh, sho;
sho = SignatureHashOld(scriptCode, txTo, nIn, nHashType);
sh = SignatureHash(scriptCode, txTo, nIn, nHashType);
#if defined(PRINT_SIGHASH_JSON)
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << txTo;
std::cout << "\t[\"" ;
std::cout << HexStr(ss.begin(), ss.end()) << "\", \"";
std::cout << HexStr(scriptCode) << "\", ";
std::cout << nIn << ", ";
std::cout << nHashType << ", \"";
std::cout << sho.GetHex() << "\"]";
if (i+1 != nRandomTests) {
std::cout << ",";
}
std::cout << "\n";
#endif
BOOST_CHECK(sh == sho);
}
#if defined(PRINT_SIGHASH_JSON)
std::cout << "]\n";
#endif
}
// Goal: check that SignatureHash generates correct hash
BOOST_AUTO_TEST_CASE(sighash_from_data)
{
Array tests = read_json(std::string(json_tests::sighash, json_tests::sighash + sizeof(json_tests::sighash)));
BOOST_FOREACH(Value& tv, tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 1) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
if (test.size() == 1) continue; // comment
std::string raw_tx = test[0].get_str();
std::string raw_script = test[1].get_str();
int nIn = test[2].get_int();
int nHashType = test[3].get_int();
std::string sigHashHex = test[4].get_str();
uint256 sh;
CDataStream stream(ParseHex(raw_tx), SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
stream >> tx;
CValidationState state;
BOOST_CHECK_MESSAGE(CheckTransaction(tx, state), strTest);
BOOST_CHECK(state.IsValid());
CScript scriptCode = CScript();
std::vector<unsigned char> raw = ParseHex(raw_script);
scriptCode.insert(scriptCode.end(), raw.begin(), raw.end());
sh = SignatureHash(scriptCode, tx, nIn, nHashType);
BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest);
}
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>add checks for deserialization errors<commit_after>// Copyright (c) 2013 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/test/unit_test.hpp>
#include <iostream>
#include "main.h"
#include "util.h"
#include "serialize.h"
#include "version.h"
#include "data/sighash.json.h"
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_utils.h"
#include "json/json_spirit_writer_template.h"
using namespace json_spirit;
extern Array read_json(const std::string& jsondata);
extern uint256 SignatureHash(const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
// Old script.cpp SignatureHash function
uint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
{
if (nIn >= txTo.vin.size())
{
printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
return 1;
}
CTransaction txTmp(txTo);
// In case concatenating two scripts ends up with two codeseparators,
// or an extra one at the end, this prevents all those possible incompatibilities.
scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
// Blank out other inputs' signatures
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
txTmp.vin[i].scriptSig = CScript();
txTmp.vin[nIn].scriptSig = scriptCode;
// Blank out some of the outputs
if ((nHashType & 0x1f) == SIGHASH_NONE)
{
// Wildcard payee
txTmp.vout.clear();
// Let the others update at will
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
if (i != nIn)
txTmp.vin[i].nSequence = 0;
}
else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
{
// Only lock-in the txout payee at same index as txin
unsigned int nOut = nIn;
if (nOut >= txTmp.vout.size())
{
printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
return 1;
}
txTmp.vout.resize(nOut+1);
for (unsigned int i = 0; i < nOut; i++)
txTmp.vout[i].SetNull();
// Let the others update at will
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
if (i != nIn)
txTmp.vin[i].nSequence = 0;
}
// Blank out other inputs completely, not recommended for open transactions
if (nHashType & SIGHASH_ANYONECANPAY)
{
txTmp.vin[0] = txTmp.vin[nIn];
txTmp.vin.resize(1);
}
// Serialize and hash
CHashWriter ss(SER_GETHASH, 0);
ss << txTmp << nHashType;
return ss.GetHash();
}
void static RandomScript(CScript &script) {
static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR};
script = CScript();
int ops = (insecure_rand() % 10);
for (int i=0; i<ops; i++)
script << oplist[insecure_rand() % (sizeof(oplist)/sizeof(oplist[0]))];
}
void static RandomTransaction(CTransaction &tx, bool fSingle) {
tx.nVersion = insecure_rand();
tx.vin.clear();
tx.vout.clear();
tx.nLockTime = (insecure_rand() % 2) ? insecure_rand() : 0;
int ins = (insecure_rand() % 4) + 1;
int outs = fSingle ? ins : (insecure_rand() % 4) + 1;
for (int in = 0; in < ins; in++) {
tx.vin.push_back(CTxIn());
CTxIn &txin = tx.vin.back();
txin.prevout.hash = GetRandHash();
txin.prevout.n = insecure_rand() % 4;
RandomScript(txin.scriptSig);
txin.nSequence = (insecure_rand() % 2) ? insecure_rand() : (unsigned int)-1;
}
for (int out = 0; out < outs; out++) {
tx.vout.push_back(CTxOut());
CTxOut &txout = tx.vout.back();
txout.nValue = insecure_rand() % 100000000;
RandomScript(txout.scriptPubKey);
}
}
BOOST_AUTO_TEST_SUITE(sighash_tests)
BOOST_AUTO_TEST_CASE(sighash_test)
{
seed_insecure_rand(false);
#if defined(PRINT_SIGHASH_JSON)
std::cout << "[\n";
std::cout << "\t[\"raw_transaction, script, input_index, hashType, signature_hash (result)\"],\n";
#endif
int nRandomTests = 50000;
#if defined(PRINT_SIGHASH_JSON)
nRandomTests = 500;
#endif
for (int i=0; i<nRandomTests; i++) {
int nHashType = insecure_rand();
CTransaction txTo;
RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE);
CScript scriptCode;
RandomScript(scriptCode);
int nIn = insecure_rand() % txTo.vin.size();
uint256 sh, sho;
sho = SignatureHashOld(scriptCode, txTo, nIn, nHashType);
sh = SignatureHash(scriptCode, txTo, nIn, nHashType);
#if defined(PRINT_SIGHASH_JSON)
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << txTo;
std::cout << "\t[\"" ;
std::cout << HexStr(ss.begin(), ss.end()) << "\", \"";
std::cout << HexStr(scriptCode) << "\", ";
std::cout << nIn << ", ";
std::cout << nHashType << ", \"";
std::cout << sho.GetHex() << "\"]";
if (i+1 != nRandomTests) {
std::cout << ",";
}
std::cout << "\n";
#endif
BOOST_CHECK(sh == sho);
}
#if defined(PRINT_SIGHASH_JSON)
std::cout << "]\n";
#endif
}
// Goal: check that SignatureHash generates correct hash
BOOST_AUTO_TEST_CASE(sighash_from_data)
{
Array tests = read_json(std::string(json_tests::sighash, json_tests::sighash + sizeof(json_tests::sighash)));
BOOST_FOREACH(Value& tv, tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 1) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
if (test.size() == 1) continue; // comment
std::string raw_tx, raw_script, sigHashHex;
int nIn, nHashType;
uint256 sh;
CTransaction tx;
CScript scriptCode = CScript();
try {
// deserialize test data
raw_tx = test[0].get_str();
raw_script = test[1].get_str();
nIn = test[2].get_int();
nHashType = test[3].get_int();
sigHashHex = test[4].get_str();
uint256 sh;
CDataStream stream(ParseHex(raw_tx), SER_NETWORK, PROTOCOL_VERSION);
stream >> tx;
CValidationState state;
BOOST_CHECK_MESSAGE(CheckTransaction(tx, state), strTest);
BOOST_CHECK(state.IsValid());
std::vector<unsigned char> raw = ParseHex(raw_script);
scriptCode.insert(scriptCode.end(), raw.begin(), raw.end());
} catch (...) {
BOOST_ERROR("Bad test, couldn't deserialize data: " << strTest);
continue;
}
sh = SignatureHash(scriptCode, tx, nIn, nHashType);
BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest);
}
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>int main(){
//Comments
return 0;
}<commit_msg>more comments<commit_after>int main(){
//Comments
//More Comments
return 0;
}<|endoftext|>
|
<commit_before>/**
* @file
*
* @brief
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#include "kdbconfig.h"
#include <external.hpp>
#include <kdb.h>
#include <kdb.hpp>
#include <iostream>
#include <string>
#include <vector>
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#ifndef _WIN32
#include <sys/types.h>
#include <sys/wait.h>
#endif
const char * buildinExecPath = BUILTIN_EXEC_FOLDER;
static std::string cwd ()
{
std::vector<char> current_dir;
current_dir.resize (KDB_MAX_PATH_LENGTH);
errno = 0;
while (getcwd (¤t_dir[0], current_dir.size ()) == nullptr && errno == ERANGE)
{
current_dir.resize (current_dir.size () * 2);
}
if (errno != 0)
{
return std::string ();
}
return std::string (¤t_dir[0]);
}
void tryExternalCommand (char ** argv)
{
std::vector<std::string> pathes;
std::string execPath = getenv ("KDB_EXEC_PATH");
size_t pos = 0;
std::string token;
std::string delimiter = ":";
while ((pos = execPath.find (delimiter)) != std::string::npos)
{
token = execPath.substr (0, pos);
pathes.push_back (token);
execPath.erase (0, pos + delimiter.length ());
}
pathes.push_back (execPath);
pathes.push_back (buildinExecPath);
for (auto & pathe : pathes)
{
std::string command;
char * savedArg = nullptr;
if (pathe[0] != '/')
{
// no absolute path, so work with current path
const std::string currentPath = cwd ();
if (currentPath.empty ())
{
std::cerr << "Could not determine "
<< "current path for " << pathe << " with command name: " << argv[0]
<< " because: " << strerror (errno) << std::endl;
continue;
}
command += currentPath;
command += "/";
}
command += pathe;
command += "/";
command += argv[0];
struct stat buf;
if (stat (command.c_str (), &buf) == -1)
{
if (errno == ENOENT)
{
// the file simply does not exist
// so it seems like it is an
// UnknownCommand
continue;
}
else
{
std::cerr << "The external command " << command << " could not be found, because: " << strerror (errno)
<< std::endl;
continue;
}
}
savedArg = argv[0];
argv[0] = const_cast<char *> (command.c_str ());
elektraExecve (command.c_str (), argv);
std::cerr << "Could not execute external command " << command << " because: " << strerror (errno) << std::endl;
argv[0] = savedArg;
}
throw UnknownCommand ();
}
#ifndef _WIN32
extern char ** environ;
#endif
void elektraExecve (const char * filename, char * const argv[])
{
#ifdef _WIN32
execve (filename, argv, 0);
#else
execve (filename, argv, environ);
#endif
}
void runManPage (std::string command, std::string profile)
{
if (command.empty ())
{
command = "kdb";
}
else
{
command = "kdb-" + command;
}
const char * man = "/usr/bin/man";
using namespace kdb;
Key k = nullptr;
if (profile != "nokdb")
{
try
{
KDB kdb;
KeySet conf;
std::string dirname;
for (int i = 0; i <= 2; ++i)
{
switch (i)
{
case 0:
dirname = "/sw/elektra/kdb/#0/" + profile + "/";
break;
case 1:
dirname = "/sw/elektra/kdb/#0/%/";
break;
case 2:
dirname = "/sw/kdb/" + profile + "/";
break; // legacy
}
kdb.get (conf, dirname);
if (!k) // first one wins, because we do not reassign
{
k = conf.lookup (dirname + "man");
}
}
}
catch (kdb::KDBException const & ce)
{
std::cerr << "There is a severe problem with your installation!\n"
<< "kdbOpen() failed with the info:" << std::endl
<< ce.what () << std::endl;
}
}
if (k)
{
man = k.get<std::string> ().c_str ();
}
char * const argv[3] = { const_cast<char *> (man), const_cast<char *> (command.c_str ()), nullptr };
elektraExecve (man, argv);
std::cout << "Sorry, I was not able to execute the man-page viewer: \"" << man << "\".\n";
std::cout << "Try to change /sw/elektra/kdb/#0/" + profile + "/man with full path to man.\n\n";
std::cout << "If you did not modify settings related to the man-page viewer,\nplease report the issue at "
"https://issues.libelektra.org/"
<< std::endl;
exit (1);
}
#ifndef _WIN32
bool runEditor (std::string editor, std::string file)
{
char * const argv[3] = { const_cast<char *> (editor.c_str ()), const_cast<char *> (file.c_str ()), 0 };
pid_t childpid = fork ();
if (!childpid)
{
elektraExecve (editor.c_str (), argv);
exit (23);
}
else
{
int status;
waitpid (childpid, &status, 0);
if (WIFEXITED (status))
{
if (WEXITSTATUS (status) != 23)
{
return true;
}
}
}
return false;
}
#else
bool runEditor (std::string, std::string)
{
// TODO: impl
return false;
}
#endif
<commit_msg>KDB_EXEC_PATH: Fix pointer after getenv<commit_after>/**
* @file
*
* @brief
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#include "kdbconfig.h"
#include <external.hpp>
#include <kdb.h>
#include <kdb.hpp>
#include <iostream>
#include <string>
#include <vector>
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#ifndef _WIN32
#include <sys/types.h>
#include <sys/wait.h>
#endif
const char * buildinExecPath = BUILTIN_EXEC_FOLDER;
static std::string cwd ()
{
std::vector<char> current_dir;
current_dir.resize (KDB_MAX_PATH_LENGTH);
errno = 0;
while (getcwd (¤t_dir[0], current_dir.size ()) == nullptr && errno == ERANGE)
{
current_dir.resize (current_dir.size () * 2);
}
if (errno != 0)
{
return std::string ();
}
return std::string (¤t_dir[0]);
}
void tryExternalCommand (char ** argv)
{
std::vector<std::string> pathes;
char * execPathPtr = getenv ("KDB_EXEC_PATH");
if (execPathPtr)
{
// The string pointed by the pointer returned by getenv shall
// not be modified. The constructor of std::string constructs a
// copy of the string.
std::string execPath (execPathPtr);
size_t pos = 0;
std::string token;
std::string delimiter = ":";
while ((pos = execPath.find (delimiter)) != std::string::npos)
{
token = execPath.substr (0, pos);
pathes.push_back (token);
execPath.erase (0, pos + delimiter.length ());
}
// There is one last path in execPath after the while
pathes.push_back (execPath);
}
pathes.push_back (buildinExecPath);
for (auto & pathe : pathes)
{
std::string command;
char * savedArg = nullptr;
if (pathe[0] != '/')
{
// no absolute path, so work with current path
const std::string currentPath = cwd ();
if (currentPath.empty ())
{
std::cerr << "Could not determine "
<< "current path for " << pathe << " with command name: " << argv[0]
<< " because: " << strerror (errno) << std::endl;
continue;
}
command += currentPath;
command += "/";
}
command += pathe;
command += "/";
command += argv[0];
struct stat buf;
if (stat (command.c_str (), &buf) == -1)
{
if (errno == ENOENT)
{
// the file simply does not exist
// so it seems like it is an
// UnknownCommand
continue;
}
else
{
std::cerr << "The external command " << command << " could not be found, because: " << strerror (errno)
<< std::endl;
continue;
}
}
savedArg = argv[0];
argv[0] = const_cast<char *> (command.c_str ());
elektraExecve (command.c_str (), argv);
std::cerr << "Could not execute external command " << command << " because: " << strerror (errno) << std::endl;
argv[0] = savedArg;
}
throw UnknownCommand ();
}
#ifndef _WIN32
extern char ** environ;
#endif
void elektraExecve (const char * filename, char * const argv[])
{
#ifdef _WIN32
execve (filename, argv, 0);
#else
execve (filename, argv, environ);
#endif
}
void runManPage (std::string command, std::string profile)
{
if (command.empty ())
{
command = "kdb";
}
else
{
command = "kdb-" + command;
}
const char * man = "/usr/bin/man";
using namespace kdb;
Key k = nullptr;
if (profile != "nokdb")
{
try
{
KDB kdb;
KeySet conf;
std::string dirname;
for (int i = 0; i <= 2; ++i)
{
switch (i)
{
case 0:
dirname = "/sw/elektra/kdb/#0/" + profile + "/";
break;
case 1:
dirname = "/sw/elektra/kdb/#0/%/";
break;
case 2:
dirname = "/sw/kdb/" + profile + "/";
break; // legacy
}
kdb.get (conf, dirname);
if (!k) // first one wins, because we do not reassign
{
k = conf.lookup (dirname + "man");
}
}
}
catch (kdb::KDBException const & ce)
{
std::cerr << "There is a severe problem with your installation!\n"
<< "kdbOpen() failed with the info:" << std::endl
<< ce.what () << std::endl;
}
}
if (k)
{
man = k.get<std::string> ().c_str ();
}
char * const argv[3] = { const_cast<char *> (man), const_cast<char *> (command.c_str ()), nullptr };
elektraExecve (man, argv);
std::cout << "Sorry, I was not able to execute the man-page viewer: \"" << man << "\".\n";
std::cout << "Try to change /sw/elektra/kdb/#0/" + profile + "/man with full path to man.\n\n";
std::cout << "If you did not modify settings related to the man-page viewer,\nplease report the issue at "
"https://issues.libelektra.org/"
<< std::endl;
exit (1);
}
#ifndef _WIN32
bool runEditor (std::string editor, std::string file)
{
char * const argv[3] = { const_cast<char *> (editor.c_str ()), const_cast<char *> (file.c_str ()), 0 };
pid_t childpid = fork ();
if (!childpid)
{
elektraExecve (editor.c_str (), argv);
exit (23);
}
else
{
int status;
waitpid (childpid, &status, 0);
if (WIFEXITED (status))
{
if (WEXITSTATUS (status) != 23)
{
return true;
}
}
}
return false;
}
#else
bool runEditor (std::string, std::string)
{
// TODO: impl
return false;
}
#endif
<|endoftext|>
|
<commit_before>/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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 <openssl/crypto.h>
#include "tscore/I_Layout.h"
#include "tscore/BufferWriter.h"
#include "records/I_RecProcess.h"
#include "RecordsConfig.h"
#include "info.h"
#if HAVE_ZLIB_H
#include <zlib.h>
#endif
#if HAVE_LZMA_H
#include <lzma.h>
#endif
#if HAVE_BROTLI_ENCODE_H
#include <brotli/encode.h>
#endif
// Produce output about compile time features, useful for checking how things were built, as well
// as for our TSQA test harness.
static void
print_feature(std::string_view name, int value, bool json, bool last = false)
{
if (json) {
printf(" \"%.*s\": %d%s", static_cast<int>(name.size()), name.data(), value, last ? "\n" : ",\n");
} else {
printf("#define %.*s %d\n", static_cast<int>(name.size()), name.data(), value);
}
}
static void
print_feature(std::string_view name, std::string_view value, bool json, bool last = false)
{
if (json) {
printf(R"( "%.*s": "%.*s"%s)", static_cast<int>(name.size()), name.data(), static_cast<int>(value.size()), value.data(),
last ? "\n" : ",\n");
} else {
printf("#define %.*s \"%.*s\"\n", static_cast<int>(name.size()), name.data(), static_cast<int>(value.size()), value.data());
}
}
void
produce_features(bool json)
{
if (json) {
printf("{\n");
}
print_feature("BUILD_MACHINE", BUILD_MACHINE, json);
print_feature("BUILD_PERSON", BUILD_PERSON, json);
print_feature("BUILD_GROUP", BUILD_GROUP, json);
print_feature("BUILD_NUMBER", BUILD_NUMBER, json);
#if HAVE_ZLIB_H
print_feature("TS_HAS_LIBZ", 1, json);
#else
print_feature("TS_HAS_LIBZ", 0, json);
#endif
#if HAVE_LZMA_H
print_feature("TS_HAS_LZMA", 1, json);
#else
print_feature("TS_HAS_LZMA", 0, json);
#endif
#if HAVE_BROTLI_ENCODE_H
print_feature("TS_HAS_BROTLI", 1, json);
#else
print_feature("TS_HAS_BROTLI", 0, json);
#endif
print_feature("TS_HAS_JEMALLOC", TS_HAS_JEMALLOC, json);
print_feature("TS_HAS_TCMALLOC", TS_HAS_TCMALLOC, json);
print_feature("TS_HAS_IN6_IS_ADDR_UNSPECIFIED", TS_HAS_IN6_IS_ADDR_UNSPECIFIED, json);
print_feature("TS_HAS_BACKTRACE", TS_HAS_BACKTRACE, json);
print_feature("TS_HAS_PROFILER", TS_HAS_PROFILER, json);
print_feature("TS_USE_FAST_SDK", TS_USE_FAST_SDK, json);
print_feature("TS_USE_DIAGS", TS_USE_DIAGS, json);
print_feature("TS_USE_EPOLL", TS_USE_EPOLL, json);
print_feature("TS_USE_KQUEUE", TS_USE_KQUEUE, json);
print_feature("TS_USE_PORT", TS_USE_PORT, json);
print_feature("TS_USE_POSIX_CAP", TS_USE_POSIX_CAP, json);
print_feature("TS_USE_TPROXY", TS_USE_TPROXY, json);
print_feature("TS_HAS_SO_MARK", TS_HAS_SO_MARK, json);
print_feature("TS_HAS_IP_TOS", TS_HAS_IP_TOS, json);
print_feature("TS_USE_HWLOC", TS_USE_HWLOC, json);
print_feature("TS_USE_SET_RBIO", TS_USE_SET_RBIO, json);
print_feature("TS_USE_TLS13", TS_USE_TLS13, json);
print_feature("TS_USE_LINUX_NATIVE_AIO", TS_USE_LINUX_NATIVE_AIO, json);
print_feature("TS_HAS_SO_PEERCRED", TS_HAS_SO_PEERCRED, json);
print_feature("TS_USE_REMOTE_UNWINDING", TS_USE_REMOTE_UNWINDING, json);
print_feature("TS_USE_TLS_OCSP", TS_USE_TLS_OCSP, json);
print_feature("SIZEOF_VOIDP", SIZEOF_VOIDP, json);
print_feature("TS_IP_TRANSPARENT", TS_IP_TRANSPARENT, json);
print_feature("TS_HAS_128BIT_CAS", TS_HAS_128BIT_CAS, json);
print_feature("TS_HAS_TESTS", TS_HAS_TESTS, json);
print_feature("TS_HAS_WCCP", TS_HAS_WCCP, json);
print_feature("TS_MAX_THREADS_IN_EACH_THREAD_TYPE", TS_MAX_THREADS_IN_EACH_THREAD_TYPE, json);
print_feature("TS_MAX_NUMBER_EVENT_THREADS", TS_MAX_NUMBER_EVENT_THREADS, json);
print_feature("TS_MAX_HOST_NAME_LEN", TS_MAX_HOST_NAME_LEN, json);
print_feature("SPLIT_DNS", SPLIT_DNS, json);
print_feature("TS_PKGSYSUSER", TS_PKGSYSUSER, json);
print_feature("TS_PKGSYSGROUP", TS_PKGSYSGROUP, json, true);
if (json) {
printf("}\n");
}
}
void
print_var(std::string_view const &name, std::string_view const &value, bool json, bool last = false)
{
if (json) {
printf(R"( "%.*s": "%.*s"%s)", static_cast<int>(name.size()), name.data(), static_cast<int>(value.size()), value.data(),
last ? "\n" : ",\n");
} else {
printf("%.*s: %.*s\n", static_cast<int>(name.size()), name.data(), static_cast<int>(value.size()), value.data());
}
}
void
produce_layout(bool json)
{
RecProcessInit(RECM_STAND_ALONE, nullptr /* diags */);
LibRecordsConfigInit();
if (json) {
printf("{\n");
}
print_var("PREFIX", Layout::get()->prefix, json);
print_var("BINDIR", RecConfigReadBinDir(), json);
print_var("SYSCONFDIR", RecConfigReadConfigDir(), json);
print_var("LIBDIR", Layout::get()->libdir, json);
print_var("LOGDIR", RecConfigReadLogDir(), json);
print_var("RUNTIMEDIR", RecConfigReadRuntimeDir(), json);
print_var("PLUGINDIR", RecConfigReadPluginDir(), json);
print_var("INCLUDEDIR", Layout::get()->includedir, json);
print_var("records.config", RecConfigReadConfigPath(nullptr, REC_CONFIG_FILE), json);
print_var("remap.config", RecConfigReadConfigPath("proxy.config.url_remap.filename"), json);
print_var("plugin.config", RecConfigReadConfigPath(nullptr, "plugin.config"), json);
print_var("ssl_multicert.config", RecConfigReadConfigPath("proxy.config.ssl.server.multicert.filename"), json);
print_var("storage.config", RecConfigReadConfigPath("proxy.config.cache.storage_filename"), json);
print_var("hosting.config", RecConfigReadConfigPath("proxy.config.cache.hosting_filename"), json);
print_var("volume.config", RecConfigReadConfigPath("proxy.config.cache.volume_filename"), json);
print_var("ip_allow.config", RecConfigReadConfigPath("proxy.config.cache.ip_allow.filename"), json, true);
if (json) {
printf("}\n");
}
}
void
produce_versions(bool json)
{
using LBW = ts::LocalBufferWriter<128>;
static const std::string_view undef{"undef"};
if (json) {
printf("{\n");
}
print_var("openssl", LBW().print("{:#x}", OPENSSL_VERSION_NUMBER).view(), json);
print_var("openssl_str", LBW().print(OPENSSL_VERSION_TEXT).view(), json);
print_var("pcre", LBW().print("{}.{}", PCRE_MAJOR, PCRE_MINOR).view(), json);
// These are optional, for now at least.
#if TS_USE_HWLOC
print_var("hwloc", LBW().print("{:#x}", HWLOC_API_VERSION).view(), json);
print_var("hwloc.run", LBW().print("{:#x}", hwloc_get_api_version()).view(), json);
#else
print_var("hwloc", undef, json);
#endif
#if HAVE_ZLIB_H
print_var("libz", LBW().print("{}", ZLIB_VERSION).view(), json);
#else
print_var("libz", undef, json);
#endif
#if HAVE_LZMA_H
print_var("lzma", LBW().print("{}", LZMA_VERSION_STRING).view(), json);
print_var("lzma.run", LBW().print("{}", lzma_version_string()).view(), json);
#else
print_var("lzma", undef, json);
#endif
#if HAVE_BROTLI_ENCODE_H
print_var("brotli", LBW().print("{:#x}", BrotliEncoderVersion()).view(), json);
#else
print_var("brotli", undef, json);
#endif
// This should always be last
print_var("traffic-server", LBW().print(TS_VERSION_STRING).view(), json, true);
if (json) {
printf("}\n");
}
}
<commit_msg>Avoid a clang warning when all the defines are set<commit_after>/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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 <openssl/crypto.h>
#include "tscore/I_Layout.h"
#include "tscore/BufferWriter.h"
#include "records/I_RecProcess.h"
#include "RecordsConfig.h"
#include "info.h"
#if HAVE_ZLIB_H
#include <zlib.h>
#endif
#if HAVE_LZMA_H
#include <lzma.h>
#endif
#if HAVE_BROTLI_ENCODE_H
#include <brotli/encode.h>
#endif
// Produce output about compile time features, useful for checking how things were built, as well
// as for our TSQA test harness.
static void
print_feature(std::string_view name, int value, bool json, bool last = false)
{
if (json) {
printf(" \"%.*s\": %d%s", static_cast<int>(name.size()), name.data(), value, last ? "\n" : ",\n");
} else {
printf("#define %.*s %d\n", static_cast<int>(name.size()), name.data(), value);
}
}
static void
print_feature(std::string_view name, std::string_view value, bool json, bool last = false)
{
if (json) {
printf(R"( "%.*s": "%.*s"%s)", static_cast<int>(name.size()), name.data(), static_cast<int>(value.size()), value.data(),
last ? "\n" : ",\n");
} else {
printf("#define %.*s \"%.*s\"\n", static_cast<int>(name.size()), name.data(), static_cast<int>(value.size()), value.data());
}
}
void
produce_features(bool json)
{
if (json) {
printf("{\n");
}
print_feature("BUILD_MACHINE", BUILD_MACHINE, json);
print_feature("BUILD_PERSON", BUILD_PERSON, json);
print_feature("BUILD_GROUP", BUILD_GROUP, json);
print_feature("BUILD_NUMBER", BUILD_NUMBER, json);
#if HAVE_ZLIB_H
print_feature("TS_HAS_LIBZ", 1, json);
#else
print_feature("TS_HAS_LIBZ", 0, json);
#endif
#if HAVE_LZMA_H
print_feature("TS_HAS_LZMA", 1, json);
#else
print_feature("TS_HAS_LZMA", 0, json);
#endif
#if HAVE_BROTLI_ENCODE_H
print_feature("TS_HAS_BROTLI", 1, json);
#else
print_feature("TS_HAS_BROTLI", 0, json);
#endif
print_feature("TS_HAS_JEMALLOC", TS_HAS_JEMALLOC, json);
print_feature("TS_HAS_TCMALLOC", TS_HAS_TCMALLOC, json);
print_feature("TS_HAS_IN6_IS_ADDR_UNSPECIFIED", TS_HAS_IN6_IS_ADDR_UNSPECIFIED, json);
print_feature("TS_HAS_BACKTRACE", TS_HAS_BACKTRACE, json);
print_feature("TS_HAS_PROFILER", TS_HAS_PROFILER, json);
print_feature("TS_USE_FAST_SDK", TS_USE_FAST_SDK, json);
print_feature("TS_USE_DIAGS", TS_USE_DIAGS, json);
print_feature("TS_USE_EPOLL", TS_USE_EPOLL, json);
print_feature("TS_USE_KQUEUE", TS_USE_KQUEUE, json);
print_feature("TS_USE_PORT", TS_USE_PORT, json);
print_feature("TS_USE_POSIX_CAP", TS_USE_POSIX_CAP, json);
print_feature("TS_USE_TPROXY", TS_USE_TPROXY, json);
print_feature("TS_HAS_SO_MARK", TS_HAS_SO_MARK, json);
print_feature("TS_HAS_IP_TOS", TS_HAS_IP_TOS, json);
print_feature("TS_USE_HWLOC", TS_USE_HWLOC, json);
print_feature("TS_USE_SET_RBIO", TS_USE_SET_RBIO, json);
print_feature("TS_USE_TLS13", TS_USE_TLS13, json);
print_feature("TS_USE_LINUX_NATIVE_AIO", TS_USE_LINUX_NATIVE_AIO, json);
print_feature("TS_HAS_SO_PEERCRED", TS_HAS_SO_PEERCRED, json);
print_feature("TS_USE_REMOTE_UNWINDING", TS_USE_REMOTE_UNWINDING, json);
print_feature("TS_USE_TLS_OCSP", TS_USE_TLS_OCSP, json);
print_feature("SIZEOF_VOIDP", SIZEOF_VOIDP, json);
print_feature("TS_IP_TRANSPARENT", TS_IP_TRANSPARENT, json);
print_feature("TS_HAS_128BIT_CAS", TS_HAS_128BIT_CAS, json);
print_feature("TS_HAS_TESTS", TS_HAS_TESTS, json);
print_feature("TS_HAS_WCCP", TS_HAS_WCCP, json);
print_feature("TS_MAX_THREADS_IN_EACH_THREAD_TYPE", TS_MAX_THREADS_IN_EACH_THREAD_TYPE, json);
print_feature("TS_MAX_NUMBER_EVENT_THREADS", TS_MAX_NUMBER_EVENT_THREADS, json);
print_feature("TS_MAX_HOST_NAME_LEN", TS_MAX_HOST_NAME_LEN, json);
print_feature("SPLIT_DNS", SPLIT_DNS, json);
print_feature("TS_PKGSYSUSER", TS_PKGSYSUSER, json);
print_feature("TS_PKGSYSGROUP", TS_PKGSYSGROUP, json, true);
if (json) {
printf("}\n");
}
}
void
print_var(std::string_view const &name, std::string_view const &value, bool json, bool last = false)
{
if (json) {
printf(R"( "%.*s": "%.*s"%s)", static_cast<int>(name.size()), name.data(), static_cast<int>(value.size()), value.data(),
last ? "\n" : ",\n");
} else {
printf("%.*s: %.*s\n", static_cast<int>(name.size()), name.data(), static_cast<int>(value.size()), value.data());
}
}
void
produce_layout(bool json)
{
RecProcessInit(RECM_STAND_ALONE, nullptr /* diags */);
LibRecordsConfigInit();
if (json) {
printf("{\n");
}
print_var("PREFIX", Layout::get()->prefix, json);
print_var("BINDIR", RecConfigReadBinDir(), json);
print_var("SYSCONFDIR", RecConfigReadConfigDir(), json);
print_var("LIBDIR", Layout::get()->libdir, json);
print_var("LOGDIR", RecConfigReadLogDir(), json);
print_var("RUNTIMEDIR", RecConfigReadRuntimeDir(), json);
print_var("PLUGINDIR", RecConfigReadPluginDir(), json);
print_var("INCLUDEDIR", Layout::get()->includedir, json);
print_var("records.config", RecConfigReadConfigPath(nullptr, REC_CONFIG_FILE), json);
print_var("remap.config", RecConfigReadConfigPath("proxy.config.url_remap.filename"), json);
print_var("plugin.config", RecConfigReadConfigPath(nullptr, "plugin.config"), json);
print_var("ssl_multicert.config", RecConfigReadConfigPath("proxy.config.ssl.server.multicert.filename"), json);
print_var("storage.config", RecConfigReadConfigPath("proxy.config.cache.storage_filename"), json);
print_var("hosting.config", RecConfigReadConfigPath("proxy.config.cache.hosting_filename"), json);
print_var("volume.config", RecConfigReadConfigPath("proxy.config.cache.volume_filename"), json);
print_var("ip_allow.config", RecConfigReadConfigPath("proxy.config.cache.ip_allow.filename"), json, true);
if (json) {
printf("}\n");
}
}
void
produce_versions(bool json)
{
using LBW = ts::LocalBufferWriter<128>;
[[maybe_unused]] static const std::string_view undef{"undef"};
if (json) {
printf("{\n");
}
print_var("openssl", LBW().print("{:#x}", OPENSSL_VERSION_NUMBER).view(), json);
print_var("openssl_str", LBW().print(OPENSSL_VERSION_TEXT).view(), json);
print_var("pcre", LBW().print("{}.{}", PCRE_MAJOR, PCRE_MINOR).view(), json);
// These are optional, for now at least.
#if TS_USE_HWLOC
print_var("hwloc", LBW().print("{:#x}", HWLOC_API_VERSION).view(), json);
print_var("hwloc.run", LBW().print("{:#x}", hwloc_get_api_version()).view(), json);
#else
print_var("hwloc", undef, json);
#endif
#if HAVE_ZLIB_H
print_var("libz", LBW().print("{}", ZLIB_VERSION).view(), json);
#else
print_var("libz", undef, json);
#endif
#if HAVE_LZMA_H
print_var("lzma", LBW().print("{}", LZMA_VERSION_STRING).view(), json);
print_var("lzma.run", LBW().print("{}", lzma_version_string()).view(), json);
#else
print_var("lzma", undef, json);
#endif
#if HAVE_BROTLI_ENCODE_H
print_var("brotli", LBW().print("{:#x}", BrotliEncoderVersion()).view(), json);
#else
print_var("brotli", undef, json);
#endif
// This should always be last
print_var("traffic-server", LBW().print(TS_VERSION_STRING).view(), json, true);
if (json) {
printf("}\n");
}
}
<|endoftext|>
|
<commit_before>/*
* The translation response struct.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "translate_response.hxx"
#include "pool.h"
#include "strref-pool.h"
#include "strmap.h"
#include "widget-view.h"
#include <string.h>
void
TranslateResponse::Clear()
{
memset(this, 0, sizeof(*this));
}
template<typename T>
static ConstBuffer<T>
Copy(pool *p, ConstBuffer<T> src)
{
if (src.IsEmpty())
return ConstBuffer<T>::Null();
ConstBuffer<void> src_v = src.ToVoid();
ConstBuffer<void> dest_v(p_memdup(p, src_v.data, src_v.size), src_v.size);
return ConstBuffer<T>::FromVoid(dest_v);
}
void
translate_response_copy(struct pool *pool, TranslateResponse *dest,
const TranslateResponse *src)
{
/* we don't copy the "max_age" attribute, because it's only used
by the tcache itself */
dest->status = src->status;
dest->request_header_forward = src->request_header_forward;
dest->response_header_forward = src->response_header_forward;
dest->base = p_strdup_checked(pool, src->base);
dest->regex = p_strdup_checked(pool, src->regex);
dest->inverse_regex = p_strdup_checked(pool, src->inverse_regex);
dest->site = p_strdup_checked(pool, src->site);
dest->document_root = p_strdup_checked(pool, src->document_root);
dest->redirect = p_strdup_checked(pool, src->redirect);
dest->bounce = p_strdup_checked(pool, src->bounce);
dest->scheme = p_strdup_checked(pool, src->scheme);
dest->host = p_strdup_checked(pool, src->host);
dest->uri = p_strdup_checked(pool, src->uri);
dest->local_uri = p_strdup_checked(pool, src->local_uri);
dest->untrusted = p_strdup_checked(pool, src->untrusted);
dest->untrusted_prefix = p_strdup_checked(pool, src->untrusted_prefix);
dest->untrusted_site_suffix =
p_strdup_checked(pool, src->untrusted_site_suffix);
dest->direct_addressing = src->direct_addressing;
dest->stateful = src->stateful;
dest->discard_session = src->discard_session;
dest->secure_cookie = src->secure_cookie;
dest->filter_4xx = src->filter_4xx;
dest->error_document = src->error_document;
dest->previous = src->previous;
dest->transparent = src->transparent;
dest->auto_base = src->auto_base;
dest->widget_info = src->widget_info;
dest->widget_group = p_strdup_checked(pool, src->widget_group);
strset_init(&dest->container_groups);
strset_copy(pool, &dest->container_groups, &src->container_groups);
dest->anchor_absolute = src->anchor_absolute;
dest->dump_headers = src->dump_headers;
dest->session = nullptr;
if (strref_is_null(&src->check))
strref_null(&dest->check);
else
strref_set_dup(pool, &dest->check, &src->check);
if (strref_is_null(&src->want_full_uri))
strref_null(&dest->want_full_uri);
else
strref_set_dup(pool, &dest->want_full_uri, &src->want_full_uri);
/* The "user" attribute must not be present in cached responses,
because they belong to only that one session. For the same
reason, we won't copy the user_max_age attribute. */
dest->user = nullptr;
dest->language = nullptr;
dest->realm = p_strdup_checked(pool, src->realm);
dest->www_authenticate = p_strdup_checked(pool, src->www_authenticate);
dest->authentication_info = p_strdup_checked(pool,
src->authentication_info);
dest->cookie_domain = p_strdup_checked(pool, src->cookie_domain);
dest->cookie_host = p_strdup_checked(pool, src->cookie_host);
dest->headers = src->headers != nullptr
? strmap_dup(pool, src->headers, 17)
: nullptr;
dest->views = src->views != nullptr
? widget_view_dup_chain(pool, src->views)
: nullptr;
dest->vary = Copy(pool, src->vary);
dest->invalidate = Copy(pool, src->invalidate);
dest->validate_mtime.mtime = src->validate_mtime.mtime;
dest->validate_mtime.path =
p_strdup_checked(pool, src->validate_mtime.path);
}
bool
translate_response_is_expandable(const TranslateResponse *response)
{
return response->regex != nullptr &&
(resource_address_is_expandable(&response->address) ||
widget_view_any_is_expandable(response->views));
}
bool
translate_response_expand(struct pool *pool,
TranslateResponse *response,
const GMatchInfo *match_info, GError **error_r)
{
assert(pool != nullptr);
assert(response != nullptr);
assert(response->regex != nullptr);
assert(match_info != nullptr);
return resource_address_expand(pool, &response->address,
match_info, error_r) &&
widget_view_expand_all(pool, response->views, match_info, error_r);
}
<commit_msg>translate_response: copy protocol_version in _copy()<commit_after>/*
* The translation response struct.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "translate_response.hxx"
#include "pool.h"
#include "strref-pool.h"
#include "strmap.h"
#include "widget-view.h"
#include <string.h>
void
TranslateResponse::Clear()
{
memset(this, 0, sizeof(*this));
}
template<typename T>
static ConstBuffer<T>
Copy(pool *p, ConstBuffer<T> src)
{
if (src.IsEmpty())
return ConstBuffer<T>::Null();
ConstBuffer<void> src_v = src.ToVoid();
ConstBuffer<void> dest_v(p_memdup(p, src_v.data, src_v.size), src_v.size);
return ConstBuffer<T>::FromVoid(dest_v);
}
void
translate_response_copy(struct pool *pool, TranslateResponse *dest,
const TranslateResponse *src)
{
dest->protocol_version = src->protocol_version;
/* we don't copy the "max_age" attribute, because it's only used
by the tcache itself */
dest->status = src->status;
dest->request_header_forward = src->request_header_forward;
dest->response_header_forward = src->response_header_forward;
dest->base = p_strdup_checked(pool, src->base);
dest->regex = p_strdup_checked(pool, src->regex);
dest->inverse_regex = p_strdup_checked(pool, src->inverse_regex);
dest->site = p_strdup_checked(pool, src->site);
dest->document_root = p_strdup_checked(pool, src->document_root);
dest->redirect = p_strdup_checked(pool, src->redirect);
dest->bounce = p_strdup_checked(pool, src->bounce);
dest->scheme = p_strdup_checked(pool, src->scheme);
dest->host = p_strdup_checked(pool, src->host);
dest->uri = p_strdup_checked(pool, src->uri);
dest->local_uri = p_strdup_checked(pool, src->local_uri);
dest->untrusted = p_strdup_checked(pool, src->untrusted);
dest->untrusted_prefix = p_strdup_checked(pool, src->untrusted_prefix);
dest->untrusted_site_suffix =
p_strdup_checked(pool, src->untrusted_site_suffix);
dest->direct_addressing = src->direct_addressing;
dest->stateful = src->stateful;
dest->discard_session = src->discard_session;
dest->secure_cookie = src->secure_cookie;
dest->filter_4xx = src->filter_4xx;
dest->error_document = src->error_document;
dest->previous = src->previous;
dest->transparent = src->transparent;
dest->auto_base = src->auto_base;
dest->widget_info = src->widget_info;
dest->widget_group = p_strdup_checked(pool, src->widget_group);
strset_init(&dest->container_groups);
strset_copy(pool, &dest->container_groups, &src->container_groups);
dest->anchor_absolute = src->anchor_absolute;
dest->dump_headers = src->dump_headers;
dest->session = nullptr;
if (strref_is_null(&src->check))
strref_null(&dest->check);
else
strref_set_dup(pool, &dest->check, &src->check);
if (strref_is_null(&src->want_full_uri))
strref_null(&dest->want_full_uri);
else
strref_set_dup(pool, &dest->want_full_uri, &src->want_full_uri);
/* The "user" attribute must not be present in cached responses,
because they belong to only that one session. For the same
reason, we won't copy the user_max_age attribute. */
dest->user = nullptr;
dest->language = nullptr;
dest->realm = p_strdup_checked(pool, src->realm);
dest->www_authenticate = p_strdup_checked(pool, src->www_authenticate);
dest->authentication_info = p_strdup_checked(pool,
src->authentication_info);
dest->cookie_domain = p_strdup_checked(pool, src->cookie_domain);
dest->cookie_host = p_strdup_checked(pool, src->cookie_host);
dest->headers = src->headers != nullptr
? strmap_dup(pool, src->headers, 17)
: nullptr;
dest->views = src->views != nullptr
? widget_view_dup_chain(pool, src->views)
: nullptr;
dest->vary = Copy(pool, src->vary);
dest->invalidate = Copy(pool, src->invalidate);
dest->validate_mtime.mtime = src->validate_mtime.mtime;
dest->validate_mtime.path =
p_strdup_checked(pool, src->validate_mtime.path);
}
bool
translate_response_is_expandable(const TranslateResponse *response)
{
return response->regex != nullptr &&
(resource_address_is_expandable(&response->address) ||
widget_view_any_is_expandable(response->views));
}
bool
translate_response_expand(struct pool *pool,
TranslateResponse *response,
const GMatchInfo *match_info, GError **error_r)
{
assert(pool != nullptr);
assert(response != nullptr);
assert(response->regex != nullptr);
assert(match_info != nullptr);
return resource_address_expand(pool, &response->address,
match_info, error_r) &&
widget_view_expand_all(pool, response->views, match_info, error_r);
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Initial Developer of the Original Code is
* Novell Inc.
* Portions created by the Initial Developer are Copyright (C) 2010 the
* Initial Developer. All Rights Reserved.
*
* Contributor(s): Florian Reuter <freuter@novell.com>
* Cedric Bosdonnat <cbosdonnat@novell.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include "frame.hxx"
#include "frmfmt.hxx"
#include "sectfrm.hxx"
#include "tabfrm.hxx"
#include "txtfrm.hxx"
#include "porlin.hxx"
#include "porlay.hxx"
#include "portxt.hxx"
#include "sortedobjs.hxx"
#include <anchoredobject.hxx>
#include <libxml/xmlwriter.h>
#include <SwPortionHandler.hxx>
class XmlPortionDumper:public SwPortionHandler
{
private:
xmlTextWriterPtr writer;
sal_uInt16 ofs;
const char* getTypeName( sal_uInt16 nType )
{
switch ( nType )
{
case POR_LIN: return "POR_LIN";
case POR_FLYCNT: return "POR_FLYCNT";
case POR_HOLE: return "POR_HOLE";
case POR_TMPEND: return "POR_TMPEND";
case POR_BRK: return "POR_BRK";
case POR_KERN: return "POR_KERN";
case POR_ARROW: return "POR_ARROW";
case POR_MULTI: return "POR_MULTI";
case POR_HIDDEN_TXT: return "POR_HIDDEN_TXT";
case POR_CONTROLCHAR: return "POR_CONTROLCHAR";
case POR_TXT: return "POR_TXT";
case POR_LAY: return "POR_LAY";
case POR_PARA: return "POR_PARA";
case POR_URL: return "POR_URL";
case POR_HNG: return "POR_HNG";
case POR_DROP: return "POR_DROP";
case POR_TOX: return "POR_TOX";
case POR_ISOTOX: return "POR_ISOTOX";
case POR_REF: return "POR_REF";
case POR_ISOREF: return "POR_ISOREF";
case POR_META: return "POR_META";
case POR_EXP: return "POR_EXP";
case POR_BLANK: return "POR_BLANK";
case POR_POSTITS: return "POR_POSTITS";
case POR_HYPH: return "POR_HYPH";
case POR_HYPHSTR: return "POR_HYPHSTR";
case POR_SOFTHYPH: return "POR_SOFTHYPH";
case POR_SOFTHYPHSTR: return "POR_SOFTHYPHSTR";
case POR_SOFTHYPH_COMP: return "POR_SOFTHYPH_COMP";
case POR_FLD: return "POR_FLD";
case POR_HIDDEN: return "POR_HIDDEN";
case POR_QUOVADIS: return "POR_QUOVADIS";
case POR_ERGOSUM: return "POR_ERGOSUM";
case POR_COMBINED: return "POR_COMBINED";
case POR_FTN: return "POR_FTN";
case POR_FTNNUM: return "POR_FTNNUM";
case POR_NUMBER: return "POR_NUMBER";
case POR_BULLET: return "POR_BULLET";
case POR_GRFNUM: return "POR_GRFNUM";
case POR_GLUE: return "POR_GLUE";
case POR_MARGIN: return "POR_MARGIN";
case POR_FIX: return "POR_FIX";
case POR_FLY: return "POR_FLY";
case POR_TAB: return "POR_TAB";
case POR_TABRIGHT: return "POR_TABRIGHT";
case POR_TABCENTER: return "POR_TABCENTER";
case POR_TABDECIMAL: return "POR_TABDECIMAL";
case POR_TABLEFT: return "POR_TABLEFT";
default:
return "Unknown";
}
}
public:
XmlPortionDumper( xmlTextWriterPtr some_writer ):writer( some_writer ), ofs( 0 )
{
}
virtual ~ XmlPortionDumper( )
{
}
/**
@param nLength
length of this portion in the model string
@param rText
text which is painted on-screen
*/
virtual void Text( sal_uInt16 nLength,
sal_uInt16 nType )
{
ofs += nLength;
xmlTextWriterStartElement( writer, BAD_CAST( "Text" ) );
xmlTextWriterWriteFormatAttribute( writer,
BAD_CAST( "nLength" ),
"%i", ( int ) nLength );
xmlTextWriterWriteFormatAttribute( writer,
BAD_CAST( "nType" ),
"%s", getTypeName( nType ) );
xmlTextWriterEndElement( writer );
}
/**
@param nLength
length of this portion in the model string
@param rText
text which is painted on-screen
@param nType
type of this portion
*/
virtual void Special( sal_uInt16 nLength,
const String & rText,
sal_uInt16 nType )
{
xmlTextWriterStartElement( writer, BAD_CAST( "Special" ) );
xmlTextWriterWriteFormatAttribute( writer,
BAD_CAST( "nLength" ),
"%i", ( int ) nLength );
xmlTextWriterWriteFormatAttribute( writer,
BAD_CAST( "nType" ),
"%s", getTypeName( nType ) );
rtl::OUString sText( rText );
rtl::OString sText8 =::rtl::OUStringToOString( sText,
RTL_TEXTENCODING_UTF8 );
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "rText" ),
"%s", sText8.getStr( ) );
xmlTextWriterEndElement( writer );
ofs += nLength;
}
virtual void LineBreak( )
{
xmlTextWriterStartElement( writer, BAD_CAST( "LineBreak" ) );
xmlTextWriterEndElement( writer );
}
/**
* @param nLength
* number of 'model string' characters to be skipped
*/
virtual void Skip( sal_uInt16 nLength )
{
xmlTextWriterStartElement( writer, BAD_CAST( "Skip" ) );
xmlTextWriterWriteFormatAttribute( writer,
BAD_CAST( "nLength" ),
"%i", ( int ) nLength );
xmlTextWriterEndElement( writer );
ofs += nLength;
}
virtual void Finish( )
{
xmlTextWriterStartElement( writer, BAD_CAST( "Finish" ) );
xmlTextWriterEndElement( writer );
}
};
namespace
{
xmlTextWriterPtr lcl_createDefaultWriter()
{
xmlTextWriterPtr writer = xmlNewTextWriterFilename( "layout.xml", 0 );
xmlTextWriterStartDocument( writer, NULL, NULL, NULL );
return writer;
}
void lcl_freeWriter( xmlTextWriterPtr writer )
{
xmlTextWriterEndDocument( writer );
xmlFreeTextWriter( writer );
}
}
void SwFrm::dumpAsXml( xmlTextWriterPtr writer )
{
bool bCreateWriter = ( NULL == writer );
if ( bCreateWriter )
writer = lcl_createDefaultWriter();
const char *name = NULL;
switch ( GetType( ) )
{
case FRM_ROOT:
name = "root";
break;
case FRM_PAGE:
name = "page";
break;
case FRM_COLUMN:
name = "column";
break;
case FRM_HEADER:
name = "header";
break;
case FRM_FOOTER:
name = "footer";
break;
case FRM_FTNCONT:
name = "ftncont";
break;
case FRM_FTN:
name = "ftn";
break;
case FRM_BODY:
name = "body";
break;
case FRM_FLY:
name = "fly";
break;
case FRM_SECTION:
name = "section";
break;
case FRM_UNUSED:
name = "unused";
break;
case FRM_TAB:
name = "tab";
break;
case FRM_ROW:
name = "row";
break;
case FRM_CELL:
name = "cell";
break;
case FRM_TXT:
name = "txt";
break;
case FRM_NOTXT:
name = "txt";
break;
};
if ( name != NULL )
{
xmlTextWriterStartElement( writer, ( const xmlChar * ) name );
dumpAsXmlAttributes( writer );
xmlTextWriterStartElement( writer, BAD_CAST( "infos" ) );
dumpInfosAsXml( writer );
xmlTextWriterEndElement( writer );
// Dump Anchored objects if any
SwSortedObjs* pAnchored = GetDrawObjs();
if ( pAnchored && pAnchored->Count( ) > 0 )
{
xmlTextWriterStartElement( writer, BAD_CAST( "anchored" ) );
for ( sal_uInt32 i = 0, len = pAnchored->Count(); i < len; i++ )
{
SwAnchoredObject* pObject = (*pAnchored)[i];
pObject->dumpAsXml( writer );
}
xmlTextWriterEndElement( writer );
}
// Dump the children
if ( IsTxtFrm( ) )
{
SwTxtFrm *pTxtFrm = ( SwTxtFrm * ) this;
rtl::OUString aTxt = pTxtFrm->GetTxt( );
for ( int i = 0; i < 32; i++ )
{
aTxt = aTxt.replace( i, '*' );
}
rtl::OString aTxt8 =::rtl::OUStringToOString( aTxt,
RTL_TEXTENCODING_UTF8 );
xmlTextWriterWriteString( writer,
( const xmlChar * ) aTxt8.getStr( ) );
XmlPortionDumper pdumper( writer );
pTxtFrm->VisitPortions( pdumper );
}
else
{
dumpChildrenAsXml( writer );
}
xmlTextWriterEndElement( writer );
}
if ( bCreateWriter )
lcl_freeWriter( writer );
}
void SwFrm::dumpInfosAsXml( xmlTextWriterPtr writer )
{
// output the Frm
xmlTextWriterStartElement( writer, BAD_CAST( "bounds" ) );
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "left" ), "%ld", Frm().Left() );
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "top" ), "%ld", Frm().Top() );
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "width" ), "%ld", Frm().Width() );
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "height" ), "%ld", Frm().Height() );
xmlTextWriterEndElement( writer );
}
void SwFrm::dumpAsXmlAttributes( xmlTextWriterPtr writer )
{
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "ptr" ), "%p", this );
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "id" ), "%u", GetFrmId() );
if ( GetNext( ) )
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "next" ), "%u", GetNext()->GetFrmId() );
if ( GetPrev( ) )
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "prev" ), "%u", GetPrev()->GetFrmId() );
if ( GetUpper( ) )
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "upper" ), "%u", GetUpper()->GetFrmId() );
if ( GetLower( ) )
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "lower" ), "%u", GetLower()->GetFrmId() );
if ( IsTxtFrm( ) )
{
SwTxtFrm *pTxtFrm = ( SwTxtFrm * ) this;
SwTxtNode *pTxtNode = pTxtFrm->GetTxtNode();
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "txtNodeIndex" ), "%lu", pTxtNode->GetIndex() );
}
}
void SwFrm::dumpChildrenAsXml( xmlTextWriterPtr writer )
{
SwFrm *pFrm = GetLower( );
for ( ; pFrm != NULL; pFrm = pFrm->GetNext( ) )
{
pFrm->dumpAsXml( writer );
}
}
void SwAnchoredObject::dumpAsXml( xmlTextWriterPtr writer )
{
bool bCreateWriter = ( NULL == writer );
if ( bCreateWriter )
writer = lcl_createDefaultWriter();
xmlTextWriterStartElement( writer, BAD_CAST( getElementName() ) );
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "ptr" ), "%p", this );
xmlTextWriterEndElement( writer );
if ( bCreateWriter )
lcl_freeWriter( writer );
}
void SwTxtFrm::dumpAsXmlAttributes( xmlTextWriterPtr writer )
{
SwFrm::dumpAsXmlAttributes( writer );
if ( HasFollow() )
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "follow" ), "%u", GetFollow()->GetFrmId() );
if (m_pPrecede != NULL)
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "precede" ), "%u", static_cast<SwTxtFrm*>(m_pPrecede)->GetFrmId() );
}
void SwSectionFrm::dumpAsXmlAttributes( xmlTextWriterPtr writer )
{
SwFrm::dumpAsXmlAttributes( writer );
if ( HasFollow() )
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "follow" ), "%u", GetFollow()->GetFrmId() );
if (m_pPrecede != NULL)
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "precede" ), "%u", static_cast<SwSectionFrm*>( m_pPrecede )->GetFrmId() );
}
void SwTabFrm::dumpAsXmlAttributes( xmlTextWriterPtr writer )
{
SwFrm::dumpAsXmlAttributes( writer );
if ( HasFollow() )
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "follow" ), "%u", GetFollow()->GetFrmId() );
if (m_pPrecede != NULL)
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "precede" ), "%u", static_cast<SwTabFrm*>( m_pPrecede )->GetFrmId() );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: '%u' expects 'unsigned int', but argument is 'sal_uInt32'<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Initial Developer of the Original Code is
* Novell Inc.
* Portions created by the Initial Developer are Copyright (C) 2010 the
* Initial Developer. All Rights Reserved.
*
* Contributor(s): Florian Reuter <freuter@novell.com>
* Cedric Bosdonnat <cbosdonnat@novell.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include "frame.hxx"
#include "frmfmt.hxx"
#include "sectfrm.hxx"
#include "tabfrm.hxx"
#include "txtfrm.hxx"
#include "porlin.hxx"
#include "porlay.hxx"
#include "portxt.hxx"
#include "sortedobjs.hxx"
#include <anchoredobject.hxx>
#include <libxml/xmlwriter.h>
#include <SwPortionHandler.hxx>
class XmlPortionDumper:public SwPortionHandler
{
private:
xmlTextWriterPtr writer;
sal_uInt16 ofs;
const char* getTypeName( sal_uInt16 nType )
{
switch ( nType )
{
case POR_LIN: return "POR_LIN";
case POR_FLYCNT: return "POR_FLYCNT";
case POR_HOLE: return "POR_HOLE";
case POR_TMPEND: return "POR_TMPEND";
case POR_BRK: return "POR_BRK";
case POR_KERN: return "POR_KERN";
case POR_ARROW: return "POR_ARROW";
case POR_MULTI: return "POR_MULTI";
case POR_HIDDEN_TXT: return "POR_HIDDEN_TXT";
case POR_CONTROLCHAR: return "POR_CONTROLCHAR";
case POR_TXT: return "POR_TXT";
case POR_LAY: return "POR_LAY";
case POR_PARA: return "POR_PARA";
case POR_URL: return "POR_URL";
case POR_HNG: return "POR_HNG";
case POR_DROP: return "POR_DROP";
case POR_TOX: return "POR_TOX";
case POR_ISOTOX: return "POR_ISOTOX";
case POR_REF: return "POR_REF";
case POR_ISOREF: return "POR_ISOREF";
case POR_META: return "POR_META";
case POR_EXP: return "POR_EXP";
case POR_BLANK: return "POR_BLANK";
case POR_POSTITS: return "POR_POSTITS";
case POR_HYPH: return "POR_HYPH";
case POR_HYPHSTR: return "POR_HYPHSTR";
case POR_SOFTHYPH: return "POR_SOFTHYPH";
case POR_SOFTHYPHSTR: return "POR_SOFTHYPHSTR";
case POR_SOFTHYPH_COMP: return "POR_SOFTHYPH_COMP";
case POR_FLD: return "POR_FLD";
case POR_HIDDEN: return "POR_HIDDEN";
case POR_QUOVADIS: return "POR_QUOVADIS";
case POR_ERGOSUM: return "POR_ERGOSUM";
case POR_COMBINED: return "POR_COMBINED";
case POR_FTN: return "POR_FTN";
case POR_FTNNUM: return "POR_FTNNUM";
case POR_NUMBER: return "POR_NUMBER";
case POR_BULLET: return "POR_BULLET";
case POR_GRFNUM: return "POR_GRFNUM";
case POR_GLUE: return "POR_GLUE";
case POR_MARGIN: return "POR_MARGIN";
case POR_FIX: return "POR_FIX";
case POR_FLY: return "POR_FLY";
case POR_TAB: return "POR_TAB";
case POR_TABRIGHT: return "POR_TABRIGHT";
case POR_TABCENTER: return "POR_TABCENTER";
case POR_TABDECIMAL: return "POR_TABDECIMAL";
case POR_TABLEFT: return "POR_TABLEFT";
default:
return "Unknown";
}
}
public:
XmlPortionDumper( xmlTextWriterPtr some_writer ):writer( some_writer ), ofs( 0 )
{
}
virtual ~ XmlPortionDumper( )
{
}
/**
@param nLength
length of this portion in the model string
@param rText
text which is painted on-screen
*/
virtual void Text( sal_uInt16 nLength,
sal_uInt16 nType )
{
ofs += nLength;
xmlTextWriterStartElement( writer, BAD_CAST( "Text" ) );
xmlTextWriterWriteFormatAttribute( writer,
BAD_CAST( "nLength" ),
"%i", ( int ) nLength );
xmlTextWriterWriteFormatAttribute( writer,
BAD_CAST( "nType" ),
"%s", getTypeName( nType ) );
xmlTextWriterEndElement( writer );
}
/**
@param nLength
length of this portion in the model string
@param rText
text which is painted on-screen
@param nType
type of this portion
*/
virtual void Special( sal_uInt16 nLength,
const String & rText,
sal_uInt16 nType )
{
xmlTextWriterStartElement( writer, BAD_CAST( "Special" ) );
xmlTextWriterWriteFormatAttribute( writer,
BAD_CAST( "nLength" ),
"%i", ( int ) nLength );
xmlTextWriterWriteFormatAttribute( writer,
BAD_CAST( "nType" ),
"%s", getTypeName( nType ) );
rtl::OUString sText( rText );
rtl::OString sText8 =::rtl::OUStringToOString( sText,
RTL_TEXTENCODING_UTF8 );
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "rText" ),
"%s", sText8.getStr( ) );
xmlTextWriterEndElement( writer );
ofs += nLength;
}
virtual void LineBreak( )
{
xmlTextWriterStartElement( writer, BAD_CAST( "LineBreak" ) );
xmlTextWriterEndElement( writer );
}
/**
* @param nLength
* number of 'model string' characters to be skipped
*/
virtual void Skip( sal_uInt16 nLength )
{
xmlTextWriterStartElement( writer, BAD_CAST( "Skip" ) );
xmlTextWriterWriteFormatAttribute( writer,
BAD_CAST( "nLength" ),
"%i", ( int ) nLength );
xmlTextWriterEndElement( writer );
ofs += nLength;
}
virtual void Finish( )
{
xmlTextWriterStartElement( writer, BAD_CAST( "Finish" ) );
xmlTextWriterEndElement( writer );
}
};
namespace
{
xmlTextWriterPtr lcl_createDefaultWriter()
{
xmlTextWriterPtr writer = xmlNewTextWriterFilename( "layout.xml", 0 );
xmlTextWriterStartDocument( writer, NULL, NULL, NULL );
return writer;
}
void lcl_freeWriter( xmlTextWriterPtr writer )
{
xmlTextWriterEndDocument( writer );
xmlFreeTextWriter( writer );
}
}
void SwFrm::dumpAsXml( xmlTextWriterPtr writer )
{
bool bCreateWriter = ( NULL == writer );
if ( bCreateWriter )
writer = lcl_createDefaultWriter();
const char *name = NULL;
switch ( GetType( ) )
{
case FRM_ROOT:
name = "root";
break;
case FRM_PAGE:
name = "page";
break;
case FRM_COLUMN:
name = "column";
break;
case FRM_HEADER:
name = "header";
break;
case FRM_FOOTER:
name = "footer";
break;
case FRM_FTNCONT:
name = "ftncont";
break;
case FRM_FTN:
name = "ftn";
break;
case FRM_BODY:
name = "body";
break;
case FRM_FLY:
name = "fly";
break;
case FRM_SECTION:
name = "section";
break;
case FRM_UNUSED:
name = "unused";
break;
case FRM_TAB:
name = "tab";
break;
case FRM_ROW:
name = "row";
break;
case FRM_CELL:
name = "cell";
break;
case FRM_TXT:
name = "txt";
break;
case FRM_NOTXT:
name = "txt";
break;
};
if ( name != NULL )
{
xmlTextWriterStartElement( writer, ( const xmlChar * ) name );
dumpAsXmlAttributes( writer );
xmlTextWriterStartElement( writer, BAD_CAST( "infos" ) );
dumpInfosAsXml( writer );
xmlTextWriterEndElement( writer );
// Dump Anchored objects if any
SwSortedObjs* pAnchored = GetDrawObjs();
if ( pAnchored && pAnchored->Count( ) > 0 )
{
xmlTextWriterStartElement( writer, BAD_CAST( "anchored" ) );
for ( sal_uInt32 i = 0, len = pAnchored->Count(); i < len; i++ )
{
SwAnchoredObject* pObject = (*pAnchored)[i];
pObject->dumpAsXml( writer );
}
xmlTextWriterEndElement( writer );
}
// Dump the children
if ( IsTxtFrm( ) )
{
SwTxtFrm *pTxtFrm = ( SwTxtFrm * ) this;
rtl::OUString aTxt = pTxtFrm->GetTxt( );
for ( int i = 0; i < 32; i++ )
{
aTxt = aTxt.replace( i, '*' );
}
rtl::OString aTxt8 =::rtl::OUStringToOString( aTxt,
RTL_TEXTENCODING_UTF8 );
xmlTextWriterWriteString( writer,
( const xmlChar * ) aTxt8.getStr( ) );
XmlPortionDumper pdumper( writer );
pTxtFrm->VisitPortions( pdumper );
}
else
{
dumpChildrenAsXml( writer );
}
xmlTextWriterEndElement( writer );
}
if ( bCreateWriter )
lcl_freeWriter( writer );
}
void SwFrm::dumpInfosAsXml( xmlTextWriterPtr writer )
{
// output the Frm
xmlTextWriterStartElement( writer, BAD_CAST( "bounds" ) );
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "left" ), "%ld", Frm().Left() );
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "top" ), "%ld", Frm().Top() );
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "width" ), "%ld", Frm().Width() );
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "height" ), "%ld", Frm().Height() );
xmlTextWriterEndElement( writer );
}
void SwFrm::dumpAsXmlAttributes( xmlTextWriterPtr writer )
{
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "ptr" ), "%p", this );
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "id" ), "%"SAL_PRIuUINT32, GetFrmId() );
if ( GetNext( ) )
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "next" ), "%"SAL_PRIuUINT32, GetNext()->GetFrmId() );
if ( GetPrev( ) )
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "prev" ), "%"SAL_PRIuUINT32, GetPrev()->GetFrmId() );
if ( GetUpper( ) )
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "upper" ), "%"SAL_PRIuUINT32, GetUpper()->GetFrmId() );
if ( GetLower( ) )
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "lower" ), "%"SAL_PRIuUINT32, GetLower()->GetFrmId() );
if ( IsTxtFrm( ) )
{
SwTxtFrm *pTxtFrm = ( SwTxtFrm * ) this;
SwTxtNode *pTxtNode = pTxtFrm->GetTxtNode();
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "txtNodeIndex" ), "%lu", pTxtNode->GetIndex() );
}
}
void SwFrm::dumpChildrenAsXml( xmlTextWriterPtr writer )
{
SwFrm *pFrm = GetLower( );
for ( ; pFrm != NULL; pFrm = pFrm->GetNext( ) )
{
pFrm->dumpAsXml( writer );
}
}
void SwAnchoredObject::dumpAsXml( xmlTextWriterPtr writer )
{
bool bCreateWriter = ( NULL == writer );
if ( bCreateWriter )
writer = lcl_createDefaultWriter();
xmlTextWriterStartElement( writer, BAD_CAST( getElementName() ) );
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "ptr" ), "%p", this );
xmlTextWriterEndElement( writer );
if ( bCreateWriter )
lcl_freeWriter( writer );
}
void SwTxtFrm::dumpAsXmlAttributes( xmlTextWriterPtr writer )
{
SwFrm::dumpAsXmlAttributes( writer );
if ( HasFollow() )
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "follow" ), "%"SAL_PRIuUINT32, GetFollow()->GetFrmId() );
if (m_pPrecede != NULL)
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "precede" ), "%"SAL_PRIuUINT32, static_cast<SwTxtFrm*>(m_pPrecede)->GetFrmId() );
}
void SwSectionFrm::dumpAsXmlAttributes( xmlTextWriterPtr writer )
{
SwFrm::dumpAsXmlAttributes( writer );
if ( HasFollow() )
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "follow" ), "%"SAL_PRIuUINT32, GetFollow()->GetFrmId() );
if (m_pPrecede != NULL)
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "precede" ), "%"SAL_PRIuUINT32, static_cast<SwSectionFrm*>( m_pPrecede )->GetFrmId() );
}
void SwTabFrm::dumpAsXmlAttributes( xmlTextWriterPtr writer )
{
SwFrm::dumpAsXmlAttributes( writer );
if ( HasFollow() )
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "follow" ), "%"SAL_PRIuUINT32, GetFollow()->GetFrmId() );
if (m_pPrecede != NULL)
xmlTextWriterWriteFormatAttribute( writer, BAD_CAST( "precede" ), "%"SAL_PRIuUINT32, static_cast<SwTabFrm*>( m_pPrecede )->GetFrmId() );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: dselect.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: os $ $Date: 2002-12-05 12:47:05 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif
#pragma hdrstop
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#include "view.hxx"
#include "edtwin.hxx"
#include "wrtsh.hxx"
#include "cmdid.h"
#include "drawbase.hxx"
#include "dselect.hxx"
extern BOOL bNoInterrupt; // in mainwn.cxx
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
DrawSelection::DrawSelection(SwWrtShell* pWrtShell, SwEditWin* pEditWin, SwView* pSwView) :
SwDrawBase(pWrtShell, pEditWin, pSwView)
{
bCreateObj = FALSE;
}
/*************************************************************************
|*
|* Tastaturereignisse bearbeiten
|*
|* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls
|* FALSE.
|*
\************************************************************************/
BOOL DrawSelection::KeyInput(const KeyEvent& rKEvt)
{
BOOL bReturn = FALSE;
switch (rKEvt.GetKeyCode().GetCode())
{
case KEY_ESCAPE:
{
if (pWin->IsDrawAction())
{
pSh->BreakMark();
pWin->ReleaseMouse();
}
bReturn = TRUE;
}
break;
}
if (!bReturn)
bReturn = SwDrawBase::KeyInput(rKEvt);
return (bReturn);
}
/*************************************************************************
|*
|* Function aktivieren
|*
\************************************************************************/
void DrawSelection::Activate(const USHORT nSlotId)
{
pWin->SetDrawMode(SID_OBJECT_SELECT);
SwDrawBase::Activate(nSlotId);
pSh->GetView().GetViewFrame()->GetBindings().Invalidate(SID_INSERT_DRAW);
}
<commit_msg>INTEGRATION: CWS os8 (1.2.138); FILE MERGED 2003/04/03 07:14:54 os 1.2.138.1: #108583# precompiled headers removed<commit_after>/*************************************************************************
*
* $RCSfile: dselect.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2003-04-17 15:39:19 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#include "view.hxx"
#include "edtwin.hxx"
#include "wrtsh.hxx"
#include "cmdid.h"
#include "drawbase.hxx"
#include "dselect.hxx"
extern BOOL bNoInterrupt; // in mainwn.cxx
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
DrawSelection::DrawSelection(SwWrtShell* pWrtShell, SwEditWin* pEditWin, SwView* pSwView) :
SwDrawBase(pWrtShell, pEditWin, pSwView)
{
bCreateObj = FALSE;
}
/*************************************************************************
|*
|* Tastaturereignisse bearbeiten
|*
|* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls
|* FALSE.
|*
\************************************************************************/
BOOL DrawSelection::KeyInput(const KeyEvent& rKEvt)
{
BOOL bReturn = FALSE;
switch (rKEvt.GetKeyCode().GetCode())
{
case KEY_ESCAPE:
{
if (pWin->IsDrawAction())
{
pSh->BreakMark();
pWin->ReleaseMouse();
}
bReturn = TRUE;
}
break;
}
if (!bReturn)
bReturn = SwDrawBase::KeyInput(rKEvt);
return (bReturn);
}
/*************************************************************************
|*
|* Function aktivieren
|*
\************************************************************************/
void DrawSelection::Activate(const USHORT nSlotId)
{
pWin->SetDrawMode(SID_OBJECT_SELECT);
SwDrawBase::Activate(nSlotId);
pSh->GetView().GetViewFrame()->GetBindings().Invalidate(SID_INSERT_DRAW);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: viewdlg.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2003-04-17 15:50:37 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "hintids.hxx"
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SVX_TSPTITEM_HXX //autogen
#include <svx/tstpitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#include "view.hxx"
#include "wrtsh.hxx"
#include "basesh.hxx"
#include "viewopt.hxx"
#include "uitool.hxx"
#include "cmdid.h"
#include "docstdlg.hxx"
#include "pagedesc.hxx"
void SwView::ExecDlg(SfxRequest &rReq)
{
Window *pMDI = &GetViewFrame()->GetWindow();
ModalDialog *pDialog = 0;
//Damit aus dem Basic keine Dialoge fuer Hintergrund-Views aufgerufen werden:
const SfxPoolItem* pItem = 0;
const SfxItemSet* pArgs = rReq.GetArgs();
USHORT nSlot = rReq.GetSlot();
if(pArgs)
pArgs->GetItemState( GetPool().GetWhich(nSlot), FALSE, &pItem );
switch ( nSlot )
{
case FN_CHANGE_PAGENUM:
{
if ( pItem )
{
USHORT nValue = ((SfxUInt16Item *)pItem)->GetValue();
USHORT nOldValue = pWrtShell->GetPageOffset();
USHORT nPage, nLogPage;
pWrtShell->GetPageNum( nPage, nLogPage,
pWrtShell->IsCrsrVisible(), FALSE);
if(nValue != nOldValue || nValue != nLogPage)
{
if(!nOldValue)
pWrtShell->SetNewPageOffset( nValue );
else
pWrtShell->SetPageOffset( nValue );
}
}
}
break;
default:
ASSERT(!this, falscher Dispatcher);
return;
}
if( pDialog )
{
pDialog->Execute();
delete pDialog;
}
}
<commit_msg>INTEGRATION: CWS dialogdiet01 (1.3.420); FILE MERGED 2004/03/26 09:12:15 mwu 1.3.420.1: sw model converted. 20040326<commit_after>/*************************************************************************
*
* $RCSfile: viewdlg.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2004-05-10 16:39:17 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "hintids.hxx"
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SVX_TSPTITEM_HXX //autogen
#include <svx/tstpitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#include "view.hxx"
#include "wrtsh.hxx"
#include "basesh.hxx"
#include "viewopt.hxx"
#include "uitool.hxx"
#include "cmdid.h"
//CHINA001 #include "docstdlg.hxx"
#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>//add CHINA001
#endif
#include "pagedesc.hxx"
void SwView::ExecDlg(SfxRequest &rReq)
{
Window *pMDI = &GetViewFrame()->GetWindow();
ModalDialog *pDialog = 0;
//Damit aus dem Basic keine Dialoge fuer Hintergrund-Views aufgerufen werden:
const SfxPoolItem* pItem = 0;
const SfxItemSet* pArgs = rReq.GetArgs();
USHORT nSlot = rReq.GetSlot();
if(pArgs)
pArgs->GetItemState( GetPool().GetWhich(nSlot), FALSE, &pItem );
switch ( nSlot )
{
case FN_CHANGE_PAGENUM:
{
if ( pItem )
{
USHORT nValue = ((SfxUInt16Item *)pItem)->GetValue();
USHORT nOldValue = pWrtShell->GetPageOffset();
USHORT nPage, nLogPage;
pWrtShell->GetPageNum( nPage, nLogPage,
pWrtShell->IsCrsrVisible(), FALSE);
if(nValue != nOldValue || nValue != nLogPage)
{
if(!nOldValue)
pWrtShell->SetNewPageOffset( nValue );
else
pWrtShell->SetPageOffset( nValue );
}
}
}
break;
default:
ASSERT(!this, falscher Dispatcher);
return;
}
if( pDialog )
{
pDialog->Execute();
delete pDialog;
}
}
<|endoftext|>
|
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Razor team
* Authors:
* Johannes Zellner <webmaster@nebulon.de>
*
* 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 "pulseaudiodevice.h"
#include "pulseaudioengine.h"
PulseAudioDevice::PulseAudioDevice(PulseAudioDeviceType t, PulseAudioEngine *engine, QObject *parent) :
QObject(parent),
m_engine(engine),
m_volume(0),
m_mute(false),
m_type(t)
{
}
PulseAudioDevice::~PulseAudioDevice()
{
}
// this is just for setting the internal volume
void PulseAudioDevice::setVolumeNoCommit(int volume)
{
if (m_volume == volume)
return;
m_volume = volume;
emit volumeChanged(m_volume);
}
void PulseAudioDevice::toggleMute()
{
m_engine->setMute(this, !m_mute);
}
void PulseAudioDevice::setMute(bool state)
{
if (m_mute == state)
return;
m_mute = state;
emit muteChanged();
}
void PulseAudioDevice::increaseVolume()
{
setVolume(volume()+10);
}
void PulseAudioDevice::decreaseVolume()
{
setVolume(volume()-10);
}
// this performs a volume change on the device
void PulseAudioDevice::setVolume(int volume)
{
int tmp = volume;
if (tmp < 0)
tmp = 0;
else if (tmp > (int)PA_VOLUME_UI_MAX)
tmp = PA_VOLUME_UI_MAX;
if (m_volume == tmp)
return;
m_volume = tmp;
if (m_engine)
m_engine->commitDeviceVolume(this);
}
<commit_msg>panel-volume: qBound is much nicer, thanks for the hint from Alexander Sokolov<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Razor team
* Authors:
* Johannes Zellner <webmaster@nebulon.de>
*
* 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 "pulseaudiodevice.h"
#include "pulseaudioengine.h"
PulseAudioDevice::PulseAudioDevice(PulseAudioDeviceType t, PulseAudioEngine *engine, QObject *parent) :
QObject(parent),
m_engine(engine),
m_volume(0),
m_mute(false),
m_type(t)
{
}
PulseAudioDevice::~PulseAudioDevice()
{
}
// this is just for setting the internal volume
void PulseAudioDevice::setVolumeNoCommit(int volume)
{
if (m_volume == volume)
return;
m_volume = volume;
emit volumeChanged(m_volume);
}
void PulseAudioDevice::toggleMute()
{
m_engine->setMute(this, !m_mute);
}
void PulseAudioDevice::setMute(bool state)
{
if (m_mute == state)
return;
m_mute = state;
emit muteChanged();
}
void PulseAudioDevice::increaseVolume()
{
setVolume(volume()+10);
}
void PulseAudioDevice::decreaseVolume()
{
setVolume(volume()-10);
}
// this performs a volume change on the device
void PulseAudioDevice::setVolume(int volume)
{
volume = qBound(0, volume, (int)PA_VOLUME_UI_MAX);
if (m_volume == volume)
return;
m_volume = volume;
if (m_engine)
m_engine->commitDeviceVolume(this);
}
<|endoftext|>
|
<commit_before>#include "p0run/interpreter.hpp"
#include "p0run/string.hpp"
#include "p0run/table.hpp"
#include "p0compile/compiler.hpp"
#include "p0compile/compiler_error.hpp"
#include <boost/test/unit_test.hpp>
using namespace p0::run;
namespace
{
bool expect_no_error(p0::compiler_error const &error)
{
std::cerr << error.what() << '\n';
BOOST_CHECK(nullptr == "no error expected");
return true;
}
template <class CheckResult>
void run_valid_source(
std::string const &source,
std::vector<value> const &arguments,
CheckResult const &check_result)
{
p0::source_range const source_range(
source.data(),
source.data() + source.size());
p0::compiler compiler(source_range, expect_no_error);
auto const program = compiler.compile();
p0::run::interpreter interpreter(program, nullptr);
auto const &main_function = program.functions().front();
auto const result = interpreter.call(main_function, arguments);
check_result(result, program);
}
void check_invalid_source(std::string const &source,
std::size_t error_position)
{
auto const check_compiler_error =
[&source, error_position](p0::compiler_error const &error) -> bool
{
auto const found_error_position = error.position().begin();
BOOST_CHECK(source.data() + error_position == found_error_position);
return true;
};
p0::source_range const source_range(
source.data(),
source.data() + source.size());
p0::compiler compiler(source_range, check_compiler_error);
compiler.compile(); //TODO make compile() throw
}
}
BOOST_AUTO_TEST_CASE(empty_function_compile_test)
{
std::string const source = "";
std::vector<p0::run::value> const arguments;
run_valid_source(source, arguments,
[](p0::run::value const &result, p0::intermediate::unit const &program)
{
auto const &main_function = program.functions().front();
BOOST_CHECK(result == value(main_function));
});
}
BOOST_AUTO_TEST_CASE(return_integer_compile_test)
{
std::string const source = "return 123";
std::vector<value> const arguments;
run_valid_source(source, arguments,
[](value const &result, p0::intermediate::unit const & /*program*/)
{
BOOST_CHECK(result == value(static_cast<integer>(123)));
});
}
BOOST_AUTO_TEST_CASE(return_null_compile_test)
{
std::string const source = "return null";
std::vector<value> const arguments;
run_valid_source(source, arguments,
[](value const &result, p0::intermediate::unit const & /*program*/)
{
BOOST_CHECK(is_null(result));
});
}
BOOST_AUTO_TEST_CASE(return_string_compile_test)
{
std::string const source = "return \"hello, world!\"";
std::vector<value> const arguments;
run_valid_source(source, arguments,
[](value const &result, p0::intermediate::unit const & /*program*/)
{
BOOST_REQUIRE(result.type == value_type::object);
BOOST_REQUIRE(dynamic_cast<string const *>(result.obj));
BOOST_CHECK(dynamic_cast<string const &>(*result.obj).content() == "hello, world!");
});
}
BOOST_AUTO_TEST_CASE(return_empty_table_compile_test)
{
std::string const source = "return []";
std::vector<value> const arguments;
run_valid_source(source, arguments,
[](value const &result, p0::intermediate::unit const & /*program*/)
{
BOOST_REQUIRE(result.type == value_type::object);
BOOST_REQUIRE(dynamic_cast<table const *>(result.obj));
});
}
BOOST_AUTO_TEST_CASE(return_trivial_table_compile_test)
{
std::string const source = "var t = [] t[123] = 456 return t";
std::vector<value> const arguments;
run_valid_source(source, arguments,
[](value const &result, p0::intermediate::unit const & /*program*/)
{
BOOST_REQUIRE(result.type == value_type::object);
BOOST_REQUIRE(dynamic_cast<table const *>(result.obj));
auto const element = dynamic_cast<table const &>(*result.obj).get_element(
value(static_cast<integer>(123)));
BOOST_REQUIRE(element);
BOOST_CHECK(*element == value(static_cast<integer>(456)));
});
}
BOOST_AUTO_TEST_CASE(misplaced_break_continue_test)
{
check_invalid_source("break", 0);
check_invalid_source("continue", 0);
check_invalid_source("{break}", 1);
check_invalid_source("{continue}", 1);
}
<commit_msg>better notation for illformed source tests<commit_after>#include "p0run/interpreter.hpp"
#include "p0run/string.hpp"
#include "p0run/table.hpp"
#include "p0compile/compiler.hpp"
#include "p0compile/compiler_error.hpp"
#include <boost/test/unit_test.hpp>
using namespace p0::run;
namespace
{
bool expect_no_error(p0::compiler_error const &error)
{
std::cerr << error.what() << '\n';
BOOST_CHECK(nullptr == "no error expected");
return true;
}
template <class CheckResult>
void run_valid_source(
std::string const &source,
std::vector<value> const &arguments,
CheckResult const &check_result)
{
p0::source_range const source_range(
source.data(),
source.data() + source.size());
p0::compiler compiler(source_range, expect_no_error);
auto const program = compiler.compile();
p0::run::interpreter interpreter(program, nullptr);
auto const &main_function = program.functions().front();
auto const result = interpreter.call(main_function, arguments);
check_result(result, program);
}
bool test_invalid_source(std::string const &correct_head,
std::string const &illformed_tail)
{
auto const full_source = correct_head + illformed_tail;
auto const error_position = correct_head.size();
bool found_expected_error = false;
auto const check_compiler_error =
[&full_source, error_position, &found_expected_error]
(p0::compiler_error const &error) -> bool
{
auto const found_error_position = error.position().begin();
found_expected_error = (full_source.data() + error_position == found_error_position);
return true;
};
p0::source_range const source_range(
full_source.data(),
full_source.data() + full_source.size());
p0::compiler compiler(source_range, check_compiler_error);
compiler.compile(); //TODO make compile() throw
return found_expected_error;
}
}
BOOST_AUTO_TEST_CASE(empty_function_compile_test)
{
std::string const source = "";
std::vector<p0::run::value> const arguments;
run_valid_source(source, arguments,
[](p0::run::value const &result, p0::intermediate::unit const &program)
{
auto const &main_function = program.functions().front();
BOOST_CHECK(result == value(main_function));
});
}
BOOST_AUTO_TEST_CASE(return_integer_compile_test)
{
std::string const source = "return 123";
std::vector<value> const arguments;
run_valid_source(source, arguments,
[](value const &result, p0::intermediate::unit const & /*program*/)
{
BOOST_CHECK(result == value(static_cast<integer>(123)));
});
}
BOOST_AUTO_TEST_CASE(return_null_compile_test)
{
std::string const source = "return null";
std::vector<value> const arguments;
run_valid_source(source, arguments,
[](value const &result, p0::intermediate::unit const & /*program*/)
{
BOOST_CHECK(is_null(result));
});
}
BOOST_AUTO_TEST_CASE(return_string_compile_test)
{
std::string const source = "return \"hello, world!\"";
std::vector<value> const arguments;
run_valid_source(source, arguments,
[](value const &result, p0::intermediate::unit const & /*program*/)
{
BOOST_REQUIRE(result.type == value_type::object);
BOOST_REQUIRE(dynamic_cast<string const *>(result.obj));
BOOST_CHECK(dynamic_cast<string const &>(*result.obj).content() == "hello, world!");
});
}
BOOST_AUTO_TEST_CASE(return_empty_table_compile_test)
{
std::string const source = "return []";
std::vector<value> const arguments;
run_valid_source(source, arguments,
[](value const &result, p0::intermediate::unit const & /*program*/)
{
BOOST_REQUIRE(result.type == value_type::object);
BOOST_REQUIRE(dynamic_cast<table const *>(result.obj));
});
}
BOOST_AUTO_TEST_CASE(return_trivial_table_compile_test)
{
std::string const source = "var t = [] t[123] = 456 return t";
std::vector<value> const arguments;
run_valid_source(source, arguments,
[](value const &result, p0::intermediate::unit const & /*program*/)
{
BOOST_REQUIRE(result.type == value_type::object);
BOOST_REQUIRE(dynamic_cast<table const *>(result.obj));
auto const element = dynamic_cast<table const &>(*result.obj).get_element(
value(static_cast<integer>(123)));
BOOST_REQUIRE(element);
BOOST_CHECK(*element == value(static_cast<integer>(456)));
});
}
BOOST_AUTO_TEST_CASE(misplaced_break_continue_test)
{
BOOST_CHECK(test_invalid_source("", "break"));
BOOST_CHECK(test_invalid_source("", "continue"));
BOOST_CHECK(test_invalid_source("{", "break}"));
BOOST_CHECK(test_invalid_source("{", "continue}"));
// BOOST_CHECK(test_invalid_source("while true { function () {", "break} }"));
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015-2018 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
*
* Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
*
* This program 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 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "medialibrary/IMediaLibrary.h"
#include "test/mocks/NoopCallback.h"
#include <iostream>
#include <condition_variable>
#include <mutex>
class TestCb : public mock::NoopCallback
{
public:
TestCb()
: m_nbDiscoveryToRun( 0 )
, m_nbDiscoveryCompleted( 0 )
, m_isParsingCompleted( false )
, m_isIdle( false )
, m_error( false )
{
}
bool waitForCompletion()
{
std::unique_lock<std::mutex> lock( m_mutex );
m_cond.wait( lock, [this](){
return (m_nbDiscoveryToRun > 0 &&
m_nbDiscoveryToRun == m_nbDiscoveryCompleted &&
m_isParsingCompleted == true &&
m_isIdle == true) || m_error;
});
return m_error == false;
}
private:
virtual void onDiscoveryStarted( const std::string& ) override
{
{
std::lock_guard<std::mutex> lock( m_mutex );
m_nbDiscoveryToRun++;
m_isParsingCompleted = false;
}
m_cond.notify_all();
}
virtual void onDiscoveryCompleted(const std::string&, bool success ) override
{
{
std::lock_guard<std::mutex> lock( m_mutex );
if ( success == true )
m_nbDiscoveryCompleted++;
else
m_error = true;
}
m_cond.notify_all();
}
virtual void onParsingStatsUpdated(uint32_t percent) override
{
{
std::lock_guard<std::mutex> lock( m_mutex );
m_isParsingCompleted = percent == 100;
}
m_cond.notify_all();
}
virtual void onBackgroundTasksIdleChanged(bool isIdle) override
{
{
std::lock_guard<std::mutex> lock( m_mutex );
m_isIdle = isIdle;
}
m_cond.notify_all();
}
private:
std::condition_variable m_cond;
std::mutex m_mutex;
uint32_t m_nbDiscoveryToRun;
uint32_t m_nbDiscoveryCompleted;
bool m_isParsingCompleted;
bool m_isIdle;
bool m_error;
};
int main( int argc, char** argv )
{
if ( argc < 2 )
{
std::cerr << "usage: " << argv[0] << " <entrypoint>" << std::endl;
return 1;
}
auto testCb = std::make_unique<TestCb>();
std::unique_ptr<medialibrary::IMediaLibrary> ml( NewMediaLibrary() );
ml->setVerbosity( medialibrary::LogLevel::Info );
ml->initialize( "/tmp/test.db", "/tmp/ml_folder", testCb.get() );
ml->setDiscoverNetworkEnabled( true );
ml->start();
ml->discover( argv[1] );
auto res = testCb->waitForCompletion();
return res == true ? 0 : 1;
}
<commit_msg>test: discoverer: Ensure we start with a clean database<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015-2018 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
*
* Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
*
* This program 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 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "medialibrary/IMediaLibrary.h"
#include "test/mocks/NoopCallback.h"
#include <iostream>
#include <condition_variable>
#include <mutex>
#include <unistd.h>
class TestCb : public mock::NoopCallback
{
public:
TestCb()
: m_nbDiscoveryToRun( 0 )
, m_nbDiscoveryCompleted( 0 )
, m_isParsingCompleted( false )
, m_isIdle( false )
, m_error( false )
{
}
bool waitForCompletion()
{
std::unique_lock<std::mutex> lock( m_mutex );
m_cond.wait( lock, [this](){
return (m_nbDiscoveryToRun > 0 &&
m_nbDiscoveryToRun == m_nbDiscoveryCompleted &&
m_isParsingCompleted == true &&
m_isIdle == true) || m_error;
});
return m_error == false;
}
private:
virtual void onDiscoveryStarted( const std::string& ) override
{
{
std::lock_guard<std::mutex> lock( m_mutex );
m_nbDiscoveryToRun++;
m_isParsingCompleted = false;
}
m_cond.notify_all();
}
virtual void onDiscoveryCompleted(const std::string&, bool success ) override
{
{
std::lock_guard<std::mutex> lock( m_mutex );
if ( success == true )
m_nbDiscoveryCompleted++;
else
m_error = true;
}
m_cond.notify_all();
}
virtual void onParsingStatsUpdated(uint32_t percent) override
{
{
std::lock_guard<std::mutex> lock( m_mutex );
m_isParsingCompleted = percent == 100;
}
m_cond.notify_all();
}
virtual void onBackgroundTasksIdleChanged(bool isIdle) override
{
{
std::lock_guard<std::mutex> lock( m_mutex );
m_isIdle = isIdle;
}
m_cond.notify_all();
}
private:
std::condition_variable m_cond;
std::mutex m_mutex;
uint32_t m_nbDiscoveryToRun;
uint32_t m_nbDiscoveryCompleted;
bool m_isParsingCompleted;
bool m_isIdle;
bool m_error;
};
int main( int argc, char** argv )
{
if ( argc < 2 )
{
std::cerr << "usage: " << argv[0] << " <entrypoint>" << std::endl;
return 1;
}
unlink( "/tmp/test.db" );
auto testCb = std::make_unique<TestCb>();
std::unique_ptr<medialibrary::IMediaLibrary> ml( NewMediaLibrary() );
ml->setVerbosity( medialibrary::LogLevel::Info );
ml->initialize( "/tmp/test.db", "/tmp/ml_folder", testCb.get() );
ml->setDiscoverNetworkEnabled( true );
ml->start();
ml->discover( argv[1] );
auto res = testCb->waitForCompletion();
return res == true ? 0 : 1;
}
<|endoftext|>
|
<commit_before>#include "widgets/chatwidget.hpp"
#include "channelmanager.hpp"
#include "colorscheme.hpp"
#include "notebookpage.hpp"
#include "settingsmanager.hpp"
#include "widgets/textinputdialog.hpp"
#include <QDebug>
#include <QFont>
#include <QFontDatabase>
#include <QPainter>
#include <QShortcut>
#include <QVBoxLayout>
#include <boost/signals2.hpp>
#include <functional>
using namespace chatterino::messages;
namespace chatterino {
namespace widgets {
namespace {
template <typename T>
inline void ezShortcut(ChatWidget *w, const char *key, T t)
{
auto s = new QShortcut(QKeySequence(key), w);
s->setContext(Qt::WidgetWithChildrenShortcut);
QObject::connect(s, &QShortcut::activated, w, t);
}
} // namespace
static int index = 0;
ChatWidget::ChatWidget(ChannelManager &_channelManager, NotebookPage *parent)
: BaseWidget(parent)
, channelManager(_channelManager)
, channel(_channelManager.getEmpty())
, vbox(this)
, header(this)
, view(this)
, input(this)
, channelName("/chatWidgets/" + std::to_string(index++) + "/channelName")
{
this->vbox.setSpacing(0);
this->vbox.setMargin(1);
this->vbox.addWidget(&this->header);
this->vbox.addWidget(&this->view, 1);
this->vbox.addWidget(&this->input);
// Initialize chat widget-wide hotkeys
// CTRL+T: Create new split (Add page)
ezShortcut(this, "CTRL+T", &ChatWidget::doAddSplit);
// CTRL+W: Close Split
ezShortcut(this, "CTRL+W", &ChatWidget::doCloseSplit);
// CTRL+R: Change Channel
ezShortcut(this, "CTRL+R", &ChatWidget::doChangeChannel);
this->channelName.getValueChangedSignal().connect(
std::bind(&ChatWidget::channelNameUpdated, this, std::placeholders::_1));
this->channelNameUpdated(this->channelName.getValue());
}
ChatWidget::~ChatWidget()
{
this->detachChannel();
}
std::shared_ptr<Channel> ChatWidget::getChannel() const
{
return this->channel;
}
std::shared_ptr<Channel> &ChatWidget::getChannelRef()
{
return this->channel;
}
void ChatWidget::setChannel(std::shared_ptr<Channel> _newChannel)
{
this->channel = _newChannel;
// on new message
this->messageAppendedConnection =
this->channel->messageAppended.connect([this](SharedMessage &message) {
SharedMessageRef deleted;
auto messageRef = new MessageRef(message);
if (this->messages.appendItem(SharedMessageRef(messageRef), deleted)) {
qreal value = std::max(0.0, this->view.getScrollBar().getDesiredValue() - 1);
this->view.getScrollBar().setDesiredValue(value, false);
}
});
// on message removed
this->messageRemovedConnection =
this->channel->messageRemovedFromStart.connect([](SharedMessage &) {
//
});
auto snapshot = this->channel->getMessageSnapshot();
for (int i = 0; i < snapshot.getLength(); i++) {
SharedMessageRef deleted;
auto messageRef = new MessageRef(snapshot[i]);
this->messages.appendItem(SharedMessageRef(messageRef), deleted);
}
}
void ChatWidget::detachChannel()
{
// on message added
this->messageAppendedConnection.disconnect();
// on message removed
this->messageRemovedConnection.disconnect();
}
void ChatWidget::channelNameUpdated(const std::string &newChannelName)
{
// remove current channel
if (!this->channel->isEmpty()) {
this->channelManager.removeChannel(this->channel->getName());
this->detachChannel();
}
// update messages
this->messages.clear();
if (newChannelName.empty()) {
this->channel = nullptr;
} else {
this->setChannel(this->channelManager.addChannel(QString::fromStdString(newChannelName)));
}
// update header
this->header.updateChannelText();
// update view
this->layoutMessages(true);
}
LimitedQueueSnapshot<SharedMessageRef> ChatWidget::getMessagesSnapshot()
{
return this->messages.getSnapshot();
}
void ChatWidget::showChangeChannelPopup()
{
// create new input dialog and execute it
TextInputDialog dialog(this);
dialog.setText(QString::fromStdString(this->channelName));
if (dialog.exec() == QDialog::Accepted) {
QString newChannelName = dialog.getText().trimmed();
this->channelName = newChannelName.toStdString();
}
}
void ChatWidget::layoutMessages(bool forceUpdate)
{
if (this->view.layoutMessages() || forceUpdate) {
this->view.update();
}
}
void ChatWidget::updateGifEmotes()
{
this->view.updateGifEmotes();
}
void ChatWidget::giveFocus()
{
this->input.textInput.setFocus();
}
void ChatWidget::paintEvent(QPaintEvent *)
{
// color the background of the chat
QPainter painter(this);
painter.fillRect(this->rect(), this->colorScheme.ChatBackground);
}
void ChatWidget::load(const boost::property_tree::ptree &tree)
{
// load tab text
try {
this->channelName = tree.get<std::string>("channelName");
} catch (boost::property_tree::ptree_error) {
}
}
boost::property_tree::ptree ChatWidget::save()
{
boost::property_tree::ptree tree;
tree.put("channelName", this->channelName.getValue());
return tree;
}
/// Slots
void ChatWidget::doAddSplit()
{
NotebookPage *page = static_cast<NotebookPage *>(this->parentWidget());
page->addChat(true);
}
void ChatWidget::doCloseSplit()
{
NotebookPage *page = static_cast<NotebookPage *>(this->parentWidget());
page->removeFromLayout(this);
}
void ChatWidget::doChangeChannel()
{
this->showChangeChannelPopup();
}
void ChatWidget::doPopup()
{
// TODO: Copy signals and stuff too
auto widget =
new ChatWidget(this->channelManager, static_cast<NotebookPage *>(this->parentWidget()));
widget->channelName = this->channelName;
widget->show();
}
void ChatWidget::doClearChat()
{
// Clear all stored messages in this chat widget
this->messages.clear();
// Layout chat widget messages, and force an update regardless if there are no messages
this->layoutMessages(true);
}
void ChatWidget::doOpenChannel()
{
qDebug() << "[UNIMPLEMENTED] Open twitch.tv/"
<< QString::fromStdString(this->channelName.getValue());
}
void ChatWidget::doOpenPopupPlayer()
{
qDebug() << "[UNIMPLEMENTED] Open twitch.tv/"
<< QString::fromStdString(this->channelName.getValue()) << "/popout";
}
} // namespace widgets
} // namespace chatterino
<commit_msg>Channel should never be a nullptr, set it to the "empty channel"<commit_after>#include "widgets/chatwidget.hpp"
#include "channelmanager.hpp"
#include "colorscheme.hpp"
#include "notebookpage.hpp"
#include "settingsmanager.hpp"
#include "widgets/textinputdialog.hpp"
#include <QDebug>
#include <QFont>
#include <QFontDatabase>
#include <QPainter>
#include <QShortcut>
#include <QVBoxLayout>
#include <boost/signals2.hpp>
#include <functional>
using namespace chatterino::messages;
namespace chatterino {
namespace widgets {
namespace {
template <typename T>
inline void ezShortcut(ChatWidget *w, const char *key, T t)
{
auto s = new QShortcut(QKeySequence(key), w);
s->setContext(Qt::WidgetWithChildrenShortcut);
QObject::connect(s, &QShortcut::activated, w, t);
}
} // namespace
static int index = 0;
ChatWidget::ChatWidget(ChannelManager &_channelManager, NotebookPage *parent)
: BaseWidget(parent)
, channelManager(_channelManager)
, channel(_channelManager.getEmpty())
, vbox(this)
, header(this)
, view(this)
, input(this)
, channelName("/chatWidgets/" + std::to_string(index++) + "/channelName")
{
this->vbox.setSpacing(0);
this->vbox.setMargin(1);
this->vbox.addWidget(&this->header);
this->vbox.addWidget(&this->view, 1);
this->vbox.addWidget(&this->input);
// Initialize chat widget-wide hotkeys
// CTRL+T: Create new split (Add page)
ezShortcut(this, "CTRL+T", &ChatWidget::doAddSplit);
// CTRL+W: Close Split
ezShortcut(this, "CTRL+W", &ChatWidget::doCloseSplit);
// CTRL+R: Change Channel
ezShortcut(this, "CTRL+R", &ChatWidget::doChangeChannel);
this->channelName.getValueChangedSignal().connect(
std::bind(&ChatWidget::channelNameUpdated, this, std::placeholders::_1));
this->channelNameUpdated(this->channelName.getValue());
}
ChatWidget::~ChatWidget()
{
this->detachChannel();
}
std::shared_ptr<Channel> ChatWidget::getChannel() const
{
return this->channel;
}
std::shared_ptr<Channel> &ChatWidget::getChannelRef()
{
return this->channel;
}
void ChatWidget::setChannel(std::shared_ptr<Channel> _newChannel)
{
this->channel = _newChannel;
// on new message
this->messageAppendedConnection =
this->channel->messageAppended.connect([this](SharedMessage &message) {
SharedMessageRef deleted;
auto messageRef = new MessageRef(message);
if (this->messages.appendItem(SharedMessageRef(messageRef), deleted)) {
qreal value = std::max(0.0, this->view.getScrollBar().getDesiredValue() - 1);
this->view.getScrollBar().setDesiredValue(value, false);
}
});
// on message removed
this->messageRemovedConnection =
this->channel->messageRemovedFromStart.connect([](SharedMessage &) {
//
});
auto snapshot = this->channel->getMessageSnapshot();
for (int i = 0; i < snapshot.getLength(); i++) {
SharedMessageRef deleted;
auto messageRef = new MessageRef(snapshot[i]);
this->messages.appendItem(SharedMessageRef(messageRef), deleted);
}
}
void ChatWidget::detachChannel()
{
// on message added
this->messageAppendedConnection.disconnect();
// on message removed
this->messageRemovedConnection.disconnect();
}
void ChatWidget::channelNameUpdated(const std::string &newChannelName)
{
// remove current channel
if (!this->channel->isEmpty()) {
this->channelManager.removeChannel(this->channel->getName());
this->detachChannel();
}
// update messages
this->messages.clear();
if (newChannelName.empty()) {
this->channel = this->channelManager.getEmpty();
} else {
this->setChannel(this->channelManager.addChannel(QString::fromStdString(newChannelName)));
}
// update header
this->header.updateChannelText();
// update view
this->layoutMessages(true);
}
LimitedQueueSnapshot<SharedMessageRef> ChatWidget::getMessagesSnapshot()
{
return this->messages.getSnapshot();
}
void ChatWidget::showChangeChannelPopup()
{
// create new input dialog and execute it
TextInputDialog dialog(this);
dialog.setText(QString::fromStdString(this->channelName));
if (dialog.exec() == QDialog::Accepted) {
QString newChannelName = dialog.getText().trimmed();
this->channelName = newChannelName.toStdString();
}
}
void ChatWidget::layoutMessages(bool forceUpdate)
{
if (this->view.layoutMessages() || forceUpdate) {
this->view.update();
}
}
void ChatWidget::updateGifEmotes()
{
this->view.updateGifEmotes();
}
void ChatWidget::giveFocus()
{
this->input.textInput.setFocus();
}
void ChatWidget::paintEvent(QPaintEvent *)
{
// color the background of the chat
QPainter painter(this);
painter.fillRect(this->rect(), this->colorScheme.ChatBackground);
}
void ChatWidget::load(const boost::property_tree::ptree &tree)
{
// load tab text
try {
this->channelName = tree.get<std::string>("channelName");
} catch (boost::property_tree::ptree_error) {
}
}
boost::property_tree::ptree ChatWidget::save()
{
boost::property_tree::ptree tree;
tree.put("channelName", this->channelName.getValue());
return tree;
}
/// Slots
void ChatWidget::doAddSplit()
{
NotebookPage *page = static_cast<NotebookPage *>(this->parentWidget());
page->addChat(true);
}
void ChatWidget::doCloseSplit()
{
NotebookPage *page = static_cast<NotebookPage *>(this->parentWidget());
page->removeFromLayout(this);
}
void ChatWidget::doChangeChannel()
{
this->showChangeChannelPopup();
}
void ChatWidget::doPopup()
{
// TODO: Copy signals and stuff too
auto widget =
new ChatWidget(this->channelManager, static_cast<NotebookPage *>(this->parentWidget()));
widget->channelName = this->channelName;
widget->show();
}
void ChatWidget::doClearChat()
{
// Clear all stored messages in this chat widget
this->messages.clear();
// Layout chat widget messages, and force an update regardless if there are no messages
this->layoutMessages(true);
}
void ChatWidget::doOpenChannel()
{
qDebug() << "[UNIMPLEMENTED] Open twitch.tv/"
<< QString::fromStdString(this->channelName.getValue());
}
void ChatWidget::doOpenPopupPlayer()
{
qDebug() << "[UNIMPLEMENTED] Open twitch.tv/"
<< QString::fromStdString(this->channelName.getValue()) << "/popout";
}
} // namespace widgets
} // namespace chatterino
<|endoftext|>
|
<commit_before>#include "test/fuzz/fuzz_runner.h"
#include "common/common/logger.h"
#include "common/common/thread.h"
#include "common/common/utility.h"
#include "common/event/libevent.h"
#include "test/test_common/environment.h"
namespace Envoy {
namespace Fuzz {
spdlog::level::level_enum Runner::log_level_;
PerTestEnvironment::PerTestEnvironment()
: test_tmpdir_([] {
const std::string fuzz_path = TestEnvironment::temporaryPath("fuzz_XXXXXX");
char test_tmpdir[fuzz_path.size() + 1];
StringUtil::strlcpy(test_tmpdir, fuzz_path.data(), fuzz_path.size() + 1);
RELEASE_ASSERT(::mkdtemp(test_tmpdir) != nullptr, "");
return std::string(test_tmpdir);
}()) {}
void Runner::setupEnvironment(int argc, char** argv, spdlog::level::level_enum default_log_level) {
Event::Libevent::Global::initialize();
TestEnvironment::initializeOptions(argc, argv);
static auto* lock = new Thread::MutexBasicLockable();
const auto environment_log_level = TestEnvironment::getOptions().logLevel();
// We only override the default log level if it looks like we're debugging;
// otherwise the default environment log level might override the default and
// spew too much when running under a fuzz engine.
log_level_ =
environment_log_level <= spdlog::level::debug ? environment_log_level : default_log_level;
Logger::Registry::initialize(log_level_, TestEnvironment::getOptions().logFormat(), *lock);
}
} // namespace Fuzz
} // namespace Envoy
extern "C" int LLVMFuzzerInitialize(int* /*argc*/, char*** argv) {
Envoy::Fuzz::Runner::setupEnvironment(1, *argv, spdlog::level::off);
return 0;
}
<commit_msg>fuzz: bump fuzzer log level to critical, to allow ASSERTs to be seen. (#4204)<commit_after>#include "test/fuzz/fuzz_runner.h"
#include "common/common/logger.h"
#include "common/common/thread.h"
#include "common/common/utility.h"
#include "common/event/libevent.h"
#include "test/test_common/environment.h"
namespace Envoy {
namespace Fuzz {
spdlog::level::level_enum Runner::log_level_;
PerTestEnvironment::PerTestEnvironment()
: test_tmpdir_([] {
const std::string fuzz_path = TestEnvironment::temporaryPath("fuzz_XXXXXX");
char test_tmpdir[fuzz_path.size() + 1];
StringUtil::strlcpy(test_tmpdir, fuzz_path.data(), fuzz_path.size() + 1);
RELEASE_ASSERT(::mkdtemp(test_tmpdir) != nullptr, "");
return std::string(test_tmpdir);
}()) {}
void Runner::setupEnvironment(int argc, char** argv, spdlog::level::level_enum default_log_level) {
Event::Libevent::Global::initialize();
TestEnvironment::initializeOptions(argc, argv);
static auto* lock = new Thread::MutexBasicLockable();
const auto environment_log_level = TestEnvironment::getOptions().logLevel();
// We only override the default log level if it looks like we're debugging;
// otherwise the default environment log level might override the default and
// spew too much when running under a fuzz engine.
log_level_ =
environment_log_level <= spdlog::level::debug ? environment_log_level : default_log_level;
Logger::Registry::initialize(log_level_, TestEnvironment::getOptions().logFormat(), *lock);
}
} // namespace Fuzz
} // namespace Envoy
extern "C" int LLVMFuzzerInitialize(int* /*argc*/, char*** argv) {
Envoy::Fuzz::Runner::setupEnvironment(1, *argv, spdlog::level::critical);
return 0;
}
<|endoftext|>
|
<commit_before>// @(#)root/test:$Id$
// Author: David Smith 20/10/14
/////////////////////////////////////////////////////////////////
//
//___A test for I/O plugins by reading files___
//
// The files used in this test have been generated by
// stress.cxx and preplaced on some data servers.
// stressIOPlugins reads the remote files via various data
// access protocols to test ROOT IO plugins. The data read are
// tested via tests based on some of stress.cxx tests.
//
// Can be run as:
// stressIOPlugins
// stressIOPlugins [name]
//
// The name parameter is a protocol name, as expected
// in a url. The supported names are: xroot, root, http, https
// If the name is omitted a selection of schemes are
// tested based on feature availability:
//
// feature protocol
//
// xrootd root
// davix http
//
// An example of output when all the tests run OK is shown below:
//
// ****************************************************************************
// * Starting stressIOPlugins test for protocol http
// * Test files will be read from:
// * http://root.cern.ch/files/StressIOPluginsTestFiles/
// ****************************************************************************
// Test 1 : Check size & compression factor of a Root file........ using stress_2.root
// : opened file with plugin class......................... TDavixFile
// : Check size & compression factor of a Root file........ OK
// Test 2 : Test graphics & Postscript............................ using stress_5.root
// : opened file with plugin class......................... TDavixFile
// : Test graphics & Postscript............................ OK
// Test 3 : Trees split and compression modes..................... using Event_8a.root
// : opened file with plugin class......................... TDavixFile
// : Trees split and compression modes..................... using Event_8b.root
// : opened file with plugin class......................... TDavixFile
// : Trees split and compression modes..................... OK
// ****************************************************************************
//_____________________________batch only_____________________
#ifndef __CINT__
#include <stdlib.h>
#include <TROOT.h>
#include <TSystem.h>
#include <TH1.h>
#include <TH2.h>
#include <TFile.h>
#include <TMath.h>
#include <TF1.h>
#include <TF2.h>
#include <TCanvas.h>
#include <TPostScript.h>
#include <TTree.h>
#include <TTreeCache.h>
#include <TSystem.h>
#include <TApplication.h>
#include <TClassTable.h>
#include <Compression.h>
#include "Event.h"
void stressIOPlugins();
void stressIOPluginsForProto(const char *protoName = 0);
void stressIOPlugins1();
void stressIOPlugins2();
void stressIOPlugins3();
void cleanup();
int main(int argc, char **argv)
{
gROOT->SetBatch();
TApplication theApp("App", &argc, argv);
const char *proto = 0;
if (argc > 1) proto = argv[1];
stressIOPluginsForProto(proto);
return 0;
}
#endif
class TH1;
class TTree;
#if defined(__CINT__) || defined(__CLING__)
struct ensureEventLoaded {
public:
ensureEventLoaded() {
// if needed load the Event shard library, making sure it exists
// This test dynamic linking when running in interpreted mode
if (!TClassTable::GetDict("Event")) {
Int_t st1 = -1;
if (gSystem->DynamicPathName("$ROOTSYS/test/libEvent",kTRUE)) {
st1 = gSystem->Load("$(ROOTSYS)/test/libEvent");
}
if (st1 == -1) {
if (gSystem->DynamicPathName("test/libEvent",kTRUE)) {
st1 = gSystem->Load("test/libEvent");
}
if (st1 == -1) {
printf("===>stress8 will try to build the libEvent library\n");
Bool_t UNIX = strcmp(gSystem->GetName(), "Unix") == 0;
if (UNIX) gSystem->Exec("(cd $ROOTSYS/test; make Event)");
else gSystem->Exec("(cd %ROOTSYS%\\test && nmake libEvent.dll)");
st1 = gSystem->Load("$(ROOTSYS)/test/libEvent");
}
}
}
}
~ensureEventLoaded() { }
} myStaticObject;
#endif
//_______________________ common part_________________________
Double_t ntotin=0, ntotout=0;
TString gPfx;
void Bprint(Int_t id, const char *title)
{
// Print test program number and its title
const Int_t kMAX = 65;
char header[80];
if (id > 0) {
snprintf(header,80,"Test %2d : %s",id,title);
} else {
snprintf(header,80," : %s",title);
}
Int_t nch = strlen(header);
for (Int_t i=nch;i<kMAX;i++) header[i] = '.';
header[kMAX] = 0;
header[kMAX-1] = ' ';
printf("%s",header);
}
TFile *openTestFile(const char *fn, const char *title) {
printf("using %s\n", fn);
TFile *f = TFile::Open(gPfx + fn);
Bprint(0,"opened file with plugin class");
if (!f) {
printf("FAILED\n");
Bprint(0, title);
return 0;
}
printf("%s\n", f->ClassName());
Bprint(0, title);
return f;
}
Bool_t isFeatureAvailable(const char *name) {
TString configfeatures = gROOT->GetConfigFeatures();
return configfeatures.Contains(name);
}
int setPath(const char *proto)
{
if (!proto) return -1;
TString p(proto);
if (p == "root" || p == "xroot") {
gPfx = p + "://eospublic.cern.ch//eos/opstest/dhsmith/StressIOPluginsTestFiles/";
return 0;
}
if (p == "http" || p == "https") {
gPfx = p + "://root.cern.ch/files/StressIOPluginsTestFiles/";
return 0;
}
return -1;
}
void stressIOPluginsForProto(const char *protoName /*=0*/)
{
//Main control function invoking all test programs
if (!protoName) {
if (isFeatureAvailable("xrootd")) {
stressIOPluginsForProto("root");
} else {
printf("* Skipping root protocol test because 'xrootd' feature not available\n");
}
if (isFeatureAvailable("davix")) {
stressIOPluginsForProto("http");
} else {
printf("* Skipping http protocol test because 'davix' feature not available\n");
}
return;
}
if (setPath(protoName)) {
printf("No server and path available to test protocol %s\n", protoName);
return;
}
printf("****************************************************************************\n");
printf("* Starting stressIOPlugins test for protocol %s\n", protoName);
printf("* Test files will be read from:\n");
printf("* %s\n", gPfx.Data());
printf("****************************************************************************\n");
stressIOPlugins1();
stressIOPlugins2();
stressIOPlugins3();
cleanup();
printf("****************************************************************************\n");
}
void stressIOPlugins()
{
stressIOPluginsForProto((const char*)0);
}
//_______________________________________________________________
void stressIOPlugins1()
{
//based on stress2()
//check length and compression factor in stress.root
const char *title = "Check size & compression factor of a Root file";
Bprint(1, title);
TFile *f = openTestFile("stress_2.root", title);
if (!f) {
printf("FAILED\n");
return;
}
Long64_t last = f->GetEND();
Float_t comp = f->GetCompressionFactor();
Bool_t OK = kTRUE;
Long64_t lastgood = 9428;
if (last <lastgood-200 || last > lastgood+200 || comp <2.0 || comp > 2.4) OK = kFALSE;
if (OK) printf("OK\n");
else {
printf("FAILED\n");
printf("%-8s last =%lld, comp=%f\n"," ",last,comp);
}
delete f;
}
//_______________________________________________________________
void stressIOPlugins2()
{
// based on stress5()
// Test of Postscript.
// Make a complex picture. Verify number of lines on ps file
// Testing automatically the graphics package is a complex problem.
// The best way we have found is to generate a Postscript image
// of a complex canvas containing many objects.
// The number of lines in the ps file is compared with a reference run.
// A few lines (up to 2 or 3) of difference may be expected because
// Postscript works with floats. The date and time of the run are also
// different.
// You can also inspect visually the ps file with a ps viewer.
const char *title = "Test graphics & Postscript";
Bprint(2,title);
TCanvas *c1 = new TCanvas("c1","stress canvas",800,600);
gROOT->LoadClass("TPostScript","Postscript");
TString psfname = TString::Format("stressIOPlugins-%d.ps", gSystem->GetPid());
TPostScript ps(psfname,112);
//Get objects generated in previous test
TFile *f = openTestFile("stress_5.root",title);
if (!f) {
printf("FAILED\n");
return;
}
TF1 *f1form = (TF1*)f->Get("f1form");
TF2 *f2form = (TF2*)f->Get("f2form");
TH1F *h1form = (TH1F*)f->Get("h1form");
TH2F *h2form = (TH2F*)f->Get("h2form");
//Divide the canvas in subpads. Plot with different options
c1->Divide(2,2);
c1->cd(1);
f1form->Draw();
c1->cd(2);
h1form->Draw();
c1->cd(3);
h2form->Draw("box");
f2form->Draw("cont1same");
c1->cd(4);
f2form->Draw("surf");
ps.Close();
//count number of lines in ps file
FILE *fp = fopen(psfname,"r");
if (!fp) {
printf("FAILED\n");
printf("%-8s could not open %s\n"," ",psfname.Data());
delete c1;
delete f;
return;
}
char line[260];
Int_t nlines = 0;
Int_t nlinesGood = 632;
while (fgets(line,255,fp)) {
nlines++;
}
fclose(fp);
ntotin += f->GetBytesRead();
ntotout += f->GetBytesWritten();
Bool_t OK = kTRUE;
if (nlines < nlinesGood-110 || nlines > nlinesGood+110) OK = kFALSE;
if (OK) printf("OK\n");
else {
printf("FAILED\n");
printf("%-8s nlines in %s file = %d\n"," ",psfname.Data(),nlines);
}
delete c1;
delete f;
}
//_______________________________________________________________
Int_t test3read(const TString &fn, const char *title)
{
// Read the event file
// Loop on all events in the file (reading everything).
// Count number of bytes read
Int_t nevent = 0;
TFile *hfile = openTestFile(fn,title);
if (!hfile) {
return 0;
}
TTree *tree; hfile->GetObject("T",tree);
Event *event = 0;
tree->SetBranchAddress("event",&event);
Int_t nentries = (Int_t)tree->GetEntries();
Int_t nev = TMath::Max(nevent,nentries);
//activate the treeCache
Int_t cachesize = 10000000; //this is the default value: 10 MBytes
tree->SetCacheSize(cachesize);
TTreeCache::SetLearnEntries(1); //one entry is sufficient to learn
TTreeCache *tc = (TTreeCache*)hfile->GetCacheRead();
tc->SetEntryRange(0,nevent);
Int_t nb = 0;
for (Int_t ev = 0; ev < nev; ev++) {
nb += tree->GetEntry(ev); //read complete event in memory
}
ntotin += hfile->GetBytesRead();
delete event;
delete hfile;
return nb;
}
//_______________________________________________________________
void stressIOPlugins3()
{
// based on stress8()
const char *title = "Trees split and compression modes";
Bprint(3,title);
Int_t nbr0 = test3read("Event_8a.root",title);
Event::Reset();
Int_t nbr1 = test3read("Event_8b.root",title);
Event::Reset();
Bool_t OK = kTRUE;
if (nbr0 == 0 || nbr0 != nbr1) OK = kFALSE;
if (OK) printf("OK\n");
else {
printf("FAILED\n");
printf("%-8s nbr0=%d, nbr1=%d\n"," ",nbr0,nbr1);
}
}
void cleanup()
{
TString psfname = TString::Format("stressIOPlugins-%d.ps", gSystem->GetPid());
gSystem->Unlink(psfname);
}
<commit_msg>Use new #pragma cling load for libEvent.<commit_after>// @(#)root/test:$Id$
// Author: David Smith 20/10/14
/////////////////////////////////////////////////////////////////
//
//___A test for I/O plugins by reading files___
//
// The files used in this test have been generated by
// stress.cxx and preplaced on some data servers.
// stressIOPlugins reads the remote files via various data
// access protocols to test ROOT IO plugins. The data read are
// tested via tests based on some of stress.cxx tests.
//
// Can be run as:
// stressIOPlugins
// stressIOPlugins [name]
//
// The name parameter is a protocol name, as expected
// in a url. The supported names are: xroot, root, http, https
// If the name is omitted a selection of schemes are
// tested based on feature availability:
//
// feature protocol
//
// xrootd root
// davix http
//
// An example of output when all the tests run OK is shown below:
//
// ****************************************************************************
// * Starting stressIOPlugins test for protocol http
// * Test files will be read from:
// * http://root.cern.ch/files/StressIOPluginsTestFiles/
// ****************************************************************************
// Test 1 : Check size & compression factor of a Root file........ using stress_2.root
// : opened file with plugin class......................... TDavixFile
// : Check size & compression factor of a Root file........ OK
// Test 2 : Test graphics & Postscript............................ using stress_5.root
// : opened file with plugin class......................... TDavixFile
// : Test graphics & Postscript............................ OK
// Test 3 : Trees split and compression modes..................... using Event_8a.root
// : opened file with plugin class......................... TDavixFile
// : Trees split and compression modes..................... using Event_8b.root
// : opened file with plugin class......................... TDavixFile
// : Trees split and compression modes..................... OK
// ****************************************************************************
//_____________________________batch only_____________________
#ifndef __CINT__
#include <stdlib.h>
#include <TROOT.h>
#include <TSystem.h>
#include <TH1.h>
#include <TH2.h>
#include <TFile.h>
#include <TMath.h>
#include <TF1.h>
#include <TF2.h>
#include <TCanvas.h>
#include <TPostScript.h>
#include <TTree.h>
#include <TTreeCache.h>
#include <TSystem.h>
#include <TApplication.h>
#include <TClassTable.h>
#include <Compression.h>
#include "Event.h"
R__LOAD_LIBRARY( libEvent )
void stressIOPlugins();
void stressIOPluginsForProto(const char *protoName = 0);
void stressIOPlugins1();
void stressIOPlugins2();
void stressIOPlugins3();
void cleanup();
int main(int argc, char **argv)
{
gROOT->SetBatch();
TApplication theApp("App", &argc, argv);
const char *proto = 0;
if (argc > 1) proto = argv[1];
stressIOPluginsForProto(proto);
return 0;
}
#endif
class TH1;
class TTree;
//_______________________ common part_________________________
Double_t ntotin=0, ntotout=0;
TString gPfx;
void Bprint(Int_t id, const char *title)
{
// Print test program number and its title
const Int_t kMAX = 65;
char header[80];
if (id > 0) {
snprintf(header,80,"Test %2d : %s",id,title);
} else {
snprintf(header,80," : %s",title);
}
Int_t nch = strlen(header);
for (Int_t i=nch;i<kMAX;i++) header[i] = '.';
header[kMAX] = 0;
header[kMAX-1] = ' ';
printf("%s",header);
}
TFile *openTestFile(const char *fn, const char *title) {
printf("using %s\n", fn);
TFile *f = TFile::Open(gPfx + fn);
Bprint(0,"opened file with plugin class");
if (!f) {
printf("FAILED\n");
Bprint(0, title);
return 0;
}
printf("%s\n", f->ClassName());
Bprint(0, title);
return f;
}
Bool_t isFeatureAvailable(const char *name) {
TString configfeatures = gROOT->GetConfigFeatures();
return configfeatures.Contains(name);
}
int setPath(const char *proto)
{
if (!proto) return -1;
TString p(proto);
if (p == "root" || p == "xroot") {
gPfx = p + "://eospublic.cern.ch//eos/opstest/dhsmith/StressIOPluginsTestFiles/";
return 0;
}
if (p == "http" || p == "https") {
gPfx = p + "://root.cern.ch/files/StressIOPluginsTestFiles/";
return 0;
}
return -1;
}
void stressIOPluginsForProto(const char *protoName /*=0*/)
{
//Main control function invoking all test programs
if (!protoName) {
if (isFeatureAvailable("xrootd")) {
stressIOPluginsForProto("root");
} else {
printf("* Skipping root protocol test because 'xrootd' feature not available\n");
}
if (isFeatureAvailable("davix")) {
stressIOPluginsForProto("http");
} else {
printf("* Skipping http protocol test because 'davix' feature not available\n");
}
return;
}
if (setPath(protoName)) {
printf("No server and path available to test protocol %s\n", protoName);
return;
}
printf("****************************************************************************\n");
printf("* Starting stressIOPlugins test for protocol %s\n", protoName);
printf("* Test files will be read from:\n");
printf("* %s\n", gPfx.Data());
printf("****************************************************************************\n");
stressIOPlugins1();
stressIOPlugins2();
stressIOPlugins3();
cleanup();
printf("****************************************************************************\n");
}
void stressIOPlugins()
{
stressIOPluginsForProto((const char*)0);
}
//_______________________________________________________________
void stressIOPlugins1()
{
//based on stress2()
//check length and compression factor in stress.root
const char *title = "Check size & compression factor of a Root file";
Bprint(1, title);
TFile *f = openTestFile("stress_2.root", title);
if (!f) {
printf("FAILED\n");
return;
}
Long64_t last = f->GetEND();
Float_t comp = f->GetCompressionFactor();
Bool_t OK = kTRUE;
Long64_t lastgood = 9428;
if (last <lastgood-200 || last > lastgood+200 || comp <2.0 || comp > 2.4) OK = kFALSE;
if (OK) printf("OK\n");
else {
printf("FAILED\n");
printf("%-8s last =%lld, comp=%f\n"," ",last,comp);
}
delete f;
}
//_______________________________________________________________
void stressIOPlugins2()
{
// based on stress5()
// Test of Postscript.
// Make a complex picture. Verify number of lines on ps file
// Testing automatically the graphics package is a complex problem.
// The best way we have found is to generate a Postscript image
// of a complex canvas containing many objects.
// The number of lines in the ps file is compared with a reference run.
// A few lines (up to 2 or 3) of difference may be expected because
// Postscript works with floats. The date and time of the run are also
// different.
// You can also inspect visually the ps file with a ps viewer.
const char *title = "Test graphics & Postscript";
Bprint(2,title);
TCanvas *c1 = new TCanvas("c1","stress canvas",800,600);
gROOT->LoadClass("TPostScript","Postscript");
TString psfname = TString::Format("stressIOPlugins-%d.ps", gSystem->GetPid());
TPostScript ps(psfname,112);
//Get objects generated in previous test
TFile *f = openTestFile("stress_5.root",title);
if (!f) {
printf("FAILED\n");
return;
}
TF1 *f1form = (TF1*)f->Get("f1form");
TF2 *f2form = (TF2*)f->Get("f2form");
TH1F *h1form = (TH1F*)f->Get("h1form");
TH2F *h2form = (TH2F*)f->Get("h2form");
//Divide the canvas in subpads. Plot with different options
c1->Divide(2,2);
c1->cd(1);
f1form->Draw();
c1->cd(2);
h1form->Draw();
c1->cd(3);
h2form->Draw("box");
f2form->Draw("cont1same");
c1->cd(4);
f2form->Draw("surf");
ps.Close();
//count number of lines in ps file
FILE *fp = fopen(psfname,"r");
if (!fp) {
printf("FAILED\n");
printf("%-8s could not open %s\n"," ",psfname.Data());
delete c1;
delete f;
return;
}
char line[260];
Int_t nlines = 0;
Int_t nlinesGood = 632;
while (fgets(line,255,fp)) {
nlines++;
}
fclose(fp);
ntotin += f->GetBytesRead();
ntotout += f->GetBytesWritten();
Bool_t OK = kTRUE;
if (nlines < nlinesGood-110 || nlines > nlinesGood+110) OK = kFALSE;
if (OK) printf("OK\n");
else {
printf("FAILED\n");
printf("%-8s nlines in %s file = %d\n"," ",psfname.Data(),nlines);
}
delete c1;
delete f;
}
//_______________________________________________________________
Int_t test3read(const TString &fn, const char *title)
{
// Read the event file
// Loop on all events in the file (reading everything).
// Count number of bytes read
Int_t nevent = 0;
TFile *hfile = openTestFile(fn,title);
if (!hfile) {
return 0;
}
TTree *tree; hfile->GetObject("T",tree);
Event *event = 0;
tree->SetBranchAddress("event",&event);
Int_t nentries = (Int_t)tree->GetEntries();
Int_t nev = TMath::Max(nevent,nentries);
//activate the treeCache
Int_t cachesize = 10000000; //this is the default value: 10 MBytes
tree->SetCacheSize(cachesize);
TTreeCache::SetLearnEntries(1); //one entry is sufficient to learn
TTreeCache *tc = (TTreeCache*)hfile->GetCacheRead();
tc->SetEntryRange(0,nevent);
Int_t nb = 0;
for (Int_t ev = 0; ev < nev; ev++) {
nb += tree->GetEntry(ev); //read complete event in memory
}
ntotin += hfile->GetBytesRead();
delete event;
delete hfile;
return nb;
}
//_______________________________________________________________
void stressIOPlugins3()
{
// based on stress8()
const char *title = "Trees split and compression modes";
Bprint(3,title);
Int_t nbr0 = test3read("Event_8a.root",title);
Event::Reset();
Int_t nbr1 = test3read("Event_8b.root",title);
Event::Reset();
Bool_t OK = kTRUE;
if (nbr0 == 0 || nbr0 != nbr1) OK = kFALSE;
if (OK) printf("OK\n");
else {
printf("FAILED\n");
printf("%-8s nbr0=%d, nbr1=%d\n"," ",nbr0,nbr1);
}
}
void cleanup()
{
TString psfname = TString::Format("stressIOPlugins-%d.ps", gSystem->GetPid());
gSystem->Unlink(psfname);
}
<|endoftext|>
|
<commit_before>// Filename: pgButton.cxx
// Created by: drose (13Mar02)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001 - 2004, Disney Enterprises, Inc. All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license. You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://etc.cmu.edu/panda3d/docs/license/ .
//
// To contact the maintainers of this program write to
// panda3d-general@lists.sourceforge.net .
//
////////////////////////////////////////////////////////////////////
#include "pgButton.h"
#include "pgMouseWatcherParameter.h"
#include "throw_event.h"
#include "mouseButton.h"
#include "mouseWatcherParameter.h"
#include "colorAttrib.h"
#include "transformState.h"
TypeHandle PGButton::_type_handle;
////////////////////////////////////////////////////////////////////
// Function: PGButton::Constructor
// Access: Published
// Description:
////////////////////////////////////////////////////////////////////
PGButton::
PGButton(const string &name) : PGItem(name)
{
_button_down = false;
_click_buttons.insert(MouseButton::one());
set_active(true);
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::Destructor
// Access: Public, Virtual
// Description:
////////////////////////////////////////////////////////////////////
PGButton::
~PGButton() {
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::Copy Constructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
PGButton::
PGButton(const PGButton ©) :
PGItem(copy)
{
_button_down = false;
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::make_copy
// Access: Public, Virtual
// Description: Returns a newly-allocated Node that is a shallow copy
// of this one. It will be a different Node pointer,
// but its internal data may or may not be shared with
// that of the original Node.
////////////////////////////////////////////////////////////////////
PandaNode *PGButton::
make_copy() const {
return new PGButton(*this);
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::enter
// Access: Public, Virtual
// Description: This is a callback hook function, called whenever the
// mouse enters the region.
////////////////////////////////////////////////////////////////////
void PGButton::
enter(const MouseWatcherParameter ¶m) {
if (get_active()) {
set_state(_button_down ? S_depressed : S_rollover);
}
PGItem::enter(param);
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::exit
// Access: Public, Virtual
// Description: This is a callback hook function, called whenever the
// mouse exits the region.
////////////////////////////////////////////////////////////////////
void PGButton::
exit(const MouseWatcherParameter ¶m) {
if (get_active()) {
set_state(S_ready);
}
PGItem::exit(param);
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::press
// Access: Public, Virtual
// Description: This is a callback hook function, called whenever a
// mouse or keyboard button is depressed while the mouse
// is within the region.
////////////////////////////////////////////////////////////////////
void PGButton::
press(const MouseWatcherParameter ¶m, bool background) {
if (has_click_button(param.get_button())) {
if (get_active()) {
_button_down = true;
set_state(S_depressed);
}
}
PGItem::press(param, background);
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::release
// Access: Public, Virtual
// Description: This is a callback hook function, called whenever a
// mouse or keyboard button previously depressed with
// press() is released.
////////////////////////////////////////////////////////////////////
void PGButton::
release(const MouseWatcherParameter ¶m, bool background) {
if (has_click_button(param.get_button())) {
_button_down = false;
if (get_active()) {
if (param.is_outside()) {
set_state(S_ready);
} else {
set_state(S_rollover);
click(param);
}
}
}
PGItem::release(param, background);
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::click
// Access: Public, Virtual
// Description: This is a callback hook function, called whenever the
// button is clicked down-and-up by the user normally.
////////////////////////////////////////////////////////////////////
void PGButton::
click(const MouseWatcherParameter ¶m) {
PGMouseWatcherParameter *ep = new PGMouseWatcherParameter(param);
string event = get_click_event(param.get_button());
play_sound(event);
throw_event(event, EventParameter(ep));
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::move
// Access: Public, Virtual
// Description: This is a callback hook function, called whenever a
// mouse is moved while the mouse
// is within the region.
////////////////////////////////////////////////////////////////////
void PGButton::
move(const MouseWatcherParameter ¶m) {
PGItem::move(param);
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::setup
// Access: Published
// Description: Sets up the button as a default text button using the
// indicated label string. The TextNode defined by
// PGItem::get_text_node() will be used to create the
// label geometry. This automatically sets up the frame
// according to the size of the text.
////////////////////////////////////////////////////////////////////
void PGButton::
setup(const string &label) {
clear_state_def(S_ready);
clear_state_def(S_depressed);
clear_state_def(S_rollover);
clear_state_def(S_inactive);
TextNode *text_node = get_text_node();
text_node->set_text(label);
PT(PandaNode) geom = text_node->generate();
LVecBase4f frame = text_node->get_card_actual();
set_frame(frame[0] - 0.4f, frame[1] + 0.4f, frame[2] - 0.15f, frame[3] + 0.15f);
PT(PandaNode) ready = new PandaNode("ready");
PT(PandaNode) depressed = new PandaNode("depressed");
PT(PandaNode) rollover = new PandaNode("rollover");
PT(PandaNode) inactive = new PandaNode("inactive");
get_state_def(S_ready).attach_new_node(ready);
get_state_def(S_depressed).attach_new_node(depressed);
get_state_def(S_rollover).attach_new_node(rollover);
get_state_def(S_inactive).attach_new_node(inactive);
ready->add_child(geom);
depressed->add_child(geom);
rollover->add_child(geom);
inactive->add_child(geom);
PGFrameStyle style;
style.set_color(0.8f, 0.8f, 0.8f, 1.0f);
style.set_width(0.1f, 0.1f);
style.set_type(PGFrameStyle::T_bevel_out);
set_frame_style(S_ready, style);
style.set_color(0.9f, 0.9f, 0.9f, 1.0f);
set_frame_style(S_rollover, style);
inactive->set_attrib(ColorAttrib::make_flat(Colorf(0.8f, 0.8f, 0.8f, 1.0f)));
style.set_color(0.6f, 0.6f, 0.6f, 1.0f);
set_frame_style(S_inactive, style);
style.set_type(PGFrameStyle::T_bevel_in);
style.set_color(0.8f, 0.8f, 0.8f, 1.0f);
set_frame_style(S_depressed, style);
depressed->set_transform(TransformState::make_pos(LVector3f(0.05f, 0.0f, -0.05f)));
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::setup
// Access: Published
// Description: Sets up the button using the indicated NodePath as
// arbitrary geometry.
////////////////////////////////////////////////////////////////////
void PGButton::
setup(const NodePath &ready, const NodePath &depressed,
const NodePath &rollover, const NodePath &inactive) {
clear_state_def(S_ready);
clear_state_def(S_depressed);
clear_state_def(S_rollover);
clear_state_def(S_inactive);
instance_to_state_def(S_ready, ready);
instance_to_state_def(S_depressed, depressed);
instance_to_state_def(S_rollover, rollover);
instance_to_state_def(S_inactive, inactive);
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::set_active
// Access: Published, Virtual
// Description: Toggles the active/inactive state of the button. In
// the case of a PGButton, this also changes its visual
// appearance.
////////////////////////////////////////////////////////////////////
void PGButton::
set_active(bool active) {
if (active != get_active()) {
PGItem::set_active(active);
set_state(active ? S_ready : S_inactive);
}
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::add_click_button
// Access: Published
// Description: Adds the indicated button to the set of buttons that
// can effectively "click" the PGButton. Normally, this
// is just MouseButton::one(). Returns true if the
// button was added, or false if it was already there.
////////////////////////////////////////////////////////////////////
bool PGButton::
add_click_button(const ButtonHandle &button) {
return _click_buttons.insert(button).second;
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::remove_click_button
// Access: Published
// Description: Removes the indicated button from the set of buttons
// that can effectively "click" the PGButton. Normally,
// this is just MouseButton::one(). Returns true if the
// button was removed, or false if it was not in the
// set.
////////////////////////////////////////////////////////////////////
bool PGButton::
remove_click_button(const ButtonHandle &button) {
return (_click_buttons.erase(button) != 0);
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::has_click_button
// Access: Published
// Description: Returns true if the indicated button is on the set of
// buttons that can effectively "click" the PGButton.
// Normally, this is just MouseButton::one().
////////////////////////////////////////////////////////////////////
bool PGButton::
has_click_button(const ButtonHandle &button) {
return (_click_buttons.count(button) != 0);
}
<commit_msg>fix setup() to not hide label<commit_after>// Filename: pgButton.cxx
// Created by: drose (13Mar02)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001 - 2004, Disney Enterprises, Inc. All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license. You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://etc.cmu.edu/panda3d/docs/license/ .
//
// To contact the maintainers of this program write to
// panda3d-general@lists.sourceforge.net .
//
////////////////////////////////////////////////////////////////////
#include "pgButton.h"
#include "pgMouseWatcherParameter.h"
#include "throw_event.h"
#include "mouseButton.h"
#include "mouseWatcherParameter.h"
#include "colorAttrib.h"
#include "transformState.h"
TypeHandle PGButton::_type_handle;
////////////////////////////////////////////////////////////////////
// Function: PGButton::Constructor
// Access: Published
// Description:
////////////////////////////////////////////////////////////////////
PGButton::
PGButton(const string &name) : PGItem(name)
{
_button_down = false;
_click_buttons.insert(MouseButton::one());
set_active(true);
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::Destructor
// Access: Public, Virtual
// Description:
////////////////////////////////////////////////////////////////////
PGButton::
~PGButton() {
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::Copy Constructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
PGButton::
PGButton(const PGButton ©) :
PGItem(copy)
{
_button_down = false;
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::make_copy
// Access: Public, Virtual
// Description: Returns a newly-allocated Node that is a shallow copy
// of this one. It will be a different Node pointer,
// but its internal data may or may not be shared with
// that of the original Node.
////////////////////////////////////////////////////////////////////
PandaNode *PGButton::
make_copy() const {
return new PGButton(*this);
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::enter
// Access: Public, Virtual
// Description: This is a callback hook function, called whenever the
// mouse enters the region.
////////////////////////////////////////////////////////////////////
void PGButton::
enter(const MouseWatcherParameter ¶m) {
if (get_active()) {
set_state(_button_down ? S_depressed : S_rollover);
}
PGItem::enter(param);
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::exit
// Access: Public, Virtual
// Description: This is a callback hook function, called whenever the
// mouse exits the region.
////////////////////////////////////////////////////////////////////
void PGButton::
exit(const MouseWatcherParameter ¶m) {
if (get_active()) {
set_state(S_ready);
}
PGItem::exit(param);
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::press
// Access: Public, Virtual
// Description: This is a callback hook function, called whenever a
// mouse or keyboard button is depressed while the mouse
// is within the region.
////////////////////////////////////////////////////////////////////
void PGButton::
press(const MouseWatcherParameter ¶m, bool background) {
if (has_click_button(param.get_button())) {
if (get_active()) {
_button_down = true;
set_state(S_depressed);
}
}
PGItem::press(param, background);
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::release
// Access: Public, Virtual
// Description: This is a callback hook function, called whenever a
// mouse or keyboard button previously depressed with
// press() is released.
////////////////////////////////////////////////////////////////////
void PGButton::
release(const MouseWatcherParameter ¶m, bool background) {
if (has_click_button(param.get_button())) {
_button_down = false;
if (get_active()) {
if (param.is_outside()) {
set_state(S_ready);
} else {
set_state(S_rollover);
click(param);
}
}
}
PGItem::release(param, background);
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::click
// Access: Public, Virtual
// Description: This is a callback hook function, called whenever the
// button is clicked down-and-up by the user normally.
////////////////////////////////////////////////////////////////////
void PGButton::
click(const MouseWatcherParameter ¶m) {
PGMouseWatcherParameter *ep = new PGMouseWatcherParameter(param);
string event = get_click_event(param.get_button());
play_sound(event);
throw_event(event, EventParameter(ep));
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::move
// Access: Public, Virtual
// Description: This is a callback hook function, called whenever a
// mouse is moved while the mouse
// is within the region.
////////////////////////////////////////////////////////////////////
void PGButton::
move(const MouseWatcherParameter ¶m) {
PGItem::move(param);
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::setup
// Access: Published
// Description: Sets up the button as a default text button using the
// indicated label string. The TextNode defined by
// PGItem::get_text_node() will be used to create the
// label geometry. This automatically sets up the frame
// according to the size of the text.
////////////////////////////////////////////////////////////////////
void PGButton::
setup(const string &label) {
clear_state_def(S_ready);
clear_state_def(S_depressed);
clear_state_def(S_rollover);
clear_state_def(S_inactive);
TextNode *text_node = get_text_node();
text_node->set_text(label);
PT(PandaNode) geom = text_node->generate();
LVecBase4f frame = text_node->get_card_actual();
set_frame(frame[0] - 0.4f, frame[1] + 0.4f, frame[2] - 0.15f, frame[3] + 0.15f);
PT(PandaNode) ready = new PandaNode("ready");
PT(PandaNode) depressed = new PandaNode("depressed");
PT(PandaNode) rollover = new PandaNode("rollover");
PT(PandaNode) inactive = new PandaNode("inactive");
PGFrameStyle style;
style.set_color(0.8f, 0.8f, 0.8f, 1.0f);
style.set_width(0.1f, 0.1f);
style.set_type(PGFrameStyle::T_bevel_out);
set_frame_style(S_ready, style);
style.set_color(0.9f, 0.9f, 0.9f, 1.0f);
set_frame_style(S_rollover, style);
inactive->set_attrib(ColorAttrib::make_flat(Colorf(0.8f, 0.8f, 0.8f, 1.0f)));
style.set_color(0.6f, 0.6f, 0.6f, 1.0f);
set_frame_style(S_inactive, style);
style.set_type(PGFrameStyle::T_bevel_in);
style.set_color(0.8f, 0.8f, 0.8f, 1.0f);
set_frame_style(S_depressed, style);
depressed->set_transform(TransformState::make_pos(LVector3f(0.05f, 0.0f, -0.05f)));
get_state_def(S_ready).attach_new_node(ready);
get_state_def(S_depressed).attach_new_node(depressed);
get_state_def(S_rollover).attach_new_node(rollover);
get_state_def(S_inactive).attach_new_node(inactive);
ready->add_child(geom);
depressed->add_child(geom);
rollover->add_child(geom);
inactive->add_child(geom);
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::setup
// Access: Published
// Description: Sets up the button using the indicated NodePath as
// arbitrary geometry.
////////////////////////////////////////////////////////////////////
void PGButton::
setup(const NodePath &ready, const NodePath &depressed,
const NodePath &rollover, const NodePath &inactive) {
clear_state_def(S_ready);
clear_state_def(S_depressed);
clear_state_def(S_rollover);
clear_state_def(S_inactive);
instance_to_state_def(S_ready, ready);
instance_to_state_def(S_depressed, depressed);
instance_to_state_def(S_rollover, rollover);
instance_to_state_def(S_inactive, inactive);
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::set_active
// Access: Published, Virtual
// Description: Toggles the active/inactive state of the button. In
// the case of a PGButton, this also changes its visual
// appearance.
////////////////////////////////////////////////////////////////////
void PGButton::
set_active(bool active) {
if (active != get_active()) {
PGItem::set_active(active);
set_state(active ? S_ready : S_inactive);
}
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::add_click_button
// Access: Published
// Description: Adds the indicated button to the set of buttons that
// can effectively "click" the PGButton. Normally, this
// is just MouseButton::one(). Returns true if the
// button was added, or false if it was already there.
////////////////////////////////////////////////////////////////////
bool PGButton::
add_click_button(const ButtonHandle &button) {
return _click_buttons.insert(button).second;
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::remove_click_button
// Access: Published
// Description: Removes the indicated button from the set of buttons
// that can effectively "click" the PGButton. Normally,
// this is just MouseButton::one(). Returns true if the
// button was removed, or false if it was not in the
// set.
////////////////////////////////////////////////////////////////////
bool PGButton::
remove_click_button(const ButtonHandle &button) {
return (_click_buttons.erase(button) != 0);
}
////////////////////////////////////////////////////////////////////
// Function: PGButton::has_click_button
// Access: Published
// Description: Returns true if the indicated button is on the set of
// buttons that can effectively "click" the PGButton.
// Normally, this is just MouseButton::one().
////////////////////////////////////////////////////////////////////
bool PGButton::
has_click_button(const ButtonHandle &button) {
return (_click_buttons.count(button) != 0);
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
#include <list>
#include <cstddef>
#include <sstream>
#include <algorithm>
#include <tuple>
#include <cassert>
const size_t B=2;
class cascading{
struct item{
bool is_init;
int value;
item(){
is_init=false;
value=0;
}
item(int v){
is_init=true;
value=v;
}
std::string to_string()const{
std::stringstream ss;
ss<<value;
return ss.str();
}
bool operator<(const item&other){
if(is_init && !other.is_init){
return true;
}
return value<other.value;
}
};
struct level{
std::vector<item> values;
size_t pos;
size_t size;
size_t lvl;
level()=default;
level(size_t _size,size_t lvl_num){
pos=0;
size=_size;
values.resize(size);
lvl=lvl_num;
}
void clear(){
for(size_t i=0;i<values.size();i++){
values[i]=item();
}
pos=0;
}
bool free(){
return (size-pos)!=0;
}
bool is_full(){
return !free();
}
std::string to_string()const{
std::stringstream ss;
ss<<lvl<<": [";
for(size_t j=0;j<size;++j){
ss<<values[j].to_string()<<" ";
}
ss<<"]";
return ss.str();
}
void insert(item val){
if(pos<size){
values[pos]=val;
pos++;
}
}
void insert(std::vector<item> new_values){
assert(new_values.size()==size);
for(;pos<size;pos++){
values[pos]=new_values[pos];
}
}
void insert(std::vector<item> &a,std::vector<item> &b){
assert(a.size()==b.size());
assert((a.size()+b.size())==size);
size_t aPos,bPos;
aPos=bPos=0;
for(pos=0;pos<size;++pos){
if(a[aPos]<b[bPos]){
values[pos]=a[aPos];
aPos++;
}else{
values[pos]=b[bPos];
bPos++;
}
}
}
};
public:
cascading():_memory(B,0){
}
void push(int v){
if(_memory.pos<B){
_memory.insert(item(v));
}else{
std::sort(_memory.values.begin(),_memory.values.end());
if(_levels.empty()){
_levels.push_back(level(_memory.size,1));
}
if(_levels[0].free()){
_levels[0].insert(_memory.values);
_memory.clear();
}else{
_levels.push_back(level(B*_levels.back().size,_levels.size()+1));
for(size_t i=_levels.size()-1;;--i){
auto prev=&_levels[i-1];
auto pprev= (i==1)? &_memory: &_levels[i-1];
_levels[i].insert(pprev->values,prev->values);
if(i==1){
break;
}
}
_levels[0].insert(_memory.values);
_memory.clear();
}
_memory.insert(item(v));
}
}
void print(){
std::cout<<"mem:\n "<<_memory.to_string()<<std::endl;
std::cout<<"ext:\n";
for(size_t i=0;i<_levels.size();++i){
std::cout<<_levels[i].to_string()<<"\n";
}
std::cout<<"\n";
}
protected:
level _memory;
std::vector<level> _levels;
};
int main(){
cascading c;
c.push(3);
c.push(1);
c.print();
c.push(2);
c.push(4);
c.print();
c.push(7);
c.push(11);
c.print();
c.push(5);
c.print();
}
<commit_msg>const.<commit_after>#include <iostream>
#include <vector>
#include <list>
#include <cstddef>
#include <sstream>
#include <algorithm>
#include <tuple>
#include <cassert>
const size_t B=2;
class cascading{
struct item{
bool is_init;
int value;
item(){
is_init=false;
value=0;
}
item(int v){
is_init=true;
value=v;
}
std::string to_string()const{
std::stringstream ss;
ss<<value;
return ss.str();
}
bool operator<(const item&other)const{
if(is_init && !other.is_init){
return true;
}
return value<other.value;
}
};
struct level{
std::vector<item> values;
size_t pos;
size_t size;
size_t lvl;
level()=default;
level(size_t _size,size_t lvl_num){
pos=0;
size=_size;
values.resize(size);
lvl=lvl_num;
}
void clear(){
for(size_t i=0;i<values.size();i++){
values[i]=item();
}
pos=0;
}
bool free(){
return (size-pos)!=0;
}
bool is_full(){
return !free();
}
std::string to_string()const{
std::stringstream ss;
ss<<lvl<<": [";
for(size_t j=0;j<size;++j){
ss<<values[j].to_string()<<" ";
}
ss<<"]";
return ss.str();
}
void insert(item val){
if(pos<size){
values[pos]=val;
pos++;
}
}
void insert(std::vector<item> new_values){
assert(new_values.size()==size);
for(;pos<size;pos++){
values[pos]=new_values[pos];
}
}
void insert(std::vector<item> &a,std::vector<item> &b){
assert(a.size()==b.size());
assert((a.size()+b.size())==size);
size_t aPos,bPos;
aPos=bPos=0;
for(pos=0;pos<size;++pos){
if(a[aPos]<b[bPos]){
values[pos]=a[aPos];
aPos++;
}else{
values[pos]=b[bPos];
bPos++;
}
}
}
};
public:
cascading():_memory(B,0){
}
void push(int v){
if(_memory.pos<B){
_memory.insert(item(v));
}else{
std::sort(_memory.values.begin(),_memory.values.end());
if(_levels.empty()){
_levels.push_back(level(_memory.size,1));
}
if(_levels[0].free()){
_levels[0].insert(_memory.values);
_memory.clear();
}else{
_levels.push_back(level(B*_levels.back().size,_levels.size()+1));
for(size_t i=_levels.size()-1;;--i){
auto prev=&_levels[i-1];
auto pprev= (i==1)? &_memory: &_levels[i-1];
_levels[i].insert(pprev->values,prev->values);
if(i==1){
break;
}
}
_levels[0].insert(_memory.values);
_memory.clear();
}
_memory.insert(item(v));
}
}
void print(){
std::cout<<"mem:\n "<<_memory.to_string()<<std::endl;
std::cout<<"ext:\n";
for(size_t i=0;i<_levels.size();++i){
std::cout<<_levels[i].to_string()<<"\n";
}
std::cout<<"\n";
}
protected:
level _memory;
std::vector<level> _levels;
};
int main(){
cascading c;
c.push(3);
c.push(1);
c.print();
c.push(2);
c.push(4);
c.print();
c.push(7);
c.push(11);
c.print();
c.push(5);
c.print();
}
<|endoftext|>
|
<commit_before>#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include "managed.h"
#include "glib.h"
#include "float.h"
TEST_CASE("Types.C", "[C][Types]") {
BuiltinTypes* bt = BuiltinTypes_new();
BuiltinTypes_ReturnsVoid(bt);
REQUIRE(BuiltinTypes_ReturnsBool(bt) == true);
REQUIRE(BuiltinTypes_ReturnsSByte(bt) == -5);
REQUIRE(BuiltinTypes_ReturnsByte(bt) == 5);
REQUIRE(BuiltinTypes_ReturnsShort(bt) == -5);
REQUIRE(BuiltinTypes_ReturnsUShort(bt) == 5);
REQUIRE(BuiltinTypes_ReturnsInt(bt) == -5);
REQUIRE(BuiltinTypes_ReturnsUInt(bt) == 5);
REQUIRE(BuiltinTypes_ReturnsLong(bt) == -5);
REQUIRE(BuiltinTypes_ReturnsULong(bt) == 5);
REQUIRE(BuiltinTypes_ReturnsChar(bt) == 'a');
REQUIRE(strcmp(BuiltinTypes_ReturnsString(bt), "Mono") == 0);
REQUIRE(BuiltinTypes_PassAndReturnsBool(bt, true) == true);
REQUIRE(BuiltinTypes_PassAndReturnsSByte(bt, -5) == -5);
REQUIRE(BuiltinTypes_PassAndReturnsByte(bt, 5) == 5);
REQUIRE(BuiltinTypes_PassAndReturnsShort(bt, -5) == -5);
REQUIRE(BuiltinTypes_PassAndReturnsUShort(bt, 5) == 5);
REQUIRE(BuiltinTypes_PassAndReturnsInt(bt, -5) == -5);
REQUIRE(BuiltinTypes_PassAndReturnsUInt(bt, 5) == 5);
REQUIRE(BuiltinTypes_PassAndReturnsLong(bt, -5) == -5);
REQUIRE(BuiltinTypes_PassAndReturnsULong(bt, 5) == 5);
REQUIRE(BuiltinTypes_PassAndReturnsChar(bt, 'a') == 'a');
REQUIRE(strcmp(BuiltinTypes_PassAndReturnsString(bt, "Mono"), "Mono") == 0);
int OutInt = 0;
BuiltinTypes_PassOutInt(bt, &OutInt);
REQUIRE(OutInt == 5);
int RefInt = 0;
BuiltinTypes_PassRefInt(bt, &RefInt);
REQUIRE(RefInt == 10);
GString* RefOut = g_string_new("");
BuiltinTypes_PassOutString(bt, RefOut);
REQUIRE(strcmp(RefOut->str, "Mono") == 0);
GString* RefStr = g_string_new("monomono");
BuiltinTypes_PassRefString(bt, RefStr);
REQUIRE(strcmp(RefStr->str, "Mono") == 0);
}
TEST_CASE("Properties", "[C][Properties]") {
REQUIRE(Platform_get_IsWindows() == false);
Platform_set_ExitCode(255);
REQUIRE(Platform_get_ExitCode() == 255);
REQUIRE(Properties_Query_get_UniversalAnswer() == 42);
Properties_Query* prop = Properties_Query_new();
REQUIRE(Properties_Query_get_IsGood(prop) == true);
REQUIRE(Properties_Query_get_IsBad(prop) == false);
REQUIRE(Properties_Query_get_Answer(prop) == 42);
Properties_Query_set_Answer(prop, 911);
REQUIRE(Properties_Query_get_Answer(prop) == 911);
REQUIRE(Properties_Query_get_IsSecret(prop) == false);
Properties_Query_set_Secret(prop, 1);
REQUIRE(Properties_Query_get_IsSecret(prop) == true);
}
TEST_CASE("Namespaces.C", "[C][Namespaces]") {
ClassWithoutNamespace* nonamespace = ClassWithoutNamespace_new();
REQUIRE(strcmp(ClassWithoutNamespace_ToString(nonamespace), "ClassWithoutNamespace") == 0);
First_ClassWithSingleNamespace* singlenamespace = First_ClassWithSingleNamespace_new();
REQUIRE(strcmp(First_ClassWithSingleNamespace_ToString(singlenamespace), "First.ClassWithSingleNamespace") == 0);
First_Second_ClassWithNestedNamespace* nestednamespaces = First_Second_ClassWithNestedNamespace_new();
REQUIRE(strcmp(First_Second_ClassWithNestedNamespace_ToString(nestednamespaces), "First.Second.ClassWithNestedNamespace") == 0);
First_Second_Third_ClassWithNestedNamespace* nestednamespaces2 = First_Second_Third_ClassWithNestedNamespace_new();
REQUIRE(strcmp(First_Second_Third_ClassWithNestedNamespace_ToString(nestednamespaces2), "First.Second.Third.ClassWithNestedNamespace") == 0);
}
TEST_CASE("Constructors.C", "[C][Constructors]") {
Constructors_Unique* unique = Constructors_Unique_new_1();
REQUIRE(Constructors_Unique_get_Id(unique) == 1);
Constructors_Unique* unique_init_id = Constructors_Unique_new_2(911);
REQUIRE(Constructors_Unique_get_Id(unique_init_id) == 911);
Constructors_SuperUnique* super_unique_default_init = Constructors_SuperUnique_new();
REQUIRE(Constructors_Unique_get_Id(super_unique_default_init) == 411);
Constructors_Implicit* implicit = Constructors_Implicit_new();
REQUIRE(strcmp(Constructors_Implicit_get_TestResult(implicit), "OK") == 0);
Constructors_AllTypeCode* all1 = Constructors_AllTypeCode_new(true, USHRT_MAX, "Mono");
REQUIRE(Constructors_AllTypeCode_get_TestResult(all1) == true);
Constructors_AllTypeCode* all2 = Constructors_AllTypeCode_new_1(SCHAR_MAX, SHRT_MAX, INT_MAX, LONG_MAX);
REQUIRE(Constructors_AllTypeCode_get_TestResult(all2) == true);
Constructors_AllTypeCode* all3 = Constructors_AllTypeCode_new_2(UCHAR_MAX, USHRT_MAX, UINT_MAX, ULONG_MAX);
REQUIRE(Constructors_AllTypeCode_get_TestResult(all3) == true);
Constructors_AllTypeCode* all4 = Constructors_AllTypeCode_new_3(FLT_MAX, DBL_MAX);
REQUIRE(Constructors_AllTypeCode_get_TestResult(all4) == true);
}
TEST_CASE("Enums.C", "[C][Enums]") {
REQUIRE(Enums_EnumTypes_PassEnum(Enum_Two) == 2);
REQUIRE(Enums_EnumTypes_PassEnum(Enum_Three) == 3);
REQUIRE(Enums_EnumTypes_PassEnumByte(EnumByte_Two) == 2);
REQUIRE(Enums_EnumTypes_PassEnumByte(EnumByte_Three) == 3);
REQUIRE(Enums_EnumTypes_PassEnumFlags(EnumFlags_FlagOne) == (1 << 0));
REQUIRE(Enums_EnumTypes_PassEnumFlags(EnumFlags_FlagTwo) == (1 << 2));
}
TEST_CASE("Arrays.C", "[C][Arrays]") {
char _byte_arr[] = { 1, 2, 3 };
_UnsignedcharArray _byte;
_byte.array = g_array_sized_new(/*zero_terminated=*/false,
/*clear=*/true, sizeof(char), G_N_ELEMENTS(_byte_arr));
g_array_append_vals (_byte.array, _byte_arr, G_N_ELEMENTS(_byte_arr));
int _sum = Arrays_ArrayTypes_SumByteArray(_byte);
REQUIRE(_sum == 6);
_IntArray _int = Arrays_ArrayTypes_ReturnsIntArray();
REQUIRE(_int.array->len == 3);
REQUIRE(g_array_index(_int.array, int, 0) == 1);
REQUIRE(g_array_index(_int.array, int, 1) == 2);
REQUIRE(g_array_index(_int.array, int, 2) == 3);
_CharArray _string = Arrays_ArrayTypes_ReturnsStringArray();
REQUIRE(_string.array->len == 3);
REQUIRE(strcmp(g_array_index(_string.array, gchar*, 0), "1") == 0);
REQUIRE(strcmp(g_array_index(_string.array, gchar*, 1), "2") == 0);
REQUIRE(strcmp(g_array_index(_string.array, gchar*, 2), "3") == 0);
}
<commit_msg>[tests][c] Added a few more tests for types.<commit_after>#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include "managed.h"
#include "glib.h"
#include "float.h"
TEST_CASE("Types.C", "[C][Types]") {
REQUIRE(Type_Char_get_Min() == 0);
REQUIRE(Type_Char_get_Max() == USHRT_MAX);
REQUIRE(Type_Char_get_Zero() == 0);
REQUIRE(Type_SByte_get_Min() == SCHAR_MIN);
REQUIRE(Type_SByte_get_Max() == SCHAR_MAX);
REQUIRE(Type_Byte_get_Min() == 0);
REQUIRE(Type_Byte_get_Max() == UCHAR_MAX);
REQUIRE(Type_Int16_get_Min() == SHRT_MIN);
REQUIRE(Type_Int16_get_Max() == SHRT_MAX);
REQUIRE(Type_Int32_get_Min() == INT_MIN);
REQUIRE(Type_Int32_get_Max() == INT_MAX);
REQUIRE(Type_Int64_get_Min() == LONG_MIN);
REQUIRE(Type_Int64_get_Max() == LONG_MAX);
REQUIRE(Type_UInt16_get_Min() == 0);
REQUIRE(Type_UInt16_get_Max() == USHRT_MAX);
REQUIRE(Type_UInt32_get_Min() == 0);
REQUIRE(Type_UInt32_get_Max() == UINT_MAX);
REQUIRE(Type_UInt64_get_Min() == 0);
REQUIRE(Type_UInt64_get_Max() == ULONG_MAX);
REQUIRE(Type_Single_get_Min() == -FLT_MAX);
REQUIRE(Type_Single_get_Max() == FLT_MAX);
REQUIRE(Type_Double_get_Min() == -DBL_MAX);
REQUIRE(Type_Double_get_Max() == DBL_MAX);
REQUIRE(Type_String_get_NullString() == NULL);
REQUIRE(strcmp(Type_String_get_EmptyString(), "") == 0);
REQUIRE(strcmp(Type_String_get_NonEmptyString(), "Hello World") == 0);
BuiltinTypes* bt = BuiltinTypes_new();
BuiltinTypes_ReturnsVoid(bt);
REQUIRE(BuiltinTypes_ReturnsBool(bt) == true);
REQUIRE(BuiltinTypes_ReturnsSByte(bt) == -5);
REQUIRE(BuiltinTypes_ReturnsByte(bt) == 5);
REQUIRE(BuiltinTypes_ReturnsShort(bt) == -5);
REQUIRE(BuiltinTypes_ReturnsUShort(bt) == 5);
REQUIRE(BuiltinTypes_ReturnsInt(bt) == -5);
REQUIRE(BuiltinTypes_ReturnsUInt(bt) == 5);
REQUIRE(BuiltinTypes_ReturnsLong(bt) == -5);
REQUIRE(BuiltinTypes_ReturnsULong(bt) == 5);
REQUIRE(BuiltinTypes_ReturnsChar(bt) == 'a');
REQUIRE(strcmp(BuiltinTypes_ReturnsString(bt), "Mono") == 0);
REQUIRE(BuiltinTypes_PassAndReturnsBool(bt, true) == true);
REQUIRE(BuiltinTypes_PassAndReturnsSByte(bt, -5) == -5);
REQUIRE(BuiltinTypes_PassAndReturnsByte(bt, 5) == 5);
REQUIRE(BuiltinTypes_PassAndReturnsShort(bt, -5) == -5);
REQUIRE(BuiltinTypes_PassAndReturnsUShort(bt, 5) == 5);
REQUIRE(BuiltinTypes_PassAndReturnsInt(bt, -5) == -5);
REQUIRE(BuiltinTypes_PassAndReturnsUInt(bt, 5) == 5);
REQUIRE(BuiltinTypes_PassAndReturnsLong(bt, -5) == -5);
REQUIRE(BuiltinTypes_PassAndReturnsULong(bt, 5) == 5);
REQUIRE(BuiltinTypes_PassAndReturnsChar(bt, 'a') == 'a');
REQUIRE(strcmp(BuiltinTypes_PassAndReturnsString(bt, "Mono"), "Mono") == 0);
int OutInt = 0;
BuiltinTypes_PassOutInt(bt, &OutInt);
REQUIRE(OutInt == 5);
int RefInt = 0;
BuiltinTypes_PassRefInt(bt, &RefInt);
REQUIRE(RefInt == 10);
GString* RefOut = g_string_new("");
BuiltinTypes_PassOutString(bt, RefOut);
REQUIRE(strcmp(RefOut->str, "Mono") == 0);
GString* RefStr = g_string_new("monomono");
BuiltinTypes_PassRefString(bt, RefStr);
REQUIRE(strcmp(RefStr->str, "Mono") == 0);
}
TEST_CASE("Properties", "[C][Properties]") {
REQUIRE(Platform_get_IsWindows() == false);
Platform_set_ExitCode(255);
REQUIRE(Platform_get_ExitCode() == 255);
REQUIRE(Properties_Query_get_UniversalAnswer() == 42);
Properties_Query* prop = Properties_Query_new();
REQUIRE(Properties_Query_get_IsGood(prop) == true);
REQUIRE(Properties_Query_get_IsBad(prop) == false);
REQUIRE(Properties_Query_get_Answer(prop) == 42);
Properties_Query_set_Answer(prop, 911);
REQUIRE(Properties_Query_get_Answer(prop) == 911);
REQUIRE(Properties_Query_get_IsSecret(prop) == false);
Properties_Query_set_Secret(prop, 1);
REQUIRE(Properties_Query_get_IsSecret(prop) == true);
}
TEST_CASE("Namespaces.C", "[C][Namespaces]") {
ClassWithoutNamespace* nonamespace = ClassWithoutNamespace_new();
REQUIRE(strcmp(ClassWithoutNamespace_ToString(nonamespace), "ClassWithoutNamespace") == 0);
First_ClassWithSingleNamespace* singlenamespace = First_ClassWithSingleNamespace_new();
REQUIRE(strcmp(First_ClassWithSingleNamespace_ToString(singlenamespace), "First.ClassWithSingleNamespace") == 0);
First_Second_ClassWithNestedNamespace* nestednamespaces = First_Second_ClassWithNestedNamespace_new();
REQUIRE(strcmp(First_Second_ClassWithNestedNamespace_ToString(nestednamespaces), "First.Second.ClassWithNestedNamespace") == 0);
First_Second_Third_ClassWithNestedNamespace* nestednamespaces2 = First_Second_Third_ClassWithNestedNamespace_new();
REQUIRE(strcmp(First_Second_Third_ClassWithNestedNamespace_ToString(nestednamespaces2), "First.Second.Third.ClassWithNestedNamespace") == 0);
}
TEST_CASE("Constructors.C", "[C][Constructors]") {
Constructors_Unique* unique = Constructors_Unique_new_1();
REQUIRE(Constructors_Unique_get_Id(unique) == 1);
Constructors_Unique* unique_init_id = Constructors_Unique_new_2(911);
REQUIRE(Constructors_Unique_get_Id(unique_init_id) == 911);
Constructors_SuperUnique* super_unique_default_init = Constructors_SuperUnique_new();
REQUIRE(Constructors_Unique_get_Id(super_unique_default_init) == 411);
Constructors_Implicit* implicit = Constructors_Implicit_new();
REQUIRE(strcmp(Constructors_Implicit_get_TestResult(implicit), "OK") == 0);
Constructors_AllTypeCode* all1 = Constructors_AllTypeCode_new(true, USHRT_MAX, "Mono");
REQUIRE(Constructors_AllTypeCode_get_TestResult(all1) == true);
Constructors_AllTypeCode* all2 = Constructors_AllTypeCode_new_1(SCHAR_MAX, SHRT_MAX, INT_MAX, LONG_MAX);
REQUIRE(Constructors_AllTypeCode_get_TestResult(all2) == true);
Constructors_AllTypeCode* all3 = Constructors_AllTypeCode_new_2(UCHAR_MAX, USHRT_MAX, UINT_MAX, ULONG_MAX);
REQUIRE(Constructors_AllTypeCode_get_TestResult(all3) == true);
Constructors_AllTypeCode* all4 = Constructors_AllTypeCode_new_3(FLT_MAX, DBL_MAX);
REQUIRE(Constructors_AllTypeCode_get_TestResult(all4) == true);
}
TEST_CASE("Enums.C", "[C][Enums]") {
REQUIRE(Enums_EnumTypes_PassEnum(Enum_Two) == 2);
REQUIRE(Enums_EnumTypes_PassEnum(Enum_Three) == 3);
REQUIRE(Enums_EnumTypes_PassEnumByte(EnumByte_Two) == 2);
REQUIRE(Enums_EnumTypes_PassEnumByte(EnumByte_Three) == 3);
REQUIRE(Enums_EnumTypes_PassEnumFlags(EnumFlags_FlagOne) == (1 << 0));
REQUIRE(Enums_EnumTypes_PassEnumFlags(EnumFlags_FlagTwo) == (1 << 2));
}
TEST_CASE("Arrays.C", "[C][Arrays]") {
char _byte_arr[] = { 1, 2, 3 };
_UnsignedcharArray _byte;
_byte.array = g_array_sized_new(/*zero_terminated=*/false,
/*clear=*/true, sizeof(char), G_N_ELEMENTS(_byte_arr));
g_array_append_vals (_byte.array, _byte_arr, G_N_ELEMENTS(_byte_arr));
int _sum = Arrays_ArrayTypes_SumByteArray(_byte);
REQUIRE(_sum == 6);
_IntArray _int = Arrays_ArrayTypes_ReturnsIntArray();
REQUIRE(_int.array->len == 3);
REQUIRE(g_array_index(_int.array, int, 0) == 1);
REQUIRE(g_array_index(_int.array, int, 1) == 2);
REQUIRE(g_array_index(_int.array, int, 2) == 3);
_CharArray _string = Arrays_ArrayTypes_ReturnsStringArray();
REQUIRE(_string.array->len == 3);
REQUIRE(strcmp(g_array_index(_string.array, gchar*, 0), "1") == 0);
REQUIRE(strcmp(g_array_index(_string.array, gchar*, 1), "2") == 0);
REQUIRE(strcmp(g_array_index(_string.array, gchar*, 2), "3") == 0);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2016, Joseph Mirabel
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
//
// This file is part of hpp-core.
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core. If not, see <http://www.gnu.org/licenses/>.
#define BOOST_TEST_MODULE pathProjector
#include <pinocchio/fwd.hpp>
#include <boost/test/included/unit_test.hpp>
#include <boost/test/test_case_template.hpp>
#include <boost/mpl/list.hpp>
#include <boost/shared_ptr.hpp>
// Boost version 1.54
// Cannot include boost CPU timers
// #include <boost/timer/timer.hpp>
// because the original timers are already included by
// the unit test framework
// #include <boost/timer.hh>
// Force benchmark output
#define HPP_ENABLE_BENCHMARK 1
#include <hpp/util/timer.hh>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/urdf/util.hh>
#include <hpp/constraints/differentiable-function.hh>
#include <hpp/constraints/implicit.hh>
#include <hpp/core/straight-path.hh>
#include <hpp/core/config-projector.hh>
#include <hpp/core/constraint-set.hh>
#include <hpp/core/problem.hh>
#include <hpp/core/interpolated-path.hh>
#include <hpp/core/path/hermite.hh>
#include <hpp/core/steering-method/straight.hh>
#include <hpp/core/steering-method/hermite.hh>
#include <hpp/core/path-projector/global.hh>
#include <hpp/core/path-projector/progressive.hh>
#include <hpp/core/path-projector/recursive-hermite.hh>
using hpp::constraints::Implicit;
using hpp::constraints::EqualToZero;
using namespace hpp::core;
using namespace hpp::pinocchio;
DevicePtr_t createRobot ()
{
std::string urdf ("<robot name='test'>"
"<link name='link1'/>"
"<link name='link2'/>"
"<link name='link3'/>"
"<joint name='tx' type='prismatic'>"
"<parent link='link1'/>"
"<child link='link2'/>"
"<limit effort='30' velocity='1.0' lower='-4' upper='4'/>"
"</joint>"
"<joint name='ty' type='prismatic'>"
"<axis xyz='0 1 0'/>"
"<parent link='link2'/>"
"<child link='link3'/>"
"<limit effort='30' velocity='1.0' lower='-4' upper='4'/>"
"</joint>"
"</robot>"
);
DevicePtr_t robot = Device::create ("test");
urdf::loadModelFromString (robot, 0, "", "anchor", urdf, "");
return robot;
}
ConstraintSetPtr_t createConstraints (DevicePtr_t r)
{
ConfigProjectorPtr_t proj =
ConfigProjector::create (r, "Polynomial projector", 1e-4, 20);
ConstraintSetPtr_t set = ConstraintSet::create (r, "Set");
set->addConstraint (proj);
return set;
}
class Polynomial : public DifferentiableFunction {
public:
Polynomial (DevicePtr_t robot) :
DifferentiableFunction (robot->configSize(), robot->numberDof (),
LiegroupSpace::R1 (), "Polynomial"),
coefs_ (vector_t::Ones (robot->configSize()))
{}
vector_t coefs_;
protected:
void impl_compute (LiegroupElementRef result, vectorIn_t argument) const {
result.vector ()[0] = argument.cwiseProduct (argument).dot (coefs_) - 1;
}
void impl_jacobian (matrixOut_t jacobian, vectorIn_t arg) const {
jacobian.row(0) = 2 * arg.cwiseProduct (coefs_);
}
};
typedef std::shared_ptr<Polynomial> PolynomialPtr_t;
/*
bool checkContinuity (PathPtr_t path) {
const value_type stepPath = path->length () / (100 - 1);
Configuration_t q = path->initial(), qq = path->initial();
vector_t v1 (func->outputSize()), v2(func->outputSize());
std::cerr << std::fixed << std::showpos << std::setprecision (4);
const char* sep = "\t| ";
for (std::size_t i = 0; i < 100; ++i) {
if (!(*path) (q, (value_type)i * stepPath))
std::cerr << "Could not project path at " << (value_type)i*stepPath
<< "\n";
if (!(*projection) (qq, (value_type) i * stepProj))
std::cerr << "Could not project projection at "
<< (value_type) i*stepProj << "\n";
(*func) (v1, q);
(*func) (v2, qq);
std::cerr << q.transpose () << sep << v1
<< sep << qq.transpose () << sep << v2 << "\n";
}
// Analyse projection
if (!HPP_DYNAMIC_PTR_CAST (InterpolatedPath, projection)) {
std::cout << "Path is not an InterpolatedPath\n";
std::cerr
<< projection->timeRange().first << sep << projection->initial ().transpose() << '\n'
<< projection->timeRange().first + projection->timeRange().second << sep << projection->end ().transpose() << '\n';
return;
}
InterpolatedPath& p = *(HPP_DYNAMIC_PTR_CAST (InterpolatedPath, projection));
typedef InterpolatedPath::InterpolationPoints_t InterpolationPoints_t;
const InterpolationPoints_t& points = p.interpolationPoints ();
std::cout << "InterpolatedPath: " << points.size() << " interpolation points.\n";
for (InterpolationPoints_t::const_iterator it = points.begin();
it != points.end(); ++it) {
std::cerr << it->first << sep << it->second.transpose() << '\n';
}
}
// */
void displayPaths (PathPtr_t path, PathPtr_t projection, DifferentiableFunctionPtr_t func) {
const value_type stepPath = path->length () / (100 - 1);
const value_type stepProj = projection->length () / (100 - 1);
Configuration_t q = path->initial(), qq = path->initial();
LiegroupElement v1 (func->outputSpace ()), v2(func->outputSpace());
std::cerr << std::fixed << std::showpos << std::setprecision (4);
const char* sep = "\t| ";
for (std::size_t i = 0; i < 100; ++i) {
if (!(*path) (q, (value_type)i * stepPath))
std::cerr << "Could not project path at " << (value_type)i*stepPath
<< "\n";
if (!(*projection) (qq, (value_type) i * stepProj))
std::cerr << "Could not project projection at "
<< (value_type) i*stepProj << "\n";
func->value (v1, q);
func->value (v2, qq);
std::cerr << q.transpose () << sep << v1
<< sep << qq.transpose () << sep << v2 << "\n";
}
// Analyse projection
if (!HPP_DYNAMIC_PTR_CAST (InterpolatedPath, projection)) {
std::cout << "Path is not an InterpolatedPath\n";
std::cerr
<< projection->timeRange().first << sep << projection->initial ().transpose() << '\n'
<< projection->timeRange().first + projection->timeRange().second << sep << projection->end ().transpose() << '\n';
return;
}
InterpolatedPath& p = *(HPP_DYNAMIC_PTR_CAST (InterpolatedPath, projection));
typedef InterpolatedPath::InterpolationPoints_t InterpolationPoints_t;
const InterpolationPoints_t& points = p.interpolationPoints ();
std::cout << "InterpolatedPath: " << points.size() << " interpolation points.\n";
for (InterpolationPoints_t::const_iterator it = points.begin();
it != points.end(); ++it) {
std::cerr << it->first << sep << it->second.transpose() << '\n';
}
}
struct traits_circle {
static DifferentiableFunctionPtr_t func (DevicePtr_t dev) {
return PolynomialPtr_t (new Polynomial (dev));
}
static void make_conf (ConfigurationOut_t q1, ConfigurationOut_t q2,
const int index) {
switch (index) {
case 0: q1 << 0, 1; q2 << 1, 0; break;
case 1: q1 << 1, 0; q2 << -1, 0; break;
case 2: {
double c = -0.99;
q1 << 1, 0; q2 << c, sqrt(1 - c*c);
break;
}
case 3: {
double c = -0.9;
q1 << 1, 0; q2 << c, sqrt(1 - c*c);
break;
}
case 4: {
double c = -0.85;
q1 << 1, 0; q2 << c, sqrt(1 - c*c);
break;
}
case 5: {
double c = -0.8;
q1 << 1, 0; q2 << c, sqrt(1 - c*c);
break;
}
case 6: {
double c = -0.75;
q1 << 1, 0; q2 << c, sqrt(1 - c*c);
break;
}
case 7: {
double c = -0.7;
q1 << 1, 0; q2 << c, sqrt(1 - c*c);
break;
}
}
}
static const int NB_CONFS;
static const value_type K;
static const char* _func;
};
struct traits_parabola {
static DifferentiableFunctionPtr_t func (DevicePtr_t dev) {
PolynomialPtr_t parabola (new Polynomial (dev));
parabola->coefs_(1) = 0;
return parabola;
}
static void make_conf (ConfigurationOut_t q1, ConfigurationOut_t q2,
const int index) {
q1 << 1,0; q2 << -1,(value_type)(2*index) / (NB_CONFS - 1);
// switch (index) {
// case 0: q1 << 1,0; q2 << -1,0; break; // Should be really fast
// case 1: q1 << 1,0; q2 << -1,1; break; // Should be slower
// }
}
static const int NB_CONFS;
static const value_type K;
static const char* _func;
};
const int traits_circle::NB_CONFS = 8;
const value_type traits_circle::K = 2.001;
const char* traits_circle::_func = "circle";
const int traits_parabola::NB_CONFS = 8;
const value_type traits_parabola::K = 2 * sqrt(2);
const char* traits_parabola::_func = "parabola";
struct traits_progressive {
typedef pathProjector::Progressive Proj_t;
typedef pathProjector::ProgressivePtr_t ProjPtr_t;
typedef steeringMethod::Straight SM_t;
static const value_type projection_step;
static const char* _proj;
};
struct traits_global {
typedef pathProjector::Global Proj_t;
typedef pathProjector::GlobalPtr_t ProjPtr_t;
typedef steeringMethod::Straight SM_t;
static const value_type projection_step;
static const char* _proj;
};
struct traits_hermite {
typedef pathProjector::RecursiveHermite Proj_t;
typedef pathProjector::RecursiveHermitePtr_t ProjPtr_t;
typedef steeringMethod::Hermite SM_t;
static const value_type projection_step;
static const char* _proj;
};
const value_type traits_progressive::projection_step = 0.1;
const value_type traits_global ::projection_step = 0.1;
const value_type traits_hermite ::projection_step = 2;
const char* traits_progressive::_proj = "progressive";
const char* traits_global ::_proj = "global";
const char* traits_hermite ::_proj = "hermite";
struct traits_global_circle : traits_global , traits_circle {};
struct traits_global_parabola : traits_global , traits_parabola {};
struct traits_progressive_circle : traits_progressive, traits_circle {};
struct traits_progressive_parabola : traits_progressive, traits_parabola {};
struct traits_hermite_circle : traits_hermite , traits_circle {};
struct traits_hermite_parabola : traits_hermite , traits_parabola {};
typedef boost::mpl::list < traits_global_circle
, traits_progressive_circle
, traits_hermite_circle
, traits_global_parabola
, traits_progressive_parabola
, traits_hermite_parabola
> test_types;
BOOST_AUTO_TEST_CASE_TEMPLATE (projectors, traits, test_types)
{
DevicePtr_t dev = createRobot();
BOOST_REQUIRE (dev);
ProblemPtr_t problem = Problem::create(dev);
ConstraintSetPtr_t c = createConstraints (dev);
DifferentiableFunctionPtr_t func = traits::func (dev);
c->configProjector ()->add (Implicit::create (func,
ComparisonTypes_t(func->outputSpace()->nv(), EqualToZero)));
problem->steeringMethod(traits::SM_t::create(problem));
problem->steeringMethod ()->constraints (c);
for (int c = 0; c < 2; ++c) {
if (c == 0)
problem->setParameter ("PathProjection/HessianBound", Parameter((value_type)-1));
else
problem->setParameter ("PathProjection/HessianBound", Parameter(traits::K));
typename traits::ProjPtr_t projector =
traits::Proj_t::create (problem, traits::projection_step);
std::cout << "========================================\n";
Configuration_t q1 (dev->configSize());
Configuration_t q2 (dev->configSize());
for (int i = 0; i < traits::NB_CONFS; ++i) {
// HPP_DEFINE_TIMECOUNTER(projector);
traits::make_conf (q1, q2, i);
PathPtr_t path = (*problem->steeringMethod ()) (q1,q2);
PathPtr_t projection;
// Averaging the projection
bool success;
for (int j = 0; j < 2; ++j) {
// HPP_START_TIMECOUNTER (projector);
success = projector->apply (path, projection);
// HPP_STOP_TIMECOUNTER (projector);
// HPP_DISPLAY_LAST_TIMECOUNTER (projector);
}
std::cout << traits::_proj << " " << traits::_func << ": projection of "
<< q1.transpose() << " -> " << q2.transpose() << " "
<< (success?"succeeded.":"failed.") << std::endl;
// HPP_STREAM_TIMECOUNTER (std::cout, projector) << std::endl;
// displayPaths (path, projection, func);
}
}
}
<commit_msg>[tests] Replace deprecated header.<commit_after>// Copyright (c) 2016, Joseph Mirabel
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
//
// This file is part of hpp-core.
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core. If not, see <http://www.gnu.org/licenses/>.
#define BOOST_TEST_MODULE pathProjector
#include <pinocchio/fwd.hpp>
#include <boost/test/included/unit_test.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/mpl/list.hpp>
#include <boost/shared_ptr.hpp>
// Boost version 1.54
// Cannot include boost CPU timers
// #include <boost/timer/timer.hpp>
// because the original timers are already included by
// the unit test framework
// #include <boost/timer.hh>
// Force benchmark output
#define HPP_ENABLE_BENCHMARK 1
#include <hpp/util/timer.hh>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/urdf/util.hh>
#include <hpp/constraints/differentiable-function.hh>
#include <hpp/constraints/implicit.hh>
#include <hpp/core/straight-path.hh>
#include <hpp/core/config-projector.hh>
#include <hpp/core/constraint-set.hh>
#include <hpp/core/problem.hh>
#include <hpp/core/interpolated-path.hh>
#include <hpp/core/path/hermite.hh>
#include <hpp/core/steering-method/straight.hh>
#include <hpp/core/steering-method/hermite.hh>
#include <hpp/core/path-projector/global.hh>
#include <hpp/core/path-projector/progressive.hh>
#include <hpp/core/path-projector/recursive-hermite.hh>
using hpp::constraints::Implicit;
using hpp::constraints::EqualToZero;
using namespace hpp::core;
using namespace hpp::pinocchio;
DevicePtr_t createRobot ()
{
std::string urdf ("<robot name='test'>"
"<link name='link1'/>"
"<link name='link2'/>"
"<link name='link3'/>"
"<joint name='tx' type='prismatic'>"
"<parent link='link1'/>"
"<child link='link2'/>"
"<limit effort='30' velocity='1.0' lower='-4' upper='4'/>"
"</joint>"
"<joint name='ty' type='prismatic'>"
"<axis xyz='0 1 0'/>"
"<parent link='link2'/>"
"<child link='link3'/>"
"<limit effort='30' velocity='1.0' lower='-4' upper='4'/>"
"</joint>"
"</robot>"
);
DevicePtr_t robot = Device::create ("test");
urdf::loadModelFromString (robot, 0, "", "anchor", urdf, "");
return robot;
}
ConstraintSetPtr_t createConstraints (DevicePtr_t r)
{
ConfigProjectorPtr_t proj =
ConfigProjector::create (r, "Polynomial projector", 1e-4, 20);
ConstraintSetPtr_t set = ConstraintSet::create (r, "Set");
set->addConstraint (proj);
return set;
}
class Polynomial : public DifferentiableFunction {
public:
Polynomial (DevicePtr_t robot) :
DifferentiableFunction (robot->configSize(), robot->numberDof (),
LiegroupSpace::R1 (), "Polynomial"),
coefs_ (vector_t::Ones (robot->configSize()))
{}
vector_t coefs_;
protected:
void impl_compute (LiegroupElementRef result, vectorIn_t argument) const {
result.vector ()[0] = argument.cwiseProduct (argument).dot (coefs_) - 1;
}
void impl_jacobian (matrixOut_t jacobian, vectorIn_t arg) const {
jacobian.row(0) = 2 * arg.cwiseProduct (coefs_);
}
};
typedef std::shared_ptr<Polynomial> PolynomialPtr_t;
/*
bool checkContinuity (PathPtr_t path) {
const value_type stepPath = path->length () / (100 - 1);
Configuration_t q = path->initial(), qq = path->initial();
vector_t v1 (func->outputSize()), v2(func->outputSize());
std::cerr << std::fixed << std::showpos << std::setprecision (4);
const char* sep = "\t| ";
for (std::size_t i = 0; i < 100; ++i) {
if (!(*path) (q, (value_type)i * stepPath))
std::cerr << "Could not project path at " << (value_type)i*stepPath
<< "\n";
if (!(*projection) (qq, (value_type) i * stepProj))
std::cerr << "Could not project projection at "
<< (value_type) i*stepProj << "\n";
(*func) (v1, q);
(*func) (v2, qq);
std::cerr << q.transpose () << sep << v1
<< sep << qq.transpose () << sep << v2 << "\n";
}
// Analyse projection
if (!HPP_DYNAMIC_PTR_CAST (InterpolatedPath, projection)) {
std::cout << "Path is not an InterpolatedPath\n";
std::cerr
<< projection->timeRange().first << sep << projection->initial ().transpose() << '\n'
<< projection->timeRange().first + projection->timeRange().second << sep << projection->end ().transpose() << '\n';
return;
}
InterpolatedPath& p = *(HPP_DYNAMIC_PTR_CAST (InterpolatedPath, projection));
typedef InterpolatedPath::InterpolationPoints_t InterpolationPoints_t;
const InterpolationPoints_t& points = p.interpolationPoints ();
std::cout << "InterpolatedPath: " << points.size() << " interpolation points.\n";
for (InterpolationPoints_t::const_iterator it = points.begin();
it != points.end(); ++it) {
std::cerr << it->first << sep << it->second.transpose() << '\n';
}
}
// */
void displayPaths (PathPtr_t path, PathPtr_t projection, DifferentiableFunctionPtr_t func) {
const value_type stepPath = path->length () / (100 - 1);
const value_type stepProj = projection->length () / (100 - 1);
Configuration_t q = path->initial(), qq = path->initial();
LiegroupElement v1 (func->outputSpace ()), v2(func->outputSpace());
std::cerr << std::fixed << std::showpos << std::setprecision (4);
const char* sep = "\t| ";
for (std::size_t i = 0; i < 100; ++i) {
if (!(*path) (q, (value_type)i * stepPath))
std::cerr << "Could not project path at " << (value_type)i*stepPath
<< "\n";
if (!(*projection) (qq, (value_type) i * stepProj))
std::cerr << "Could not project projection at "
<< (value_type) i*stepProj << "\n";
func->value (v1, q);
func->value (v2, qq);
std::cerr << q.transpose () << sep << v1
<< sep << qq.transpose () << sep << v2 << "\n";
}
// Analyse projection
if (!HPP_DYNAMIC_PTR_CAST (InterpolatedPath, projection)) {
std::cout << "Path is not an InterpolatedPath\n";
std::cerr
<< projection->timeRange().first << sep << projection->initial ().transpose() << '\n'
<< projection->timeRange().first + projection->timeRange().second << sep << projection->end ().transpose() << '\n';
return;
}
InterpolatedPath& p = *(HPP_DYNAMIC_PTR_CAST (InterpolatedPath, projection));
typedef InterpolatedPath::InterpolationPoints_t InterpolationPoints_t;
const InterpolationPoints_t& points = p.interpolationPoints ();
std::cout << "InterpolatedPath: " << points.size() << " interpolation points.\n";
for (InterpolationPoints_t::const_iterator it = points.begin();
it != points.end(); ++it) {
std::cerr << it->first << sep << it->second.transpose() << '\n';
}
}
struct traits_circle {
static DifferentiableFunctionPtr_t func (DevicePtr_t dev) {
return PolynomialPtr_t (new Polynomial (dev));
}
static void make_conf (ConfigurationOut_t q1, ConfigurationOut_t q2,
const int index) {
switch (index) {
case 0: q1 << 0, 1; q2 << 1, 0; break;
case 1: q1 << 1, 0; q2 << -1, 0; break;
case 2: {
double c = -0.99;
q1 << 1, 0; q2 << c, sqrt(1 - c*c);
break;
}
case 3: {
double c = -0.9;
q1 << 1, 0; q2 << c, sqrt(1 - c*c);
break;
}
case 4: {
double c = -0.85;
q1 << 1, 0; q2 << c, sqrt(1 - c*c);
break;
}
case 5: {
double c = -0.8;
q1 << 1, 0; q2 << c, sqrt(1 - c*c);
break;
}
case 6: {
double c = -0.75;
q1 << 1, 0; q2 << c, sqrt(1 - c*c);
break;
}
case 7: {
double c = -0.7;
q1 << 1, 0; q2 << c, sqrt(1 - c*c);
break;
}
}
}
static const int NB_CONFS;
static const value_type K;
static const char* _func;
};
struct traits_parabola {
static DifferentiableFunctionPtr_t func (DevicePtr_t dev) {
PolynomialPtr_t parabola (new Polynomial (dev));
parabola->coefs_(1) = 0;
return parabola;
}
static void make_conf (ConfigurationOut_t q1, ConfigurationOut_t q2,
const int index) {
q1 << 1,0; q2 << -1,(value_type)(2*index) / (NB_CONFS - 1);
// switch (index) {
// case 0: q1 << 1,0; q2 << -1,0; break; // Should be really fast
// case 1: q1 << 1,0; q2 << -1,1; break; // Should be slower
// }
}
static const int NB_CONFS;
static const value_type K;
static const char* _func;
};
const int traits_circle::NB_CONFS = 8;
const value_type traits_circle::K = 2.001;
const char* traits_circle::_func = "circle";
const int traits_parabola::NB_CONFS = 8;
const value_type traits_parabola::K = 2 * sqrt(2);
const char* traits_parabola::_func = "parabola";
struct traits_progressive {
typedef pathProjector::Progressive Proj_t;
typedef pathProjector::ProgressivePtr_t ProjPtr_t;
typedef steeringMethod::Straight SM_t;
static const value_type projection_step;
static const char* _proj;
};
struct traits_global {
typedef pathProjector::Global Proj_t;
typedef pathProjector::GlobalPtr_t ProjPtr_t;
typedef steeringMethod::Straight SM_t;
static const value_type projection_step;
static const char* _proj;
};
struct traits_hermite {
typedef pathProjector::RecursiveHermite Proj_t;
typedef pathProjector::RecursiveHermitePtr_t ProjPtr_t;
typedef steeringMethod::Hermite SM_t;
static const value_type projection_step;
static const char* _proj;
};
const value_type traits_progressive::projection_step = 0.1;
const value_type traits_global ::projection_step = 0.1;
const value_type traits_hermite ::projection_step = 2;
const char* traits_progressive::_proj = "progressive";
const char* traits_global ::_proj = "global";
const char* traits_hermite ::_proj = "hermite";
struct traits_global_circle : traits_global , traits_circle {};
struct traits_global_parabola : traits_global , traits_parabola {};
struct traits_progressive_circle : traits_progressive, traits_circle {};
struct traits_progressive_parabola : traits_progressive, traits_parabola {};
struct traits_hermite_circle : traits_hermite , traits_circle {};
struct traits_hermite_parabola : traits_hermite , traits_parabola {};
typedef boost::mpl::list < traits_global_circle
, traits_progressive_circle
, traits_hermite_circle
, traits_global_parabola
, traits_progressive_parabola
, traits_hermite_parabola
> test_types;
BOOST_AUTO_TEST_CASE_TEMPLATE (projectors, traits, test_types)
{
DevicePtr_t dev = createRobot();
BOOST_REQUIRE (dev);
ProblemPtr_t problem = Problem::create(dev);
ConstraintSetPtr_t c = createConstraints (dev);
DifferentiableFunctionPtr_t func = traits::func (dev);
c->configProjector ()->add (Implicit::create (func,
ComparisonTypes_t(func->outputSpace()->nv(), EqualToZero)));
problem->steeringMethod(traits::SM_t::create(problem));
problem->steeringMethod ()->constraints (c);
for (int c = 0; c < 2; ++c) {
if (c == 0)
problem->setParameter ("PathProjection/HessianBound", Parameter((value_type)-1));
else
problem->setParameter ("PathProjection/HessianBound", Parameter(traits::K));
typename traits::ProjPtr_t projector =
traits::Proj_t::create (problem, traits::projection_step);
std::cout << "========================================\n";
Configuration_t q1 (dev->configSize());
Configuration_t q2 (dev->configSize());
for (int i = 0; i < traits::NB_CONFS; ++i) {
// HPP_DEFINE_TIMECOUNTER(projector);
traits::make_conf (q1, q2, i);
PathPtr_t path = (*problem->steeringMethod ()) (q1,q2);
PathPtr_t projection;
// Averaging the projection
bool success;
for (int j = 0; j < 2; ++j) {
// HPP_START_TIMECOUNTER (projector);
success = projector->apply (path, projection);
// HPP_STOP_TIMECOUNTER (projector);
// HPP_DISPLAY_LAST_TIMECOUNTER (projector);
}
std::cout << traits::_proj << " " << traits::_func << ": projection of "
<< q1.transpose() << " -> " << q2.transpose() << " "
<< (success?"succeeded.":"failed.") << std::endl;
// HPP_STREAM_TIMECOUNTER (std::cout, projector) << std::endl;
// displayPaths (path, projection, func);
}
}
}
<|endoftext|>
|
<commit_before>#include "account.hpp"
#include "b_string.hpp"
#include "draft_journal.hpp"
#include "entry.hpp"
#include "interval_type.hpp"
#include "phatbooks_tests_common.hpp"
#include "repeater.hpp"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/shared_ptr.hpp>
#include <jewel/decimal.hpp>
#include <UnitTest++/UnitTest++.h>
#include <vector>
namespace gregorian = boost::gregorian;
using boost::shared_ptr;
using jewel::Decimal;
using gregorian::date;
using std::vector;
namespace phatbooks
{
namespace test
{
TEST_FIXTURE(TestFixture, test_repeater_next_date)
{
PhatbooksDatabaseConnection& dbc = *pdbc;
DraftJournal dj(dbc);
dj.set_whether_actual(true);
dj.set_comment("draft journal to test repeater");
dj.set_name("Test");
Entry entry1(dbc);
entry1.set_account(Account(dbc, "cash"));
entry1.set_comment("Test entry");
entry1.set_amount(Decimal("-0.95"));
entry1.set_whether_reconciled(false);
dj.push_entry(entry1);
Entry entry2(dbc);
entry2.set_account(Account(dbc, "food"));
entry2.set_comment("Test entry");
entry2.set_amount(Decimal("0.95"));
entry2.set_whether_reconciled(false);
dj.push_entry(entry2);
Repeater repeater1(dbc);
repeater1.set_interval_type(interval_type::days);
repeater1.set_interval_units(3);
repeater1.set_next_date(date(2012, 5, 30));
dj.push_repeater(repeater1);
dj.save();
CHECK_EQUAL(repeater1.next_date(), date(2012, 5, 30));
CHECK_EQUAL(repeater1.next_date(0), date(2012, 5, 30));
CHECK_EQUAL(repeater1.next_date(2), date(2012, 6, 5));
CHECK_EQUAL(repeater1.next_date(1), date(2012, 6, 2));
Repeater repeater2(dbc);
repeater2.set_interval_type(interval_type::weeks);
repeater2.set_interval_units(2);
repeater2.set_next_date(date(2012, 12, 31));
dj.push_repeater(repeater2);
dj.save();
CHECK_EQUAL(repeater2.next_date(2), date(2013, 1, 28));
CHECK_EQUAL(repeater2.next_date(1), date(2013, 1, 14));
Repeater repeater3(dbc);
repeater3.set_interval_type(interval_type::months);
repeater3.set_interval_units(1);
repeater3.set_next_date(date(2014, 9, 20));
CHECK_EQUAL(repeater3.next_date(5), date(2015, 2, 20));
Repeater repeater4(dbc);
repeater4.set_interval_type(interval_type::month_ends);
repeater4.set_interval_units(1);
repeater4.set_next_date(date(1996, 1, 31));
CHECK_EQUAL(repeater4.next_date(), date(1996, 1, 31));
CHECK_EQUAL(repeater4.next_date(1), date(1996, 2, 29));
CHECK_EQUAL(repeater4.next_date(6), date(1996, 7, 31));
CHECK_EQUAL(repeater4.next_date(8), date(1996, 9, 30));
CHECK_EQUAL(repeater4.next_date(13), date(1997, 2, 28));
Repeater repeater5(dbc);
repeater5.set_interval_type(interval_type::days);
repeater5.set_interval_units(1);
repeater5.set_next_date(date(1900, 2, 27));
CHECK_EQUAL(repeater5.next_date(1), date(1900, 2, 28));
CHECK_EQUAL(repeater5.next_date(2), date(1900, 3, 1));
Repeater repeater6(dbc);
repeater6.set_interval_type(interval_type::month_ends);
repeater6.set_interval_units(12);
repeater6.set_next_date(date(1999, 2, 28));
CHECK_EQUAL(repeater6.next_date(1), date(2000, 2, 29));
Repeater repeater1b(dbc, 1);
CHECK_EQUAL(repeater1b.next_date(), date(2012, 5, 30));
CHECK_EQUAL(repeater1b.next_date(1), date(2012, 6, 2));
}
TEST_FIXTURE(TestFixture, test_repeater_firings_till)
{
PhatbooksDatabaseConnection& dbc = *pdbc;
Repeater repeater1(dbc);
repeater1.set_interval_type(interval_type::days);
repeater1.set_interval_units(5);
repeater1.set_next_date(date(2000, 5, 3));
shared_ptr<vector<date> > firings1 =
repeater1.firings_till(date(1999, 5, 2));
CHECK(firings1->empty());
firings1 = repeater1.firings_till(date(2000, 5, 4));
CHECK_EQUAL(firings1->size(), 1);
CHECK_EQUAL((*firings1)[0], date(2000, 5, 3));
firings1 = repeater1.firings_till(date(2000, 5, 2));
CHECK(firings1->empty());
firings1 = repeater1.firings_till(date(2000, 5, 3));
CHECK_EQUAL(firings1->size(), 1);
CHECK_EQUAL((*firings1)[0], date(2000, 5, 3));
firings1 = repeater1.firings_till(date(2000, 5, 20));
CHECK_EQUAL(firings1->size(), 4);
CHECK_EQUAL((*firings1)[0], date(2000, 5, 3));
CHECK_EQUAL((*firings1)[1], date(2000, 5, 8));
CHECK_EQUAL((*firings1)[2], date(2000, 5, 13));
CHECK_EQUAL((*firings1)[3], date(2000, 5, 18));
Repeater repeater2(dbc);
repeater2.set_interval_type(interval_type::month_ends);
repeater2.set_interval_units(3);
repeater2.set_next_date(date(2012, 12, 31));
shared_ptr<vector<date> > firings2;
firings2 = repeater2.firings_till(date(2012, 12, 30));
CHECK(firings2->empty());
firings2 = repeater2.firings_till(date(2013, 2, 28));
CHECK_EQUAL(firings2->size(), 1);
CHECK_EQUAL((*firings2)[0], date(2012, 12, 31));
firings2 = repeater2.firings_till(date(2013, 12, 31));
CHECK_EQUAL(firings2->size(), 5);
CHECK_EQUAL((*firings2)[4], date(2013, 12, 31));
CHECK_EQUAL((*firings2)[3], date(2013, 9, 30));
CHECK_EQUAL((*firings2)[2], date(2013, 6, 30));
CHECK_EQUAL((*firings2)[1], date(2013, 3, 31));
CHECK_EQUAL((*firings2)[0], date(2012, 12, 31));
}
TEST_FIXTURE(TestFixture, test_repeater_fire_next)
{
PhatbooksDatabaseConnection& dbc = *pdbc;
DraftJournal dj1(dbc);
dj1.set_whether_actual(true);
dj1.set_comment("journal to test repeater");
dj1.set_name(BString("Test")); // BString is optional
Entry entry1a(dbc);
entry1a.set_account(Account(dbc, "cash"));
entry1a.set_comment(BString("Test entry")); // BString is optional
entry1a.set_amount(Decimal("-1090.95"));
entry1a.set_whether_reconciled(false);
dj1.push_entry(entry1a);
Entry entry1b(dbc);
entry1b.set_account(Account(dbc, "food"));
entry1b.set_comment("Test entry");
entry1b.set_amount(Decimal("1090.95"));
entry1b.set_whether_reconciled(false);
dj1.push_entry(entry1b);
Repeater repeater1(dbc);
repeater1.set_interval_type(interval_type::weeks);
repeater1.set_interval_units(2);
repeater1.set_next_date(date(2012, 7, 30));
dj1.push_repeater(repeater1);
dj1.save();
Repeater repeater1b(dbc, 1);
OrdinaryJournal oj1b = repeater1b.fire_next();
CHECK_EQUAL(oj1b.comment(), "journal to test repeater");
CHECK_EQUAL(oj1b.comment(), BString("journal to test repeater"));
CHECK_EQUAL(oj1b.date(), date(2012, 7, 30));
CHECK_EQUAL(repeater1.next_date(), date(2012, 8, 13));
OrdinaryJournal oj1c(dbc, 2);
CHECK_EQUAL(oj1c.date(), date(2012, 7, 30));
CHECK_EQUAL(oj1c.comment(), "journal to test repeater");
CHECK_EQUAL(oj1c.entries().size(), 2);
repeater1b.fire_next();
repeater1b.fire_next();
OrdinaryJournal oj3(dbc, 3);
OrdinaryJournal oj4(dbc, 4);
CHECK_EQUAL(oj3.date(), date(2012, 8, 13));
CHECK_EQUAL(oj4.date(), date(2012, 8, 27));
CHECK_EQUAL(oj4.id(), 4);
CHECK_EQUAL(oj3.comment(), oj4.comment());
vector<Entry>::const_iterator it3 = ++oj3.entries().begin();
vector<Entry>::const_iterator it4 = ++oj4.entries().begin();
CHECK_EQUAL(it3->amount(), it4->amount());
}
TEST_FIXTURE(TestFixture, test_repeater_frequency_phrase)
{
PhatbooksDatabaseConnection& dbc = *pdbc;
Repeater repeater1(dbc);
repeater1.set_interval_type(interval_type::days);
repeater1.set_interval_units(1);
CHECK_EQUAL(frequency_description(repeater1), "every day");
CHECK(typeid(frequency_description(repeater1)) == typeid(std::string));
CHECK_EQUAL(frequency_description(repeater1), BString("every day"));
Repeater repeater2(dbc);
repeater2.set_interval_type(interval_type::days);
repeater2.set_interval_units(12);
CHECK_EQUAL(frequency_description(repeater2), "every 12 days");
Repeater repeater3(dbc);
repeater3.set_interval_type(interval_type::weeks);
repeater3.set_interval_units(1);
CHECK_EQUAL(frequency_description(repeater3), "every week");
Repeater repeater4(dbc);
repeater4.set_interval_type(interval_type::weeks);
repeater4.set_interval_units(2);
CHECK_EQUAL(frequency_description(repeater4), "every 2 weeks");
Repeater repeater5(dbc);
repeater5.set_interval_type(interval_type::months);
repeater5.set_interval_units(3);
CHECK_EQUAL(frequency_description(repeater5), "every 3 months");
Repeater repeater6(dbc);
repeater6.set_interval_type(interval_type::months);
repeater6.set_interval_units(1);
CHECK_EQUAL(frequency_description(repeater6), "every month");
Repeater repeater7(dbc);
repeater7.set_interval_type(interval_type::months);
repeater7.set_interval_units(12);
CHECK_EQUAL(frequency_description(repeater7), "every 12 months");
Repeater repeater8(dbc);
repeater8.set_interval_type(interval_type::month_ends);
repeater8.set_interval_units(1);
CHECK_EQUAL
( frequency_description(repeater8),
"every month, on the last day of the month"
);
Repeater repeater9(dbc);
repeater9.set_interval_type(interval_type::month_ends);
repeater9.set_interval_units(10);
CHECK_EQUAL
( frequency_description(repeater9),
"every 10 months, on the last day of the month"
);
CHECK_EQUAL
( frequency_description(repeater9),
BString("every 10 months, on the last day of the month")
);
}
} // namespace test
} // namespace phatbooks
<commit_msg>Changes code in tests for Repeater, to accommodate new Frequency-based interface to Repeater.<commit_after>#include "account.hpp"
#include "b_string.hpp"
#include "draft_journal.hpp"
#include "entry.hpp"
#include "frequency.hpp"
#include "interval_type.hpp"
#include "phatbooks_tests_common.hpp"
#include "repeater.hpp"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/shared_ptr.hpp>
#include <jewel/decimal.hpp>
#include <UnitTest++/UnitTest++.h>
#include <vector>
namespace gregorian = boost::gregorian;
using boost::shared_ptr;
using jewel::Decimal;
using gregorian::date;
using std::vector;
namespace phatbooks
{
namespace test
{
TEST_FIXTURE(TestFixture, test_repeater_next_date)
{
PhatbooksDatabaseConnection& dbc = *pdbc;
DraftJournal dj(dbc);
dj.set_whether_actual(true);
dj.set_comment("draft journal to test repeater");
dj.set_name("Test");
Entry entry1(dbc);
entry1.set_account(Account(dbc, "cash"));
entry1.set_comment("Test entry");
entry1.set_amount(Decimal("-0.95"));
entry1.set_whether_reconciled(false);
dj.push_entry(entry1);
Entry entry2(dbc);
entry2.set_account(Account(dbc, "food"));
entry2.set_comment("Test entry");
entry2.set_amount(Decimal("0.95"));
entry2.set_whether_reconciled(false);
dj.push_entry(entry2);
Repeater repeater1(dbc);
repeater1.set_frequency(Frequency(3, interval_type::days));
repeater1.set_next_date(date(2012, 5, 30));
dj.push_repeater(repeater1);
dj.save();
CHECK_EQUAL(repeater1.next_date(), date(2012, 5, 30));
CHECK_EQUAL(repeater1.next_date(0), date(2012, 5, 30));
CHECK_EQUAL(repeater1.next_date(2), date(2012, 6, 5));
CHECK_EQUAL(repeater1.next_date(1), date(2012, 6, 2));
Repeater repeater2(dbc);
repeater2.set_frequency(Frequency(2, interval_type::weeks));
repeater2.set_next_date(date(2012, 12, 31));
dj.push_repeater(repeater2);
dj.save();
CHECK_EQUAL(repeater2.next_date(2), date(2013, 1, 28));
CHECK_EQUAL(repeater2.next_date(1), date(2013, 1, 14));
Repeater repeater3(dbc);
Repeater3.set_frequency(Frequency(1, interval_type::months));
repeater3.set_next_date(date(2014, 9, 20));
CHECK_EQUAL(repeater3.next_date(5), date(2015, 2, 20));
Repeater repeater4(dbc);
repeater4.set_frequency(Frequency(1, interval_type::month_ends));
repeater4.set_next_date(date(1996, 1, 31));
CHECK_EQUAL(repeater4.next_date(), date(1996, 1, 31));
CHECK_EQUAL(repeater4.next_date(1), date(1996, 2, 29));
CHECK_EQUAL(repeater4.next_date(6), date(1996, 7, 31));
CHECK_EQUAL(repeater4.next_date(8), date(1996, 9, 30));
CHECK_EQUAL(repeater4.next_date(13), date(1997, 2, 28));
Repeater repeater5(dbc);
repeater5.set_frequency(Frequency(1, interval_type::days));
repeater5.set_next_date(date(1900, 2, 27));
CHECK_EQUAL(repeater5.next_date(1), date(1900, 2, 28));
CHECK_EQUAL(repeater5.next_date(2), date(1900, 3, 1));
Repeater repeater6(dbc);
repeater6.set_frequency(Frequency(12, interval_type::month_ends));
repeater6.set_next_date(date(1999, 2, 28));
CHECK_EQUAL(repeater6.next_date(1), date(2000, 2, 29));
Repeater repeater1b(dbc, 1);
CHECK_EQUAL(repeater1b.next_date(), date(2012, 5, 30));
CHECK_EQUAL(repeater1b.next_date(1), date(2012, 6, 2));
}
TEST_FIXTURE(TestFixture, test_repeater_firings_till)
{
PhatbooksDatabaseConnection& dbc = *pdbc;
Repeater repeater1(dbc);
repeater1.set_frequency(Frequency(5, interval_type::days));
repeater1.set_next_date(date(2000, 5, 3));
shared_ptr<vector<date> > firings1 =
repeater1.firings_till(date(1999, 5, 2));
CHECK(firings1->empty());
firings1 = repeater1.firings_till(date(2000, 5, 4));
CHECK_EQUAL(firings1->size(), 1);
CHECK_EQUAL((*firings1)[0], date(2000, 5, 3));
firings1 = repeater1.firings_till(date(2000, 5, 2));
CHECK(firings1->empty());
firings1 = repeater1.firings_till(date(2000, 5, 3));
CHECK_EQUAL(firings1->size(), 1);
CHECK_EQUAL((*firings1)[0], date(2000, 5, 3));
firings1 = repeater1.firings_till(date(2000, 5, 20));
CHECK_EQUAL(firings1->size(), 4);
CHECK_EQUAL((*firings1)[0], date(2000, 5, 3));
CHECK_EQUAL((*firings1)[1], date(2000, 5, 8));
CHECK_EQUAL((*firings1)[2], date(2000, 5, 13));
CHECK_EQUAL((*firings1)[3], date(2000, 5, 18));
Repeater repeater2(dbc);
repeater2.set_frequency(Frequency(3, interval_type::month_ends));
repeater2.set_next_date(date(2012, 12, 31));
shared_ptr<vector<date> > firings2;
firings2 = repeater2.firings_till(date(2012, 12, 30));
CHECK(firings2->empty());
firings2 = repeater2.firings_till(date(2013, 2, 28));
CHECK_EQUAL(firings2->size(), 1);
CHECK_EQUAL((*firings2)[0], date(2012, 12, 31));
firings2 = repeater2.firings_till(date(2013, 12, 31));
CHECK_EQUAL(firings2->size(), 5);
CHECK_EQUAL((*firings2)[4], date(2013, 12, 31));
CHECK_EQUAL((*firings2)[3], date(2013, 9, 30));
CHECK_EQUAL((*firings2)[2], date(2013, 6, 30));
CHECK_EQUAL((*firings2)[1], date(2013, 3, 31));
CHECK_EQUAL((*firings2)[0], date(2012, 12, 31));
}
TEST_FIXTURE(TestFixture, test_repeater_fire_next)
{
PhatbooksDatabaseConnection& dbc = *pdbc;
DraftJournal dj1(dbc);
dj1.set_whether_actual(true);
dj1.set_comment("journal to test repeater");
dj1.set_name(BString("Test")); // BString is optional
Entry entry1a(dbc);
entry1a.set_account(Account(dbc, "cash"));
entry1a.set_comment(BString("Test entry")); // BString is optional
entry1a.set_amount(Decimal("-1090.95"));
entry1a.set_whether_reconciled(false);
dj1.push_entry(entry1a);
Entry entry1b(dbc);
entry1b.set_account(Account(dbc, "food"));
entry1b.set_comment("Test entry");
entry1b.set_amount(Decimal("1090.95"));
entry1b.set_whether_reconciled(false);
dj1.push_entry(entry1b);
Repeater repeater1(dbc);
repeater1.set_frequency(Frequency(2, interval_type::weeks));
repeater1.set_next_date(date(2012, 7, 30));
dj1.push_repeater(repeater1);
dj1.save();
Repeater repeater1b(dbc, 1);
OrdinaryJournal oj1b = repeater1b.fire_next();
CHECK_EQUAL(oj1b.comment(), "journal to test repeater");
CHECK_EQUAL(oj1b.comment(), BString("journal to test repeater"));
CHECK_EQUAL(oj1b.date(), date(2012, 7, 30));
CHECK_EQUAL(repeater1.next_date(), date(2012, 8, 13));
OrdinaryJournal oj1c(dbc, 2);
CHECK_EQUAL(oj1c.date(), date(2012, 7, 30));
CHECK_EQUAL(oj1c.comment(), "journal to test repeater");
CHECK_EQUAL(oj1c.entries().size(), 2);
repeater1b.fire_next();
repeater1b.fire_next();
OrdinaryJournal oj3(dbc, 3);
OrdinaryJournal oj4(dbc, 4);
CHECK_EQUAL(oj3.date(), date(2012, 8, 13));
CHECK_EQUAL(oj4.date(), date(2012, 8, 27));
CHECK_EQUAL(oj4.id(), 4);
CHECK_EQUAL(oj3.comment(), oj4.comment());
vector<Entry>::const_iterator it3 = ++oj3.entries().begin();
vector<Entry>::const_iterator it4 = ++oj4.entries().begin();
CHECK_EQUAL(it3->amount(), it4->amount());
}
TEST_FIXTURE(TestFixture, test_repeater_frequency_phrase)
{
PhatbooksDatabaseConnection& dbc = *pdbc;
Repeater repeater1(dbc);
repeater1.set_frequency(Frequency(1, interval_type::days));
CHECK_EQUAL(frequency_description(repeater1), "every day");
CHECK(typeid(frequency_description(repeater1)) == typeid(std::string));
CHECK_EQUAL(frequency_description(repeater1), BString("every day"));
Repeater repeater2(dbc);
repeater2.set_frequency(Frequency(12, interval_type::days));
CHECK_EQUAL(frequency_description(repeater2), "every 12 days");
Repeater repeater3(dbc);
repeater3.set_frequency(Frequency(1, interval_type::weeks));
CHECK_EQUAL(frequency_description(repeater3), "every week");
Repeater repeater4(dbc);
repeater4.set_frequency(Frequency(2, interval_type::weeks));
CHECK_EQUAL(frequency_description(repeater4), "every 2 weeks");
Repeater repeater5(dbc);
repeater5.set_frequency(Frequency(3, interval_type::months));
CHECK_EQUAL(frequency_description(repeater5), "every 3 months");
Repeater repeater6(dbc);
repeater6.set_frequency(Frequency(1, interval_type::months));
CHECK_EQUAL(frequency_description(repeater6), "every month");
Repeater repeater7(dbc);
repeater7.set_frequency(Frequency(12, interval_type::months));
CHECK_EQUAL(frequency_description(repeater7), "every 12 months");
Repeater repeater8(dbc);
repeater8.set_frequency(Frequency(1, interval_type::month_ends));
CHECK_EQUAL
( frequency_description(repeater8),
"every month, on the last day of the month"
);
Repeater repeater9(dbc);
repeater9.set_frequency(Frequency(10, interval_type::month_ends));
CHECK_EQUAL
( frequency_description(repeater9),
"every 10 months, on the last day of the month"
);
CHECK_EQUAL
( frequency_description(repeater9),
BString("every 10 months, on the last day of the month")
);
}
} // namespace test
} // namespace phatbooks
<|endoftext|>
|
<commit_before>#include <OpenCL/opencl.h>
#define PV_USE_OPENCL
#include "../src/arch/opencl/CLDevice.hpp"
#include "../src/arch/opencl/CLKernel.hpp"
#include "../src/arch/opencl/CLBuffer.hpp"
#include "../src/utils/Timer.hpp"
#include "../src/utils/cl_random.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#define DEVICE 1
#define NX 256
#define NY 256
#define NXL 16
#define NYL 8
int check_results(uint4 * rnd_state, uint4 * rnd_state2, int count);
void c_rand(uint4 * rnd_state, int count);
int main(int argc, char * argv[])
{
unsigned int nxl, nyl;
PV::Timer timer;
int argid = 0;
int query = 0;
int device = DEVICE;
int status = CL_SUCCESS;
int nWarm = 10, nLoops = 100;
if (argc > 1) {
device = atoi(argv[1]);
}
PV::CLKernel * kernel;
PV::CLDevice * cld = new PV::CLDevice(device);
// query and print information about the devices found
//
if (query) cld->query_device_info();
if (device == 0) {
nxl = NXL;
nyl = NYL;
}
else {
nxl = 1;
nyl = 1;
}
kernel = cld->createKernel("test_cl_random.cl", "cl_rand");
const size_t mem_size = NX*NY*sizeof(uint4);
uint4 * rnd_state = cl_random_init(NX*NY);
uint4 * rnd_state2 = cl_random_init(NX*NY);
assert(rnd_state != NULL);
assert(rnd_state2 != NULL);
// create device buffer
//
PV::CLBuffer * d_rnd_state = cld->createBuffer(CL_MEM_COPY_HOST_PTR, mem_size, rnd_state);
status |= kernel->setKernelArg(argid++, NX);
status |= kernel->setKernelArg(argid++, NY);
status |= kernel->setKernelArg(argid++, 1);
status |= kernel->setKernelArg(argid++, 0);
status |= kernel->setKernelArg(argid++, d_rnd_state);
printf("Executing on device...");
kernel->run(NX*NY, nxl*nyl);
// Check results for accuracy
//
printf("\nChecking results...");
d_rnd_state->copyFromDevice();
status = check_results(rnd_state, rnd_state2, NX*NY);
if (status != CL_SUCCESS) {
exit(status);
}
printf(" CORRECT\n");
for (int n = 0; n < nWarm; n++) {
kernel->run(NX*NY, nxl*nyl);
}
printf("Timing %d loops on device... ", nLoops);
timer.start();
for (int n = 0; n < nLoops; n++) {
kernel->run(NX*NY, nxl*nyl);
}
status |= kernel->finish();
timer.stop();
timer.elapsed_time();
printf("Timing %d loops on host..... ", nLoops);
timer.start();
for (int n = 0; n < nLoops; n++) {
c_rand(rnd_state2, NX*NY);
}
timer.stop();
timer.elapsed_time();
// Shutdown and cleanup
//
// clReleaseMemObject(d_rnd_state);
delete cld;
printf("Finished...\n");
return status;
}
int check_results(uint4 * rnd_state, uint4 * rnd_state2, int count)
{
uint4 state;
for (int k = 0; k < count; k++) {
state = cl_random_state(rnd_state2[k]);
if (state.s0 != rnd_state[k].s0) {
printf("check_results: results differ at k==%d, rnd_state==%d, rnd_state2==%d\n",
k, state.s0, rnd_state[k].s0);
return 1;
}
}
return 0;
}
void c_rand(uint4 * rnd_state, int count)
{
for (int k = 0; k < count; k++) {
rnd_state[k] = cl_random_state(rnd_state[k]);
}
}
<commit_msg>Moved test_cl_random.cl to tests/kernels directory.<commit_after>#include <OpenCL/opencl.h>
#define PV_USE_OPENCL
#include "../src/arch/opencl/CLDevice.hpp"
#include "../src/arch/opencl/CLKernel.hpp"
#include "../src/arch/opencl/CLBuffer.hpp"
#include "../src/utils/Timer.hpp"
#include "../src/utils/cl_random.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#define DEVICE 1
#define NX 256
#define NY 256
#define NXL 16
#define NYL 8
int check_results(uint4 * rnd_state, uint4 * rnd_state2, int count);
void c_rand(uint4 * rnd_state, int count);
int main(int argc, char * argv[])
{
unsigned int nxl, nyl;
PV::Timer timer;
int argid = 0;
int query = 0;
int device = DEVICE;
int status = CL_SUCCESS;
int nWarm = 10, nLoops = 100;
if (argc > 1) {
device = atoi(argv[1]);
}
PV::CLKernel * kernel;
PV::CLDevice * cld = new PV::CLDevice(device);
// query and print information about the devices found
//
if (query) cld->query_device_info();
if (device == 0) {
nxl = NXL;
nyl = NYL;
}
else {
nxl = 1;
nyl = 1;
}
kernel = cld->createKernel("kernels/test_cl_random.cl", "cl_rand");
const size_t mem_size = NX*NY*sizeof(uint4);
uint4 * rnd_state = cl_random_init(NX*NY);
uint4 * rnd_state2 = cl_random_init(NX*NY);
assert(rnd_state != NULL);
assert(rnd_state2 != NULL);
// create device buffer
//
PV::CLBuffer * d_rnd_state = cld->createBuffer(CL_MEM_COPY_HOST_PTR, mem_size, rnd_state);
status |= kernel->setKernelArg(argid++, NX);
status |= kernel->setKernelArg(argid++, NY);
status |= kernel->setKernelArg(argid++, 1);
status |= kernel->setKernelArg(argid++, 0);
status |= kernel->setKernelArg(argid++, d_rnd_state);
printf("Executing on device...");
kernel->run(NX*NY, nxl*nyl);
// Check results for accuracy
//
printf("\nChecking results...");
d_rnd_state->copyFromDevice();
status = check_results(rnd_state, rnd_state2, NX*NY);
if (status != CL_SUCCESS) {
exit(status);
}
printf(" CORRECT\n");
for (int n = 0; n < nWarm; n++) {
kernel->run(NX*NY, nxl*nyl);
}
printf("Timing %d loops on device... ", nLoops);
timer.start();
for (int n = 0; n < nLoops; n++) {
kernel->run(NX*NY, nxl*nyl);
}
status |= kernel->finish();
timer.stop();
timer.elapsed_time();
printf("Timing %d loops on host..... ", nLoops);
timer.start();
for (int n = 0; n < nLoops; n++) {
c_rand(rnd_state2, NX*NY);
}
timer.stop();
timer.elapsed_time();
// Shutdown and cleanup
//
// clReleaseMemObject(d_rnd_state);
delete cld;
printf("Finished...\n");
return status;
}
int check_results(uint4 * rnd_state, uint4 * rnd_state2, int count)
{
uint4 state;
for (int k = 0; k < count; k++) {
state = cl_random_state(rnd_state2[k]);
if (state.s0 != rnd_state[k].s0) {
printf("check_results: results differ at k==%d, rnd_state==%d, rnd_state2==%d\n",
k, state.s0, rnd_state[k].s0);
return 1;
}
}
return 0;
}
void c_rand(uint4 * rnd_state, int count)
{
for (int k = 0; k < count; k++) {
rnd_state[k] = cl_random_state(rnd_state[k]);
}
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.