text
stringlengths 54
60.6k
|
---|
<commit_before><?hh //strict
/**
* This file is part of hhpack\performance.
*
* (c) Noritaka Horio <holy.shared.design@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace hhpack\performance\result;
use hhpack\performance\WatchedResult;
use ConstMapAccess;
final class ComplexResult implements WatchedResult<ImmMap<string, num>>, ConstMapAccess<string, WatchedResult<num>>
{
private ImmMap<string, WatchedResult<num>> $watchedResult;
public function __construct(
KeyedTraversable<string, WatchedResult<num>> $results = []
)
{
$watchedResult = Map {};
foreach ($results as $key => $value) {
$watchedResult->set($key, $value);
}
$this->watchedResult = $watchedResult->toImmMap();
}
<<__Memoize>>
public function first() : ImmMap<string, num>
{
return $this->watchedResult->map(($result) ==> $result->first());
}
<<__Memoize>>
public function last() : ImmMap<string, num>
{
return $this->watchedResult->map(($result) ==> $result->last());
}
<<__Memoize>>
public function value() : ImmMap<string, num>
{
return $this->toImmMap();
}
public function mapWithKey<Tu>((function(string,WatchedResult<num>):Tu) $mapper) : ImmMap<string, Tu>
{
return $this->watchedResult->mapWithKey($mapper);
}
public function contains<Tu super string>(Tu $m) : bool
{
return $this->watchedResult->contains($m);
}
public function at(string $k) : WatchedResult<num>
{
return $this->watchedResult->at($k);
}
public function get(string $k) : ?WatchedResult<num>
{
return $this->watchedResult->get($k);
}
public function containsKey<Tu super string>(Tu $k): bool
{
return $this->watchedResult->containsKey($k);
}
public function toImmMap() : ImmMap<string, num>
{
return $this->watchedResult->map(($result) ==> $result->value());
}
}
<commit_msg>comment out for ConstMapAccess<commit_after><?hh //strict
/**
* This file is part of hhpack\performance.
*
* (c) Noritaka Horio <holy.shared.design@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace hhpack\performance\result;
use hhpack\performance\WatchedResult;
// Do not use because the error occurs at runtime.
//
// see https://github.com/hhvm/user-documentation/issues/261
// https://github.com/facebook/hhvm/issues/6758
// use ConstMapAccess;
final class ComplexResult implements WatchedResult<ImmMap<string, num>> //, ConstMapAccess<string, WatchedResult<num>>
{
private ImmMap<string, WatchedResult<num>> $watchedResult;
public function __construct(
KeyedTraversable<string, WatchedResult<num>> $results = []
)
{
$watchedResult = Map {};
foreach ($results as $key => $value) {
$watchedResult->set($key, $value);
}
$this->watchedResult = $watchedResult->toImmMap();
}
<<__Memoize>>
public function first() : ImmMap<string, num>
{
return $this->watchedResult->map(($result) ==> $result->first());
}
<<__Memoize>>
public function last() : ImmMap<string, num>
{
return $this->watchedResult->map(($result) ==> $result->last());
}
<<__Memoize>>
public function value() : ImmMap<string, num>
{
return $this->toImmMap();
}
public function mapWithKey<Tu>((function(string,WatchedResult<num>):Tu) $mapper) : ImmMap<string, Tu>
{
return $this->watchedResult->mapWithKey($mapper);
}
public function contains<Tu super string>(Tu $m) : bool
{
return $this->watchedResult->contains($m);
}
public function at(string $k) : WatchedResult<num>
{
return $this->watchedResult->at($k);
}
public function get(string $k) : ?WatchedResult<num>
{
return $this->watchedResult->get($k);
}
public function containsKey<Tu super string>(Tu $k): bool
{
return $this->watchedResult->containsKey($k);
}
public function toImmMap() : ImmMap<string, num>
{
return $this->watchedResult->map(($result) ==> $result->value());
}
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2016-2017 INRA
*
* 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.
*/
#ifndef INRA_EFYj_UTILS_HPP
#define INRA_EFYj_UTILS_HPP
#include <algorithm>
#include <functional>
#include <limits>
#include <string>
#include <vector>
#include <fmt/format.h>
#include <efyj/efyj.hpp>
#if (defined(__i386__) || defined(__x86_64__)) && defined(__GNUC__) && \
__GNUC__ >= 2
#define efyj_breakpoint() \
do { \
__asm__ __volatile__("int $03"); \
} while (0)
#elif (defined(_MSC_VER) || defined(__DMC__)) && defined(_M_IX86)
#define efyj_breakpoint() \
do { \
__asm int 3h \
} while (0)
#elif defined(_MSC_VER)
#define efyj_breakpoint() \
do { \
__debugbreak(); \
} while (0)
#elif defined(__alpha__) && !defined(__osf__) && defined(__GNUC__) && \
__GNUC__ >= 2
#define efyj_breakpoint() \
do { \
__asm__ __volatile__("bpt"); \
} while (0)
#elif defined(__APPLE__)
#define efyj_breakpoint() \
do { \
__builtin_trap(); \
} while (0)
#else /* !__i386__ && !__alpha__ */
#define efyj_breakpoint() \
do { \
raise(SIGTRAP); \
} while (0)
#endif /* __i386__ */
#ifndef NDEBUG
#define efyj_bad_return(status__) \
do { \
efyj_breakpoint(); \
return status__; \
} while (0)
#define efyj_return_if_bad(expr__) \
do { \
auto status__ = (expr__); \
if (status__ != status::success) { \
efyj_breakpoint(); \
return status__; \
} \
} while (0)
#define efyj_return_if_fail(expr__, status__) \
do { \
if (!(expr__)) { \
efyj_breakpoint(); \
return status__; \
} \
} while (0)
#else
#define efyj_bad_return(status__) \
do { \
return status__; \
} while (0)
#define efyj_return_if_bad(expr__) \
do { \
auto status__ = (expr__); \
if (status__ != status::success) { \
return status__; \
} \
} while (0)
#define efyj_return_if_fail(expr__, status__) \
do { \
if (!(expr__)) { \
return status__; \
} \
} while (0)
#endif
#if defined(__GNUC__)
#define efyj_unreachable() __builtin_unreachable();
#elif defined(_MSC_VER)
#define efyj_unreachable() __assume(0)
#else
#define efyj_unreachable()
#endif
namespace efyj {
/** Casts nonnegative integer to unsigned.
*/
template<typename Integer>
constexpr typename std::make_unsigned<Integer>::type
to_unsigned(Integer value)
{
assert(value >= 0);
return static_cast<typename std::make_unsigned<Integer>::type>(value);
}
/**
* @brief Get a sub-string without any @c std::isspace characters at left.
*
* @param s The string-view to clean up.
*
* @return An update sub-string or the same string-view.
*/
inline std::string_view
left_trim(std::string_view s) noexcept
{
auto found = s.find_first_not_of(" \t\n\v\f\r");
if (found == std::string::npos)
return {};
return s.substr(found, std::string::npos);
}
/**
* @brief Get a sub-string without any @c std::isspace characters at right.
*
* @param s The string-view to clean up.
*
* @return An update sub-string or the same string-view.
*/
inline std::string_view
right_trim(std::string_view s) noexcept
{
auto found = s.find_last_not_of(" \t\n\v\f\r");
if (found == std::string::npos)
return {};
return s.substr(0, found + 1);
}
/**
* @brief Get a sub-string without any @c std::isspace characters at left
* and right
*
* @param s The string-view to clean up.
*
* @return An update sub-string or the same string-view.
*/
inline std::string_view
trim(std::string_view s) noexcept
{
return left_trim(right_trim(s));
}
/**
* @brief Compute the length of the @c container.
* @details Return the @c size provided by the @c C::size() but cast it into
* a
* @c int. This is a specific baryonyx function, we know that number of
* variables and constraints are lower than the @c INT_MAX value.
*
* @code
* std::vector<int> v(z);
*
* for (int i = 0, e = length(v); i != e; ++i)
* ...
* @endcode
*
* @param c The container to request to size.
* @tparam T The of container value (must provide a @c size() member).
*/
template<class C>
constexpr int
length(const C& c) noexcept
{
return static_cast<int>(c.size());
}
/**
* @brief Compute the length of the C array.
* @details Return the size of the C array but cast it into a @c int. This
* is a specific baryonyx function, we know that number of variables and
* constraints are lower than the @c int max value (INT_MAX).
*
* @code
* int v[150];
* for (int i = 0, e = length(v); i != e; ++i)
* ...
* @endcode
*
* @param v The container to return size.
* @tparam T The type of the C array.
* @tparam N The size of the C array.
*/
template<class T, size_t N>
constexpr int
length(const T (&array)[N]) noexcept
{
(void)array;
return static_cast<int>(N);
}
inline constexpr std::size_t
max_value(int need, size_t real) noexcept;
struct scope_exit
{
scope_exit(std::function<void(void)> fct)
: fct(fct)
{}
~scope_exit()
{
fct();
}
std::function<void(void)> fct;
};
void
tokenize(const std::string& str,
std::vector<std::string>& tokens,
const std::string& delim,
bool trimEmpty);
inline constexpr size_t
max_value(int need, size_t real) noexcept
{
return need <= 0 ? real : std::min(static_cast<size_t>(need), real);
}
inline void
tokenize(const std::string& str,
std::vector<std::string>& tokens,
const std::string& delim,
bool trimEmpty)
{
tokens.clear();
std::string::size_type pos, lastPos = 0, length = str.length();
using value_type = typename std::vector<std::string>::value_type;
using size_type = typename std::vector<std::string>::size_type;
while (lastPos < length + 1) {
pos = str.find_first_of(delim, lastPos);
if (pos == std::string::npos) {
pos = length;
}
if (pos != lastPos || !trimEmpty)
tokens.push_back(
value_type(str.data() + lastPos, (size_type)pos - lastPos));
lastPos = pos + 1;
}
}
/**
* @brief Return true if @c Source can be casted into @c Target integer
* type.
* @details Check if the integer type @c Source is castable into @c Target.
*
* @param arg A value.
* @tparam Source An integer type.
* @tparam Target An integer type.
* @return true if @c static_cast<Target>(Source) is valid.
*/
template<typename Target, typename Source>
inline bool
is_numeric_castable(Source arg)
{
static_assert(std::is_integral<Source>::value, "Integer required.");
static_assert(std::is_integral<Target>::value, "Integer required.");
using arg_traits = std::numeric_limits<Source>;
using result_traits = std::numeric_limits<Target>;
if (result_traits::digits == arg_traits::digits &&
result_traits::is_signed == arg_traits::is_signed)
return true;
if (result_traits::digits > arg_traits::digits)
return result_traits::is_signed || arg >= 0;
if (arg_traits::is_signed &&
arg < static_cast<Source>(result_traits::min()))
return false;
return arg <= static_cast<Source>(result_traits::max());
}
class output_file
{
private:
std::FILE* file = nullptr;
public:
output_file() noexcept = default;
output_file(const char* file_path) noexcept
{
#ifdef _WIN32
if (fopen_s(&file, file_path, "w"))
file = nullptr;
#else
file = std::fopen(file_path, "w");
#endif
}
output_file(output_file&& other) noexcept
: file(other.file)
{
other.file = nullptr;
}
output_file& operator=(output_file&& other) noexcept
{
if (file) {
std::fclose(file);
file = nullptr;
}
file = other.file;
other.file = nullptr;
return *this;
}
output_file(const output_file&) = delete;
output_file& operator=(const output_file&) = delete;
std::FILE* get() const noexcept
{
return file;
}
bool is_open() const noexcept
{
return file != nullptr;
}
~output_file()
{
if (file)
std::fclose(file);
}
void vprint(const std::string_view format,
const fmt::format_args args) const
{
fmt::vprint(file, format, args);
}
template<typename... Args>
void print(const std::string_view format, const Args&... args) const
{
vprint(format, fmt::make_format_args(args...));
}
};
class input_file
{
private:
std::FILE* file = nullptr;
public:
input_file() noexcept = default;
input_file(const char* file_path) noexcept
{
#ifdef _WIN32
if (fopen_s(&file, file_path, "r"))
file = nullptr;
#else
file = std::fopen(file_path, "r");
#endif
}
input_file(input_file&& other) noexcept
: file(other.file)
{
other.file = nullptr;
}
input_file& operator=(input_file&& other) noexcept
{
if (file) {
std::fclose(file);
file = nullptr;
}
file = other.file;
other.file = nullptr;
return *this;
}
input_file(const input_file&) = delete;
input_file& operator=(const input_file&) = delete;
std::FILE* get() const noexcept
{
return file;
}
bool is_open() const noexcept
{
return file != nullptr;
}
~input_file()
{
if (file)
std::fclose(file);
}
};
} // namespace efyj
#endif
<commit_msg>utils: use if-constexpr feature in numeric cast<commit_after>/* Copyright (C) 2016-2017 INRA
*
* 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.
*/
#ifndef INRA_EFYj_UTILS_HPP
#define INRA_EFYj_UTILS_HPP
#include <algorithm>
#include <functional>
#include <limits>
#include <string>
#include <vector>
#include <fmt/format.h>
#include <efyj/efyj.hpp>
#if (defined(__i386__) || defined(__x86_64__)) && defined(__GNUC__) && \
__GNUC__ >= 2
#define efyj_breakpoint() \
do { \
__asm__ __volatile__("int $03"); \
} while (0)
#elif (defined(_MSC_VER) || defined(__DMC__)) && defined(_M_IX86)
#define efyj_breakpoint() \
do { \
__asm int 3h \
} while (0)
#elif defined(_MSC_VER)
#define efyj_breakpoint() \
do { \
__debugbreak(); \
} while (0)
#elif defined(__alpha__) && !defined(__osf__) && defined(__GNUC__) && \
__GNUC__ >= 2
#define efyj_breakpoint() \
do { \
__asm__ __volatile__("bpt"); \
} while (0)
#elif defined(__APPLE__)
#define efyj_breakpoint() \
do { \
__builtin_trap(); \
} while (0)
#else /* !__i386__ && !__alpha__ */
#define efyj_breakpoint() \
do { \
raise(SIGTRAP); \
} while (0)
#endif /* __i386__ */
#ifndef NDEBUG
#define efyj_bad_return(status__) \
do { \
efyj_breakpoint(); \
return status__; \
} while (0)
#define efyj_return_if_bad(expr__) \
do { \
auto status__ = (expr__); \
if (status__ != status::success) { \
efyj_breakpoint(); \
return status__; \
} \
} while (0)
#define efyj_return_if_fail(expr__, status__) \
do { \
if (!(expr__)) { \
efyj_breakpoint(); \
return status__; \
} \
} while (0)
#else
#define efyj_bad_return(status__) \
do { \
return status__; \
} while (0)
#define efyj_return_if_bad(expr__) \
do { \
auto status__ = (expr__); \
if (status__ != status::success) { \
return status__; \
} \
} while (0)
#define efyj_return_if_fail(expr__, status__) \
do { \
if (!(expr__)) { \
return status__; \
} \
} while (0)
#endif
#if defined(__GNUC__)
#define efyj_unreachable() __builtin_unreachable();
#elif defined(_MSC_VER)
#define efyj_unreachable() __assume(0)
#else
#define efyj_unreachable()
#endif
namespace efyj {
/** Casts nonnegative integer to unsigned.
*/
template<typename Integer>
constexpr typename std::make_unsigned<Integer>::type
to_unsigned(Integer value)
{
assert(value >= 0);
return static_cast<typename std::make_unsigned<Integer>::type>(value);
}
/**
* @brief Get a sub-string without any @c std::isspace characters at left.
*
* @param s The string-view to clean up.
*
* @return An update sub-string or the same string-view.
*/
inline std::string_view
left_trim(std::string_view s) noexcept
{
auto found = s.find_first_not_of(" \t\n\v\f\r");
if (found == std::string::npos)
return {};
return s.substr(found, std::string::npos);
}
/**
* @brief Get a sub-string without any @c std::isspace characters at right.
*
* @param s The string-view to clean up.
*
* @return An update sub-string or the same string-view.
*/
inline std::string_view
right_trim(std::string_view s) noexcept
{
auto found = s.find_last_not_of(" \t\n\v\f\r");
if (found == std::string::npos)
return {};
return s.substr(0, found + 1);
}
/**
* @brief Get a sub-string without any @c std::isspace characters at left
* and right
*
* @param s The string-view to clean up.
*
* @return An update sub-string or the same string-view.
*/
inline std::string_view
trim(std::string_view s) noexcept
{
return left_trim(right_trim(s));
}
/**
* @brief Compute the length of the @c container.
* @details Return the @c size provided by the @c C::size() but cast it into
* a
* @c int. This is a specific baryonyx function, we know that number of
* variables and constraints are lower than the @c INT_MAX value.
*
* @code
* std::vector<int> v(z);
*
* for (int i = 0, e = length(v); i != e; ++i)
* ...
* @endcode
*
* @param c The container to request to size.
* @tparam T The of container value (must provide a @c size() member).
*/
template<class C>
constexpr int
length(const C& c) noexcept
{
return static_cast<int>(c.size());
}
/**
* @brief Compute the length of the C array.
* @details Return the size of the C array but cast it into a @c int. This
* is a specific baryonyx function, we know that number of variables and
* constraints are lower than the @c int max value (INT_MAX).
*
* @code
* int v[150];
* for (int i = 0, e = length(v); i != e; ++i)
* ...
* @endcode
*
* @param v The container to return size.
* @tparam T The type of the C array.
* @tparam N The size of the C array.
*/
template<class T, size_t N>
constexpr int
length(const T (&array)[N]) noexcept
{
(void)array;
return static_cast<int>(N);
}
inline constexpr std::size_t
max_value(int need, size_t real) noexcept;
struct scope_exit
{
scope_exit(std::function<void(void)> fct)
: fct(fct)
{}
~scope_exit()
{
fct();
}
std::function<void(void)> fct;
};
void
tokenize(const std::string& str,
std::vector<std::string>& tokens,
const std::string& delim,
bool trimEmpty);
inline constexpr size_t
max_value(int need, size_t real) noexcept
{
return need <= 0 ? real : std::min(static_cast<size_t>(need), real);
}
inline void
tokenize(const std::string& str,
std::vector<std::string>& tokens,
const std::string& delim,
bool trimEmpty)
{
tokens.clear();
std::string::size_type pos, lastPos = 0, length = str.length();
using value_type = typename std::vector<std::string>::value_type;
using size_type = typename std::vector<std::string>::size_type;
while (lastPos < length + 1) {
pos = str.find_first_of(delim, lastPos);
if (pos == std::string::npos) {
pos = length;
}
if (pos != lastPos || !trimEmpty)
tokens.push_back(
value_type(str.data() + lastPos, (size_type)pos - lastPos));
lastPos = pos + 1;
}
}
/**
* @brief Return true if @c Source can be casted into @c Target integer
* type.
* @details Check if the integer type @c Source is castable into @c Target.
*
* @param arg A value.
* @tparam Source An integer type.
* @tparam Target An integer type.
* @return true if @c static_cast<Target>(Source) is valid.
*/
template<typename Target, typename Source>
inline bool
is_numeric_castable(Source arg)
{
static_assert(std::is_integral<Source>::value, "Integer required.");
static_assert(std::is_integral<Target>::value, "Integer required.");
if constexpr (std::is_same_v<Target, Source>)
return true;
using arg_traits = std::numeric_limits<Source>;
using result_traits = std::numeric_limits<Target>;
if (result_traits::digits > arg_traits::digits)
return result_traits::is_signed || arg >= 0;
if (arg_traits::is_signed &&
arg < static_cast<Source>(result_traits::min()))
return false;
return arg <= static_cast<Source>(result_traits::max());
}
class output_file
{
private:
std::FILE* file = nullptr;
public:
output_file() noexcept = default;
output_file(const char* file_path) noexcept
{
#ifdef _WIN32
if (fopen_s(&file, file_path, "w"))
file = nullptr;
#else
file = std::fopen(file_path, "w");
#endif
}
output_file(output_file&& other) noexcept
: file(other.file)
{
other.file = nullptr;
}
output_file& operator=(output_file&& other) noexcept
{
if (file) {
std::fclose(file);
file = nullptr;
}
file = other.file;
other.file = nullptr;
return *this;
}
output_file(const output_file&) = delete;
output_file& operator=(const output_file&) = delete;
std::FILE* get() const noexcept
{
return file;
}
bool is_open() const noexcept
{
return file != nullptr;
}
~output_file()
{
if (file)
std::fclose(file);
}
void vprint(const std::string_view format,
const fmt::format_args args) const
{
fmt::vprint(file, format, args);
}
template<typename... Args>
void print(const std::string_view format, const Args&... args) const
{
vprint(format, fmt::make_format_args(args...));
}
};
class input_file
{
private:
std::FILE* file = nullptr;
public:
input_file() noexcept = default;
input_file(const char* file_path) noexcept
{
#ifdef _WIN32
if (fopen_s(&file, file_path, "r"))
file = nullptr;
#else
file = std::fopen(file_path, "r");
#endif
}
input_file(input_file&& other) noexcept
: file(other.file)
{
other.file = nullptr;
}
input_file& operator=(input_file&& other) noexcept
{
if (file) {
std::fclose(file);
file = nullptr;
}
file = other.file;
other.file = nullptr;
return *this;
}
input_file(const input_file&) = delete;
input_file& operator=(const input_file&) = delete;
std::FILE* get() const noexcept
{
return file;
}
bool is_open() const noexcept
{
return file != nullptr;
}
~input_file()
{
if (file)
std::fclose(file);
}
};
} // namespace efyj
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include "secs/container.h"
using std::cout;
using std::endl;
int main() {
cout << "Hello world!" << endl;
return 0;
}<commit_msg>Adds simple benchmark<commit_after>#include <iostream>
#include <chrono>
#include "secs/container.h"
namespace chrono = std::chrono;
using std::cout;
using std::endl;
using std::make_unique;
using std::string;
using std::unique_ptr;
using std::vector;
using secs::Container;
struct Velocity {
float x = 0;
float y = 0;
Velocity(float x = 0, float y = 0)
: x(x), y(y)
{}
};
static const size_t COUNT = 10000;
template<typename F>
void benchmark(const string& label, F&& body) {
auto t0 = chrono::high_resolution_clock::now();
body();
auto t1 = chrono::high_resolution_clock::now();
cout << label
<< ": "
<< chrono::duration_cast<chrono::nanoseconds>(t1 - t0).count()
<< "ns\n";
}
static std::default_random_engine gen;
float random_number() {
std::uniform_real_distribution<float> dist(-1, 1);
return dist(gen);
}
float compute(Velocity& v) {
return v.x + v.y;
}
////////////////////////////////////////////////////////////////////////////////
void vector_of_values() {
vector<Velocity> inputs;
inputs.reserve(COUNT);
for (size_t i = 0; i < COUNT; ++i) {
inputs.emplace_back(random_number(), random_number());
}
vector<float> outputs;
outputs.reserve(COUNT);
benchmark("vector of values", [&]() {
for (auto& input : inputs) {
outputs.push_back(compute(input));
}
});
}
void vector_of_pointers() {
vector<unique_ptr<Velocity>> inputs;
inputs.reserve(COUNT);
for (size_t i = 0; i < COUNT; ++i) {
inputs.push_back(make_unique<Velocity>(random_number(), random_number()));
}
vector<float> outputs;
outputs.reserve(COUNT);
benchmark("vector of pointers", [&]() {
for (auto& input : inputs) {
outputs.push_back(compute(*input));
}
});
}
void container_with_entity() {
Container container;
for (size_t i = 0; i < COUNT; ++i) {
auto e = container.create();
e.create_component<Velocity>(random_number(), random_number());
}
vector<float> outputs;
outputs.reserve(COUNT);
benchmark("container iteration via entity", [&]() {
for (auto c : container.entities().need<Velocity>()) {
outputs.push_back(compute(*c.entity().component<Velocity>()));
}
});
}
void container_with_cursor() {
Container container;
for (size_t i = 0; i < COUNT; ++i) {
auto e = container.create();
e.create_component<Velocity>(random_number(), random_number());
}
vector<float> outputs;
outputs.reserve(COUNT);
benchmark("container iteration via cursor", [&]() {
for (auto c : container.entities().need<Velocity>()) {
outputs.push_back(compute(c.get<Velocity>()));
}
});
}
int main() {
vector_of_values();
vector_of_pointers();
container_with_entity();
container_with_cursor();
return 0;
}<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/////////////////////////////////////////////////////////////
// //
// Class to analyze ZDC data //
// //
/////////////////////////////////////////////////////////////
#include <TList.h>
#include <TH2F.h>
#include <TH1F.h>
#include <TFile.h>
#include <TString.h>
#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliVEvent.h"
#include "AliESD.h"
#include "AliESDEvent.h"
#include "AliESDHeader.h"
#include "AliESDInputHandler.h"
#include "AliESDZDC.h"
#include "AliMultiplicity.h"
#include "AliAODHandler.h"
#include "AliAODEvent.h"
#include "AliAODVertex.h"
#include "AliAODMCHeader.h"
#include "AliMCEventHandler.h"
#include "AliMCEvent.h"
#include "AliHeader.h"
#include "AliAODMCParticle.h"
#include "AliAnalysisTaskSE.h"
#include "AliGenEventHeader.h"
#include "AliGenHijingEventHeader.h"
#include "AliPhysicsSelectionTask.h"
#include "AliPhysicsSelection.h"
#include "AliBackgroundSelection.h"
#include "AliTriggerAnalysis.h"
#include "AliCentrality.h"
#include "AliAnalysisTaskZDC.h"
ClassImp(AliAnalysisTaskZDC)
//________________________________________________________________________
AliAnalysisTaskZDC::AliAnalysisTaskZDC():
AliAnalysisTaskSE(),
fDebug(0),
fIsMCInput(kFALSE),
fOutput(0x0),
fhTDCZNSum(0x0),
fhTDCZNDiff(0x0),
fhZNCSpectrum(0x0),
fhZNASpectrum(0x0),
fhZPCSpectrum(0x0),
fhZPASpectrum(0x0),
fhZEM1Spectrum(0x0),
fhZEM2Spectrum(0x0),
fhZNCpmc(0x0),
fhZNApmc(0x0),
fhZPCpmc(0x0),
fhZPApmc(0x0),
fhZNCCentroid(0x0),
fhZNACentroid(0x0),
fhZNCemd(0x0),
fhZNAemd(0x0),
fhPMCZNCemd(0x0),
fhPMCZNAemd(0x0),
fDebunch(0x0)
{
// Default constructor
}
//________________________________________________________________________
AliAnalysisTaskZDC::AliAnalysisTaskZDC(const char *name):
AliAnalysisTaskSE(name),
fDebug(0),
fIsMCInput(kFALSE),
fOutput(0x0),
fhTDCZNSum(0x0),
fhTDCZNDiff(0x0),
fhZNCSpectrum(0x0),
fhZNASpectrum(0x0),
fhZPCSpectrum(0x0),
fhZPASpectrum(0x0),
fhZEM1Spectrum(0x0),
fhZEM2Spectrum(0x0),
fhZNCpmc(0x0),
fhZNApmc(0x0),
fhZPCpmc(0x0),
fhZPApmc(0x0),
fhZNCCentroid(0x0),
fhZNACentroid(0x0),
fhZNCemd(0x0),
fhZNAemd(0x0),
fhPMCZNCemd(0x0),
fhPMCZNAemd(0x0),
fDebunch(0x0)
{
// Output slot #1 writes into a TList container
DefineOutput(1, TList::Class());
}
//________________________________________________________________________
AliAnalysisTaskZDC& AliAnalysisTaskZDC::operator=(const AliAnalysisTaskZDC& c)
{
//
// Assignment operator
//
if (this!=&c) {
AliAnalysisTaskSE::operator=(c);
}
return *this;
}
//________________________________________________________________________
AliAnalysisTaskZDC::AliAnalysisTaskZDC(const AliAnalysisTaskZDC& ana):
AliAnalysisTaskSE(ana),
fDebug(ana.fDebug),
fIsMCInput(ana.fIsMCInput),
fOutput(ana.fOutput),
fhTDCZNSum(ana.fhTDCZNSum),
fhTDCZNDiff(ana.fhTDCZNDiff),
fhZNCSpectrum(ana.fhZNCSpectrum),
fhZNASpectrum(ana.fhZNASpectrum),
fhZPCSpectrum(ana.fhZPCSpectrum),
fhZPASpectrum(ana.fhZPASpectrum),
fhZEM1Spectrum(ana.fhZEM1Spectrum),
fhZEM2Spectrum(ana.fhZEM2Spectrum),
fhZNCpmc(ana.fhZNCpmc),
fhZNApmc(ana.fhZNApmc),
fhZPCpmc(ana.fhZPCpmc),
fhZPApmc(ana.fhZPApmc),
fhZNCCentroid(ana.fhZNCCentroid),
fhZNACentroid(ana.fhZNACentroid),
fhZNCemd(ana.fhZNCemd),
fhZNAemd(ana.fhZNAemd),
fhPMCZNCemd(ana.fhPMCZNCemd),
fhPMCZNAemd(ana.fhPMCZNAemd),
fDebunch(ana.fDebunch)
{
//
// Copy Constructor
//
}
//________________________________________________________________________
AliAnalysisTaskZDC::~AliAnalysisTaskZDC()
{
// Destructor
if(fOutput && !AliAnalysisManager::GetAnalysisManager()->IsProofMode()){
delete fOutput; fOutput=0;
}
}
//________________________________________________________________________
void AliAnalysisTaskZDC::UserCreateOutputObjects()
{
// Create the output containers
fOutput = new TList;
fOutput->SetOwner();
//fOutput->SetName("output");
fhTDCZNSum = new TH1F("fhTDCZNSum","TDC_{ZNC}+TDC_{ZNA}",60,-30.,-30.);
fhTDCZNSum->GetXaxis()->SetTitle("TDC_{ZNC}+TDC_{ZNA} (ns)");
fOutput->Add(fhTDCZNSum);
fhTDCZNDiff = new TH1F("fhTDCZNDiff","TDC_{ZNC}-TDC_{ZNA}",60,-30.,30.);
fhTDCZNDiff->GetXaxis()->SetTitle("TDC_{ZNC}-TDC_{ZNA} (ns)");
fOutput->Add(fhTDCZNDiff);
fhZNCSpectrum = new TH1F("fhZNCSpectrum", "ZNC signal", 200,0., 140000.);
fOutput->Add(fhZNCSpectrum);
fhZNASpectrum = new TH1F("fhZNASpectrum", "ZNA signal", 200,0., 140000.) ;
fOutput->Add(fhZNASpectrum);
fhZPCSpectrum = new TH1F("fhZPCSpectrum", "ZPC signal", 200,0., 50000.) ;
fOutput->Add(fhZPCSpectrum);
fhZPASpectrum = new TH1F("fhZPASpectrum", "ZPA signal", 200,0., 50000.) ;
fOutput->Add(fhZPASpectrum);
fhZEM1Spectrum = new TH1F("fhZEM1Spectrum", "ZEM1 signal", 100,0., 2500.);
fOutput->Add(fhZEM1Spectrum);
fhZEM2Spectrum = new TH1F("fhZEM2Spectrum", "ZEM2 signal", 100,0., 2500.);
fOutput->Add(fhZEM2Spectrum);
fhZNCpmc = new TH1F("fhZNCpmc","ZNC PMC",200, 0., 160000.);
fOutput->Add(fhZNCpmc);
fhZNApmc = new TH1F("fhZNApmc","ZNA PMC",200, 0., 160000.);
fOutput->Add(fhZNApmc);
fhZPCpmc = new TH1F("fhZPCpmc","ZPC PMC",200, 0., 40000.);
fOutput->Add(fhZPCpmc);
fhZPApmc = new TH1F("fhZPApmc","ZPA PMC",200, 0., 40000.);
fOutput->Add(fhZPApmc);
fhZNCCentroid = new TH2F("fhZNCCentroid","Centroid over ZNC",70,-3.5,3.5,70,-3.5,3.5);
fOutput->Add(fhZNCCentroid);
fhZNACentroid = new TH2F("fhZNACentroid","Centroid over ZNA",70,-3.5,3.5,70,-3.5,3.5);
fOutput->Add(fhZNACentroid);
fhZNCemd = new TH1F("fhZNCemd","ZNC signal lg",200,0.,6000.);
fOutput->Add(fhZNCemd);
fhZNAemd = new TH1F("fhZNAemd","ZNA signal lg",200,0.,6000.);
fOutput->Add(fhZNAemd);
fhPMCZNCemd = new TH1F("fhPMCZNCemd","ZNC PMC lg",200, 10., 6000.);
fOutput->Add(fhPMCZNCemd);
fhPMCZNAemd = new TH1F("fhPMCZNAemd","ZNA PMC lg",200, 10., 6000.);
fOutput->Add(fhPMCZNAemd);
fDebunch = new TH2F("fDebunch","ZN TDC sum vs. diff", 120,-30,30,120,-30,-30);
fOutput->Add(fDebunch);
PostData(1, fOutput);
}
//________________________________________________________________________
void AliAnalysisTaskZDC::UserExec(Option_t */*option*/)
{
// Execute analysis for current event:
if(fDebug>1) printf(" **** AliAnalysisTaskZDC::UserExec() \n");
if (!InputEvent()) {
Printf("ERROR: InputEvent not available");
return;
}
AliESDEvent* esd = dynamic_cast<AliESDEvent*> (InputEvent());
if(!esd) return;
// Select PHYSICS events (type=7, for data)
if(!fIsMCInput && esd->GetEventType()!=7) return;
// ********* MC INFO *********************************
if(fIsMCInput){
AliMCEventHandler* eventHandler = dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler());
if (!eventHandler) {
Printf("ERROR: Could not retrieve MC event handler");
return;
}
AliMCEvent* mcEvent = eventHandler->MCEvent();
if (!mcEvent) {
Printf("ERROR: Could not retrieve MC event");
return;
}
}
// ****************************************************
AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();
AliESDZDC *esdZDC = esd->GetESDZDC();
if((((AliInputEventHandler*)(am->GetInputEventHandler()))->IsEventSelected())){
fhZNCSpectrum->Fill(esdZDC->GetZDCN1Energy());
fhZNASpectrum->Fill(esdZDC->GetZDCN2Energy());
fhZPCSpectrum->Fill(esdZDC->GetZDCP1Energy());
fhZPASpectrum->Fill(esdZDC->GetZDCP2Energy());
fhZEM1Spectrum->Fill(esdZDC->GetZDCEMEnergy(0)/8.);
fhZEM2Spectrum->Fill(esdZDC->GetZDCEMEnergy(1)/8.);
const Double_t * towZNC = esdZDC->GetZN1TowerEnergy();
const Double_t * towZPC = esdZDC->GetZP1TowerEnergy();
const Double_t * towZNA = esdZDC->GetZN2TowerEnergy();
const Double_t * towZPA = esdZDC->GetZP2TowerEnergy();
//
fhZNCpmc->Fill(towZNC[0]);
fhZNApmc->Fill(towZNA[0]);
fhZPCpmc->Fill(towZPC[0]);
fhZPApmc->Fill(towZPA[0]);
Double_t xyZNC[2]={-99.,-99.}, xyZNA[2]={-99.,-99.};
esdZDC->GetZNCentroidInPbPb(1380., xyZNC, xyZNA);
//esdZDC->GetZNCentroidInpp(xyZNC, xyZNA);
fhZNCCentroid->Fill(xyZNC[0], xyZNC[1]);
fhZNACentroid->Fill(xyZNA[0], xyZNA[1]);
const Double_t * towZNCLG = esdZDC->GetZN1TowerEnergyLR();
const Double_t * towZNALG = esdZDC->GetZN2TowerEnergyLR();
Double_t znclg=0., znalg=0.;
for(Int_t iq=0; iq<5; iq++){
znclg += towZNCLG[iq];
znalg += towZNALG[iq];
}
fhZNCemd->Fill(znclg/2.);
fhZNAemd->Fill(znalg/2.);
fhPMCZNCemd->Fill(towZNCLG[0]);
fhPMCZNAemd->Fill(towZNALG[0]);
}
Float_t tdcC=999., tdcA=999;
Float_t tdcSum=999., tdcDiff=999;
if(esdZDC->GetZDCTDCData(10,0)>1e-4){
tdcC = esdZDC->GetZDCTDCCorrected(10,0);
if(esdZDC->GetZDCTDCData(12,0)>1e-4){
tdcA = esdZDC->GetZDCTDCCorrected(12,0);
tdcSum = tdcC+tdcA;
tdcDiff = tdcC-tdcA;
}
}
//for(Int_t i=0; i<4; i++){
if(tdcSum!=999.) fhTDCZNSum->Fill(tdcSum);
if(tdcDiff!=999.)fhTDCZNDiff->Fill(tdcDiff);
if(tdcSum!=999. && tdcDiff!=999.) fDebunch->Fill(tdcDiff, tdcSum);
//}
PostData(1, fOutput);
}
//________________________________________________________________________
void AliAnalysisTaskZDC::Terminate(Option_t */*option*/)
{
// Terminate analysis
//
}
<commit_msg>Updating QA task<commit_after>/**************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/////////////////////////////////////////////////////////////
// //
// Class to analyze ZDC data //
// //
/////////////////////////////////////////////////////////////
#include <TList.h>
#include <TH2F.h>
#include <TH1F.h>
#include <TFile.h>
#include <TString.h>
#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliVEvent.h"
#include "AliESD.h"
#include "AliESDEvent.h"
#include "AliESDHeader.h"
#include "AliESDInputHandler.h"
#include "AliESDZDC.h"
#include "AliMultiplicity.h"
#include "AliAODHandler.h"
#include "AliAODEvent.h"
#include "AliAODVertex.h"
#include "AliAODMCHeader.h"
#include "AliMCEventHandler.h"
#include "AliMCEvent.h"
#include "AliHeader.h"
#include "AliAODMCParticle.h"
#include "AliAnalysisTaskSE.h"
#include "AliGenEventHeader.h"
#include "AliGenHijingEventHeader.h"
#include "AliPhysicsSelectionTask.h"
#include "AliPhysicsSelection.h"
#include "AliBackgroundSelection.h"
#include "AliTriggerAnalysis.h"
#include "AliCentrality.h"
#include "AliAnalysisTaskZDC.h"
ClassImp(AliAnalysisTaskZDC)
//________________________________________________________________________
AliAnalysisTaskZDC::AliAnalysisTaskZDC():
AliAnalysisTaskSE(),
fDebug(0),
fIsMCInput(kFALSE),
fOutput(0x0),
fhTDCZNSum(0x0),
fhTDCZNDiff(0x0),
fhZNCSpectrum(0x0),
fhZNASpectrum(0x0),
fhZPCSpectrum(0x0),
fhZPASpectrum(0x0),
fhZEM1Spectrum(0x0),
fhZEM2Spectrum(0x0),
fhZNCpmc(0x0),
fhZNApmc(0x0),
fhZPCpmc(0x0),
fhZPApmc(0x0),
fhZNCCentroid(0x0),
fhZNACentroid(0x0),
fhZNCemd(0x0),
fhZNAemd(0x0),
fhPMCZNCemd(0x0),
fhPMCZNAemd(0x0),
fDebunch(0x0)
{
// Default constructor
}
//________________________________________________________________________
AliAnalysisTaskZDC::AliAnalysisTaskZDC(const char *name):
AliAnalysisTaskSE(name),
fDebug(0),
fIsMCInput(kFALSE),
fOutput(0x0),
fhTDCZNSum(0x0),
fhTDCZNDiff(0x0),
fhZNCSpectrum(0x0),
fhZNASpectrum(0x0),
fhZPCSpectrum(0x0),
fhZPASpectrum(0x0),
fhZEM1Spectrum(0x0),
fhZEM2Spectrum(0x0),
fhZNCpmc(0x0),
fhZNApmc(0x0),
fhZPCpmc(0x0),
fhZPApmc(0x0),
fhZNCCentroid(0x0),
fhZNACentroid(0x0),
fhZNCemd(0x0),
fhZNAemd(0x0),
fhPMCZNCemd(0x0),
fhPMCZNAemd(0x0),
fDebunch(0x0)
{
// Output slot #1 writes into a TList container
DefineOutput(1, TList::Class());
}
//________________________________________________________________________
AliAnalysisTaskZDC& AliAnalysisTaskZDC::operator=(const AliAnalysisTaskZDC& c)
{
//
// Assignment operator
//
if (this!=&c) {
AliAnalysisTaskSE::operator=(c);
}
return *this;
}
//________________________________________________________________________
AliAnalysisTaskZDC::AliAnalysisTaskZDC(const AliAnalysisTaskZDC& ana):
AliAnalysisTaskSE(ana),
fDebug(ana.fDebug),
fIsMCInput(ana.fIsMCInput),
fOutput(ana.fOutput),
fhTDCZNSum(ana.fhTDCZNSum),
fhTDCZNDiff(ana.fhTDCZNDiff),
fhZNCSpectrum(ana.fhZNCSpectrum),
fhZNASpectrum(ana.fhZNASpectrum),
fhZPCSpectrum(ana.fhZPCSpectrum),
fhZPASpectrum(ana.fhZPASpectrum),
fhZEM1Spectrum(ana.fhZEM1Spectrum),
fhZEM2Spectrum(ana.fhZEM2Spectrum),
fhZNCpmc(ana.fhZNCpmc),
fhZNApmc(ana.fhZNApmc),
fhZPCpmc(ana.fhZPCpmc),
fhZPApmc(ana.fhZPApmc),
fhZNCCentroid(ana.fhZNCCentroid),
fhZNACentroid(ana.fhZNACentroid),
fhZNCemd(ana.fhZNCemd),
fhZNAemd(ana.fhZNAemd),
fhPMCZNCemd(ana.fhPMCZNCemd),
fhPMCZNAemd(ana.fhPMCZNAemd),
fDebunch(ana.fDebunch)
{
//
// Copy Constructor
//
}
//________________________________________________________________________
AliAnalysisTaskZDC::~AliAnalysisTaskZDC()
{
// Destructor
if(fOutput && !AliAnalysisManager::GetAnalysisManager()->IsProofMode()){
delete fOutput; fOutput=0;
}
}
//________________________________________________________________________
void AliAnalysisTaskZDC::UserCreateOutputObjects()
{
// Create the output containers
fOutput = new TList;
fOutput->SetOwner();
//fOutput->SetName("output");
fhTDCZNSum = new TH1F("fhTDCZNSum","TDC_{ZNC}+TDC_{ZNA}",60,-30.,-30.);
fhTDCZNSum->GetXaxis()->SetTitle("TDC_{ZNC}+TDC_{ZNA} (ns)");
fOutput->Add(fhTDCZNSum);
fhTDCZNDiff = new TH1F("fhTDCZNDiff","TDC_{ZNC}-TDC_{ZNA}",60,-30.,30.);
fhTDCZNDiff->GetXaxis()->SetTitle("TDC_{ZNC}-TDC_{ZNA} (ns)");
fOutput->Add(fhTDCZNDiff);
fhZNCSpectrum = new TH1F("fhZNCSpectrum", "ZNC signal", 200,0., 140000.);
fOutput->Add(fhZNCSpectrum);
fhZNASpectrum = new TH1F("fhZNASpectrum", "ZNA signal", 200,0., 140000.) ;
fOutput->Add(fhZNASpectrum);
fhZPCSpectrum = new TH1F("fhZPCSpectrum", "ZPC signal", 200,0., 50000.) ;
fOutput->Add(fhZPCSpectrum);
fhZPASpectrum = new TH1F("fhZPASpectrum", "ZPA signal", 200,0., 50000.) ;
fOutput->Add(fhZPASpectrum);
fhZEM1Spectrum = new TH1F("fhZEM1Spectrum", "ZEM1 signal", 100,0., 2500.);
fOutput->Add(fhZEM1Spectrum);
fhZEM2Spectrum = new TH1F("fhZEM2Spectrum", "ZEM2 signal", 100,0., 2500.);
fOutput->Add(fhZEM2Spectrum);
fhZNCpmc = new TH1F("fhZNCpmc","ZNC PMC",200, 0., 160000.);
fOutput->Add(fhZNCpmc);
fhZNApmc = new TH1F("fhZNApmc","ZNA PMC",200, 0., 160000.);
fOutput->Add(fhZNApmc);
fhZPCpmc = new TH1F("fhZPCpmc","ZPC PMC",200, 0., 40000.);
fOutput->Add(fhZPCpmc);
fhZPApmc = new TH1F("fhZPApmc","ZPA PMC",200, 0., 40000.);
fOutput->Add(fhZPApmc);
fhZNCCentroid = new TH2F("fhZNCCentroid","Centroid over ZNC",70,-3.5,3.5,70,-3.5,3.5);
fOutput->Add(fhZNCCentroid);
fhZNACentroid = new TH2F("fhZNACentroid","Centroid over ZNA",70,-3.5,3.5,70,-3.5,3.5);
fOutput->Add(fhZNACentroid);
fhZNCemd = new TH1F("fhZNCemd","ZNC signal lg",200,0.,6000.);
fOutput->Add(fhZNCemd);
fhZNAemd = new TH1F("fhZNAemd","ZNA signal lg",200,0.,6000.);
fOutput->Add(fhZNAemd);
fhPMCZNCemd = new TH1F("fhPMCZNCemd","ZNC PMC lg",200, 10., 6000.);
fOutput->Add(fhPMCZNCemd);
fhPMCZNAemd = new TH1F("fhPMCZNAemd","ZNA PMC lg",200, 10., 6000.);
fOutput->Add(fhPMCZNAemd);
fDebunch = new TH2F("fDebunch","ZN TDC sum vs. diff", 120,-30,30,120,-30,-30);
fOutput->Add(fDebunch);
PostData(1, fOutput);
}
//________________________________________________________________________
void AliAnalysisTaskZDC::UserExec(Option_t */*option*/)
{
// Execute analysis for current event:
if(fDebug>1) printf(" **** AliAnalysisTaskZDC::UserExec() \n");
if (!InputEvent()) {
Printf("ERROR: InputEvent not available");
return;
}
AliESDEvent* esd = dynamic_cast<AliESDEvent*> (InputEvent());
if(!esd) return;
// Select PHYSICS events (type=7, for data)
if(!fIsMCInput && esd->GetEventType()!=7) return;
// ********* MC INFO *********************************
if(fIsMCInput){
AliMCEventHandler* eventHandler = dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler());
if (!eventHandler) {
Printf("ERROR: Could not retrieve MC event handler");
return;
}
AliMCEvent* mcEvent = eventHandler->MCEvent();
if (!mcEvent) {
Printf("ERROR: Could not retrieve MC event");
return;
}
}
// ****************************************************
AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();
AliESDZDC *esdZDC = esd->GetESDZDC();
if((((AliInputEventHandler*)(am->GetInputEventHandler()))->IsEventSelected())){
fhZNCSpectrum->Fill(esdZDC->GetZDCN1Energy());
fhZNASpectrum->Fill(esdZDC->GetZDCN2Energy());
fhZPCSpectrum->Fill(esdZDC->GetZDCP1Energy());
fhZPASpectrum->Fill(esdZDC->GetZDCP2Energy());
fhZEM1Spectrum->Fill(esdZDC->GetZDCEMEnergy(0)/8.);
fhZEM2Spectrum->Fill(esdZDC->GetZDCEMEnergy(1)/8.);
const Double_t * towZNC = esdZDC->GetZN1TowerEnergy();
const Double_t * towZPC = esdZDC->GetZP1TowerEnergy();
const Double_t * towZNA = esdZDC->GetZN2TowerEnergy();
const Double_t * towZPA = esdZDC->GetZP2TowerEnergy();
//
fhZNCpmc->Fill(towZNC[0]);
fhZNApmc->Fill(towZNA[0]);
fhZPCpmc->Fill(towZPC[0]);
fhZPApmc->Fill(towZPA[0]);
Double_t xyZNC[2]={-99.,-99.}, xyZNA[2]={-99.,-99.};
esdZDC->GetZNCentroidInPbPb(1380., xyZNC, xyZNA);
//esdZDC->GetZNCentroidInpp(xyZNC, xyZNA);
fhZNCCentroid->Fill(xyZNC[0], xyZNC[1]);
fhZNACentroid->Fill(xyZNA[0], xyZNA[1]);
const Double_t * towZNCLG = esdZDC->GetZN1TowerEnergyLR();
const Double_t * towZNALG = esdZDC->GetZN2TowerEnergyLR();
Double_t znclg=0., znalg=0.;
for(Int_t iq=0; iq<5; iq++){
znclg += towZNCLG[iq];
znalg += towZNALG[iq];
}
fhZNCemd->Fill(znclg/2.);
fhZNAemd->Fill(znalg/2.);
fhPMCZNCemd->Fill(towZNCLG[0]);
fhPMCZNAemd->Fill(towZNALG[0]);
}
Float_t tdcC=999., tdcA=999;
Float_t tdcSum=999., tdcDiff=999;
for(int i=0; i<4; i++){
if(esdZDC->GetZDCTDCData(10,i) != 0.){
tdcC = esdZDC->GetZDCTDCCorrected(10,i);
if(esdZDC->GetZDCTDCData(12,i) != 0.){
tdcA = esdZDC->GetZDCTDCCorrected(12,i);
tdcSum = tdcC+tdcA;
tdcDiff = tdcC-tdcA;
}
}
if(tdcSum!=999.) fhTDCZNSum->Fill(tdcSum);
if(tdcDiff!=999.)fhTDCZNDiff->Fill(tdcDiff);
if(tdcSum!=999. && tdcDiff!=999.) fDebunch->Fill(tdcDiff, tdcSum);
}
PostData(1, fOutput);
}
//________________________________________________________________________
void AliAnalysisTaskZDC::Terminate(Option_t */*option*/)
{
// Terminate analysis
//
}
<|endoftext|> |
<commit_before>//#pragma warning(disable 4996)
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
GLuint LoadTexture(const char * filename)
{
GLuint texture;
unsigned int width, height;
unsigned char * data;
unsigned char header[54]; // Each BMP file begins by a 54-bytes header
unsigned int dataPos; // Position in the file where the actual data begins
unsigned int imageSize; // width*height*3
// Read file
FILE * file;
errno_t err;
err = fopen_s(&file, filename, "rb");
if (file == NULL) {
printf("Image could not be opened\n");
return false;
}
// check the bmp file
if (fread(header, 1, 54, file) != 54) {
printf("Not a correct BMP file\n");
return false;
}
if (header[0] != 'B' || header[1] != 'M') {
printf("Not a correct BMP file\n");
return false;
}
// Read ints from the byte array
dataPos = *(int*)&(header[0x0A]);
imageSize = *(int*)&(header[0x22]);
width = *(int*)&(header[0x12]);
height = *(int*)&(header[0x16]);
// Some BMP files are misformatted, guess missing information
if (imageSize == 0) imageSize = width*height * 3; // 3 : one byte for each Red, Green and Blue component
if (dataPos == 0) dataPos = 54; // The BMP header is done that way
// Create a buffer
data = (unsigned char *)malloc(imageSize);
// Read the actual data from the file into the buffer
fread(data, width * height * 3, 1, file);
fclose(file);
glGenTextures(1, &texture);
// "Bind" the newly created texture : all future texture functions will modify this texture
glBindTexture(GL_TEXTURE_2D, texture);
// Give the image to OpenGL
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
free(data);
return texture;
}
int main(int argc, char* argv[])
{
printf("[main]initialize the code here...\n");
//gluBuild2DMipmaps(GL_TEXTURE_2D, 3, width, height, GL_RGB, GL_UNSIGNED_BYTE, &data);
// Poor filtering. Needed !
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
printf("[main]finish here.\n");
system("pause");
return 0;
}<commit_msg>Upload the working version<commit_after>#pragma warning(disable 4996)
#include <GL\glut.h>
#include <GL\GL.h>
#include <GL\freeglut_ext.h>
#include <stdio.h>
#include <stdlib.h>
//#pragma comment( lib, "glew32.lib" )
unsigned int width = 480, height = 640;
GLuint texture = 0;
/* Handler for window-repaint event. Called back when the window first appears and
whenever the window needs to be re-painted. */
void display()
{
// Clear color and depth buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW); // Operate on model-view matrix
/* Draw a quad */
glBegin(GL_QUADS);
glTexCoord2i(0, 0); glVertex2i(0, 0);
glTexCoord2i(0, 1); glVertex2i(0, height);
glTexCoord2i(1, 1); glVertex2i(width, height);
glTexCoord2i(1, 0); glVertex2i(width, 0);
glEnd();
glutSwapBuffers();
}
/* Handler for window re-size event. Called back when the window first appears and
whenever the window is re-sized with its new width and height */
void reshape(GLsizei newwidth, GLsizei newheight)
{
// Set the viewport to cover the new window
glViewport(0, 0, width = newwidth, height = newheight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, 0.0, 100.0);
glMatrixMode(GL_MODELVIEW);
glutPostRedisplay();
}
//loadTexture .bmp 24bit RGB image function
GLuint loadTexture(const char * filename)
{
unsigned char header[54]; // Each BMP file begins by a 54-bytes header
unsigned int dataPos; // Position in the file where the actual data begins
unsigned int imageSize; // width*height*3
// Read file
FILE * file;
errno_t err;
err = fopen_s(&file, filename, "rb");
if (file == NULL) {
printf("Image could not be opened\n");
return false;
}
// check the bmp file
if (fread(header, 1, 54, file) != 54) {
printf("Not a correct BMP file\n");
return false;
}
if (header[0] != 'B' || header[1] != 'M') {
printf("Not a correct BMP file\n");
return false;
}
// Read ints from the byte array
dataPos = *(int*)&(header[0x0A]);
imageSize = *(int*)&(header[0x22]);
width = *(int*)&(header[0x12]);
height = *(int*)&(header[0x16]);
// Some BMP files are misformatted, guess missing information
if (imageSize == 0) imageSize = width*height * 3; // 3 : one byte for each Red, Green and Blue component
if (dataPos == 0) dataPos = 54; // The BMP header is done that way
//data = (unsigned char *)malloc(imageSize);// Create a buffer
unsigned char* data = new unsigned char[imageSize];
// Read the actual data from the file into the buffer
// fread ( void * ptr, size_t size, size_t count, FILE * stream );
fread(data, sizeof(unsigned char), imageSize, file);
// Convert (B, G, R) to (R, G, B)
unsigned char tmp;
for (int j = 0; j < width * 3; j += 3)
{
tmp = data[j];
data[j] = data[j + 2];
data[j + 2] = tmp;
}
GLuint texture;
glGenTextures(1, &texture);
// "Bind" the newly created texture : all future texture functions will modify this texture
glBindTexture(GL_TEXTURE_2D, texture);
// Give the image to OpenGL
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// Release memory
fclose(file);
free(data);
return texture;
}
void initGL()
{
glViewport(0, 0, width, height); // use a screen size of width by height
glEnable(GL_TEXTURE_2D); // Enable 2D texturing
glMatrixMode(GL_PROJECTION); // Make a simple 2D projection on the entire window
glLoadIdentity();
//glOrtho(0.0, w, h, 0.0, 0.0, 100.0);
//glOrtho(0.0, glutGet(GLUT_WINDOW_WIDTH), 0.0, glutGet(GLUT_WINDOW_HEIGHT), -1.0, 1.0);
glOrtho(0.0, width, 0.0, height, 0.0, 1.0);
glMatrixMode(GL_MODELVIEW); // Set the matrix mode to object modeling
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Set default
glClearDepth(0.0f); // Set default
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear the window
}
int main(int argc, char* argv[])
{
printf("[main]initialize the code here...\n");
/*
GLuint texture;
texture = loadTexture(argv[1]);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(512, 512);
glutCreateWindow("glutTest09");
DrawImage(texture);
// Poor filtering. Needed !
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
*/
/* GLUT init */
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB);
glutInitWindowSize(width, height);
glutCreateWindow(argv[1]); // Set windows name
glutDisplayFunc(display);
glutReshapeFunc(reshape); // Optional
/* OpenGL 2D generic initialization*/
initGL();
// load image with loadTexture function
texture = loadTexture(argv[1]);
/* OpenGL main loop*/
glutMainLoop();
printf("[main]finish here.\n");
system("pause");
return 0;
}<|endoftext|> |
<commit_before>#include <iostream>
#include <unistd.h>
#include "timer.hpp"
int main() {
high_resolution_timer timer;
usleep(1000 * 1000);
high_resolution_timer::duration dur = timer.pulse();
std::cerr << std::chrono::duration_cast<std::chrono::microseconds>(dur).count() << std::endl;
return 0;
}
<commit_msg>Win32 compatibility.<commit_after>#include <iostream>
#ifdef WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
#include "timer.hpp"
int main() {
high_resolution_timer timer;
#ifdef WIN32
Sleep(1000);
#else
usleep(1000 * 1000);
#endif
high_resolution_timer::duration dur = timer.pulse();
std::cerr << std::chrono::duration_cast<std::chrono::microseconds>(dur).count() << std::endl;
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 "webkit/glue/plugins/plugin_lib.h"
#include <dlfcn.h>
#include <elf.h>
#include "base/string_util.h"
#include "base/sys_string_conversions.h"
#include "webkit/glue/plugins/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 {
// 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) {
FILE* file = fopen(filename.value().c_str(), "rb");
if (!file)
return false;
char buffer[5];
if (fread(buffer, 5, 1, file) != 1) {
fclose(file);
return false;
}
fclose(file);
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;
}
} // anonymous namespace
namespace NPAPI {
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))
return false;
void* dl = base::LoadNativeLibrary(filename);
if (!dl)
return false;
info->path = filename;
// 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 = UTF8ToWide(name);
const char* description = NULL;
NP_GetValue(NULL, nsPluginVariable_DescriptionString, &description);
if (description)
info->desc = UTF8ToWide(description);
}
base::UnloadNativeLibrary(dl);
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);
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 = UTF8ToWide(description.substr(ofs, end - ofs));
} else {
mime_type.description = UTF8ToWide(description.substr(ofs));
}
mime_types->push_back(mime_type);
if (end == std::string::npos)
break;
ofs = end + 1;
}
}
} // namespace NPAPI
<commit_msg>Linux: Do not unload the o3d plugin in the browser process. This is a temporary workaround for a shutdown crash.<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/plugins/plugin_lib.h"
#include <dlfcn.h>
#include <elf.h>
#include "base/string_util.h"
#include "base/sys_string_conversions.h"
#include "webkit/glue/plugins/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 {
// 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) {
FILE* file = fopen(filename.value().c_str(), "rb");
if (!file)
return false;
char buffer[5];
if (fread(buffer, 5, 1, file) != 1) {
fclose(file);
return false;
}
fclose(file);
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;
}
// TODO(thestig) This is a hack to work around the crash in bug 25245. Remove
// this once we read plugins out of process.
bool SkipPluginUnloadHack(const WebPluginInfo& info) {
std::string filename = info.path.BaseName().value();
return (filename.find("npo3dautoplugin") != std::string::npos); // O3D
}
} // anonymous namespace
namespace NPAPI {
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))
return false;
void* dl = base::LoadNativeLibrary(filename);
if (!dl)
return false;
info->path = filename;
// 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 = UTF8ToWide(name);
const char* description = NULL;
NP_GetValue(NULL, nsPluginVariable_DescriptionString, &description);
if (description)
info->desc = UTF8ToWide(description);
}
if (!SkipPluginUnloadHack(*info))
base::UnloadNativeLibrary(dl);
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);
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 = UTF8ToWide(description.substr(ofs, end - ofs));
} else {
mime_type.description = UTF8ToWide(description.substr(ofs));
}
mime_types->push_back(mime_type);
if (end == std::string::npos)
break;
ofs = end + 1;
}
}
} // namespace NPAPI
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "RadiusDropLoot.h"
#include "../../Common/ETypes.h"
#include "../../Common/Helpers/RapidHelper.hpp"
#include <ATF/global.hpp>
namespace GameServer
{
namespace Addon
{
bool CRadiusDropLoot::m_bActivated = false;
bool CRadiusDropLoot::m_bOnlyPitboss = false;
int CRadiusDropLoot::m_nRange = 10;
void CRadiusDropLoot::load()
{
enable_hook(
(ATF::Global::Info::CreateItemBox111_ptr)&ATF::Global::CreateItemBox,
&CRadiusDropLoot::CreateItemBox);
}
void CRadiusDropLoot::unload()
{
cleanup_all_hook();
}
Yorozuya::Module::ModuleName_t CRadiusDropLoot::get_name()
{
static const Yorozuya::Module::ModuleName_t name = "addon.radius_drop_loot";
return name;
}
void CRadiusDropLoot::configure(const rapidjson::Value & nodeConfig)
{
CRadiusDropLoot::m_bActivated = RapidHelper::GetValueOrDefault(nodeConfig, "activated", false);
CRadiusDropLoot::m_bOnlyPitboss = RapidHelper::GetValueOrDefault(nodeConfig, "only_pitboss", false);
CRadiusDropLoot::m_nRange = RapidHelper::GetValueOrDefault(nodeConfig, "range", 100);
}
ATF::CItemBox* CRadiusDropLoot::CreateItemBox(
ATF::_STORAGE_LIST::_db_con* pItem,
ATF::CPlayer* pOwner,
unsigned int dwPartyBossSerial,
bool bPartyShare,
ATF::CCharacter* pThrower,
char byCreateCode,
ATF::CMapData* pMap,
uint16_t wLayerIndex,
float* pStdPos,
bool bHide,
ATF::Global::Info::CreateItemBox111_ptr next)
{
ATF::CItemBox* result = nullptr;
do
{
if (!CRadiusDropLoot::m_bActivated)
{
result = next(pItem, pOwner, dwPartyBossSerial, bPartyShare, pThrower, byCreateCode, pMap, wLayerIndex, pStdPos, bHide);
break;
}
if (pThrower->m_ObjID.m_byKind == 0 &&
pThrower->m_ObjID.m_byID != (uint8_t)e_obj_id::obj_id_monster)
{
result = next(pItem, pOwner, dwPartyBossSerial, bPartyShare, pThrower, byCreateCode, pMap, wLayerIndex, pStdPos, bHide);
break;
}
ATF::CMonster* pMonster = (ATF::CMonster*)pThrower;
if (CRadiusDropLoot::m_bOnlyPitboss && !pMonster->IsBossMonster())
{
result = next(pItem, pOwner, dwPartyBossSerial, bPartyShare, pThrower, byCreateCode, pMap, wLayerIndex, pStdPos, bHide);
break;
}
ATF::CItemBox* pItemBox = nullptr;
ATF::Global::CItemBox_Ref gItemBox = **ATF::Global::g_ItemBox;
for (auto& item_box : gItemBox)
{
if (!item_box.m_bLive)
{
pItemBox = &item_box;
break;
}
}
if (pItemBox == nullptr)
break;
ATF::_itembox_create_setdata Dst;
memcpy(&Dst.Item, pItem, sizeof(Dst.Item));
auto& ItemRecords = ATF::Global::g_MainThread->m_tblItemData[pItem->m_byTableCode];
Dst.m_pRecordSet = ItemRecords.GetRecord(pItem->m_wItemIndex);
if (Dst.m_pRecordSet == nullptr)
break;
Dst.byCreateCode = byCreateCode;
Dst.pOwner = pOwner;
Dst.bParty = bPartyShare;
Dst.pThrower = pThrower;
Dst.m_pMap = pMap;
Dst.m_nLayerIndex = wLayerIndex;
Dst.dwPartyBossSerial = dwPartyBossSerial;
if (!pMap->GetRandPosInRange(pStdPos, CRadiusDropLoot::m_nRange, Dst.m_fStartPos))
break;
if (!pItemBox->Create(&Dst, bHide))
break;
result = pItemBox;
} while (false);
return result;
}
}
}
<commit_msg>Fixed create item box by gm command<commit_after>#include "stdafx.h"
#include "RadiusDropLoot.h"
#include "../../Common/ETypes.h"
#include "../../Common/Helpers/RapidHelper.hpp"
#include <ATF/global.hpp>
namespace GameServer
{
namespace Addon
{
bool CRadiusDropLoot::m_bActivated = false;
bool CRadiusDropLoot::m_bOnlyPitboss = false;
int CRadiusDropLoot::m_nRange = 10;
void CRadiusDropLoot::load()
{
enable_hook(
(ATF::Global::Info::CreateItemBox111_ptr)&ATF::Global::CreateItemBox,
&CRadiusDropLoot::CreateItemBox);
}
void CRadiusDropLoot::unload()
{
cleanup_all_hook();
}
Yorozuya::Module::ModuleName_t CRadiusDropLoot::get_name()
{
static const Yorozuya::Module::ModuleName_t name = "addon.radius_drop_loot";
return name;
}
void CRadiusDropLoot::configure(const rapidjson::Value & nodeConfig)
{
CRadiusDropLoot::m_bActivated = RapidHelper::GetValueOrDefault(nodeConfig, "activated", false);
CRadiusDropLoot::m_bOnlyPitboss = RapidHelper::GetValueOrDefault(nodeConfig, "only_pitboss", false);
CRadiusDropLoot::m_nRange = RapidHelper::GetValueOrDefault(nodeConfig, "range", 100);
}
ATF::CItemBox* CRadiusDropLoot::CreateItemBox(
ATF::_STORAGE_LIST::_db_con* pItem,
ATF::CPlayer* pOwner,
unsigned int dwPartyBossSerial,
bool bPartyShare,
ATF::CCharacter* pThrower,
char byCreateCode,
ATF::CMapData* pMap,
uint16_t wLayerIndex,
float* pStdPos,
bool bHide,
ATF::Global::Info::CreateItemBox111_ptr next)
{
ATF::CItemBox* result = nullptr;
do
{
if (!CRadiusDropLoot::m_bActivated)
{
result = next(pItem, pOwner, dwPartyBossSerial, bPartyShare, pThrower, byCreateCode, pMap, wLayerIndex, pStdPos, bHide);
break;
}
if (!pThrower)
{
result = next(pItem, pOwner, dwPartyBossSerial, bPartyShare, pThrower, byCreateCode, pMap, wLayerIndex, pStdPos, bHide);
break;
}
if (pThrower->m_ObjID.m_byKind == 0 &&
pThrower->m_ObjID.m_byID != (uint8_t)e_obj_id::obj_id_monster)
{
result = next(pItem, pOwner, dwPartyBossSerial, bPartyShare, pThrower, byCreateCode, pMap, wLayerIndex, pStdPos, bHide);
break;
}
ATF::CMonster* pMonster = (ATF::CMonster*)pThrower;
if (CRadiusDropLoot::m_bOnlyPitboss && !pMonster->IsBossMonster())
{
result = next(pItem, pOwner, dwPartyBossSerial, bPartyShare, pThrower, byCreateCode, pMap, wLayerIndex, pStdPos, bHide);
break;
}
ATF::CItemBox* pItemBox = nullptr;
ATF::Global::CItemBox_Ref gItemBox = **ATF::Global::g_ItemBox;
for (auto& item_box : gItemBox)
{
if (!item_box.m_bLive)
{
pItemBox = &item_box;
break;
}
}
if (pItemBox == nullptr)
break;
ATF::_itembox_create_setdata Dst;
memcpy(&Dst.Item, pItem, sizeof(Dst.Item));
auto& ItemRecords = ATF::Global::g_MainThread->m_tblItemData[pItem->m_byTableCode];
Dst.m_pRecordSet = ItemRecords.GetRecord(pItem->m_wItemIndex);
if (Dst.m_pRecordSet == nullptr)
break;
Dst.byCreateCode = byCreateCode;
Dst.pOwner = pOwner;
Dst.bParty = bPartyShare;
Dst.pThrower = pThrower;
Dst.m_pMap = pMap;
Dst.m_nLayerIndex = wLayerIndex;
Dst.dwPartyBossSerial = dwPartyBossSerial;
if (!pMap->GetRandPosInRange(pStdPos, CRadiusDropLoot::m_nRange, Dst.m_fStartPos))
break;
if (!pItemBox->Create(&Dst, bHide))
break;
result = pItemBox;
} while (false);
return result;
}
}
}
<|endoftext|> |
<commit_before>#include <thread>
#include "TcpClient.h"
#include "platform/CCFileUtils.h"
#include "base/CCDirector.h"
#include "base/CCScheduler.h"
#include "2d/CCLabel.h"
#include "HelloWorldScene.h"
#include "../../PacketType.h"
#ifdef _WIN32
#pragma comment(lib,"ws2_32.lib")
#define sleep(x) Sleep(x)
#endif
static TcpClient* s_TcpClient = nullptr;
TcpClient::TcpClient() : m_recvBuffer(BUF_SIZE), m_sock(NULL), m_loginId(-1)
{
}
TcpClient::~TcpClient()
{
#ifndef _WIN32
close(m_sock);
#else
closesocket(m_sock);
WSACleanup();
#endif
}
bool TcpClient::initialize()
{
#ifdef _WIN32
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
return false;
#endif
m_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (m_sock == INVALID_SOCKET)
return false;
/// thread start
auto t = std::thread(CC_CALLBACK_0(TcpClient::networkThread, this));
t.detach();
return true;
}
TcpClient* TcpClient::getInstance()
{
if (nullptr == s_TcpClient)
{
s_TcpClient = new TcpClient();
if (false == s_TcpClient->initialize())
return nullptr;
/// for test connect
s_TcpClient->connect("127.0.0.1", 9001);
}
return s_TcpClient;
}
void TcpClient::destroyInstance()
{
CC_SAFE_DELETE(s_TcpClient);
}
bool TcpClient::connect(const char* serverAddr, int port)
{
struct hostent* host;
struct sockaddr_in hostAddr;
if ((host = gethostbyname(serverAddr)) == 0)
return false;
memset(&hostAddr, 0, sizeof(hostAddr));
hostAddr.sin_family = AF_INET;
hostAddr.sin_addr.s_addr = ((struct in_addr *)(host->h_addr_list[0]))->s_addr;
hostAddr.sin_port = htons(port);
if (SOCKET_ERROR == ::connect(m_sock, (struct sockaddr*)&hostAddr, sizeof(hostAddr)))
{
CCLOG("CONNECT FAILED");
return false;
}
//u_long arg = 1;
//ioctlsocket(mSocket, FIONBIO, &arg);
/// nagle ˰
int opt = 1;
setsockopt(m_sock, IPPROTO_TCP, TCP_NODELAY, (const char*)&opt, sizeof(int));
return true;
}
bool TcpClient::send(const char* data, int length)
{
int count = 0;
while (count < length)
{
int n = ::send(m_sock, data + count, length, 0);
if (n == SOCKET_ERROR)
{
CCLOG("SEND ERROR");
return false;
}
count += n;
length -= n;
}
return true;
}
void TcpClient::networkThread()
{
while ( true )
{
char inBuf[4096] = { 0, };
int n = ::recv(m_sock, inBuf, 4096, 0);
if (n < 1)
{
sleep(0); ///< for cpu low-utilization
continue;
}
if (!m_recvBuffer.Write(inBuf, n))
{
/// á.
assert(false);
}
processPacket();
}
}
void TcpClient::processPacket()
{
auto scheduler = cocos2d::Director::getInstance()->getScheduler();
/// Ŷ Ľؼ ϼǴ Ŷ , ش ݹ ҷش.
while (true)
{
PacketHeader header;
if (false == m_recvBuffer.Peek((char*)&header, sizeof(PacketHeader)))
break;
if (header.mSize > m_recvBuffer.GetStoredSize())
break;
switch (header.mType)
{
case PKT_SC_LOGIN:
{
LoginResult recvData;
bool ret = m_recvBuffer.Read((char*)&recvData, recvData.mSize);
assert(ret && recvData.mPlayerId != -1);
CCLOG("LOGIN OK: ID[%d] Name[%s] POS[%.4f, %.4f]", recvData.mPlayerId, recvData.mName, recvData.mPosX, recvData.mPosY);
m_loginId = recvData.mPlayerId;
}
break;
case PKT_SC_CHAT:
{
ChatBroadcastResult recvData;
bool ret = m_recvBuffer.Read((char*)&recvData, recvData.mSize);
assert(ret && recvData.mPlayerId != -1);
auto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(std::string("base_layer"));
scheduler->performFunctionInCocosThread(CC_CALLBACK_0(HelloWorld::chatDraw, dynamic_cast<HelloWorld*>(layer), std::string(recvData.mName), std::string(recvData.mChat)));
}
break;
case PKT_SC_MOVE:
{
MoveBroadcastResult recvData;
bool ret = m_recvBuffer.Read((char*)&recvData, recvData.mSize);
assert(ret && recvData.mPlayerId != -1);
auto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(std::string("base_layer"));
if ( recvData.mPlayerId == m_loginId ) ///< in case of me
scheduler->performFunctionInCocosThread(CC_CALLBACK_0(HelloWorld::updateMe, dynamic_cast<HelloWorld*>(layer), recvData.mPosX, recvData.mPosY));
else
scheduler->performFunctionInCocosThread(CC_CALLBACK_0(HelloWorld::updatePeer, dynamic_cast<HelloWorld*>(layer), recvData.mPlayerId, recvData.mPosX, recvData.mPosY));
}
break;
default:
assert(false);
}
}
}
void TcpClient::loginRequest()
{
if (m_loginId > 0)
return;
/// 뷫 Ʒ id α Ʈ..
LoginRequest sendData;
sendData.mPlayerId = 1000 + rand() % 101;
send((const char*)&sendData, sizeof(LoginRequest));
}
void TcpClient::chatRequest(const char* chat)
{
if (m_loginId < 0)
return;
ChatBroadcastRequest sendData;
sendData.mPlayerId = m_loginId;
memcpy(sendData.mChat, chat, strlen(chat));
send((const char*)&sendData, sizeof(ChatBroadcastRequest));
}
void TcpClient::moveRequest(float x, float y)
{
if (m_loginId < 0)
return;
MoveRequest sendData;
sendData.mPlayerId = m_loginId;
sendData.mPosX = x;
sendData.mPosY = y;
send((const char*)&sendData, sizeof(MoveRequest));
}
<commit_msg>*fixed: random seeding...<commit_after>#include <thread>
#include "TcpClient.h"
#include "platform/CCFileUtils.h"
#include "base/CCDirector.h"
#include "base/CCScheduler.h"
#include "2d/CCLabel.h"
#include "HelloWorldScene.h"
#include "../../PacketType.h"
#ifdef _WIN32
#pragma comment(lib,"ws2_32.lib")
#define sleep(x) Sleep(x)
#endif
static TcpClient* s_TcpClient = nullptr;
TcpClient::TcpClient() : m_recvBuffer(BUF_SIZE), m_sock(NULL), m_loginId(-1)
{
}
TcpClient::~TcpClient()
{
#ifndef _WIN32
close(m_sock);
#else
closesocket(m_sock);
WSACleanup();
#endif
}
bool TcpClient::initialize()
{
#ifdef _WIN32
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
return false;
#endif
m_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (m_sock == INVALID_SOCKET)
return false;
/// thread start
auto t = std::thread(CC_CALLBACK_0(TcpClient::networkThread, this));
t.detach();
return true;
}
TcpClient* TcpClient::getInstance()
{
if (nullptr == s_TcpClient)
{
s_TcpClient = new TcpClient();
if (false == s_TcpClient->initialize())
return nullptr;
/// for test connect
//s_TcpClient->connect("127.0.0.1", 9001);
s_TcpClient->connect("10.73.45.147", 9001);
}
return s_TcpClient;
}
void TcpClient::destroyInstance()
{
CC_SAFE_DELETE(s_TcpClient);
}
bool TcpClient::connect(const char* serverAddr, int port)
{
struct hostent* host;
struct sockaddr_in hostAddr;
if ((host = gethostbyname(serverAddr)) == 0)
return false;
memset(&hostAddr, 0, sizeof(hostAddr));
hostAddr.sin_family = AF_INET;
hostAddr.sin_addr.s_addr = ((struct in_addr *)(host->h_addr_list[0]))->s_addr;
hostAddr.sin_port = htons(port);
if (SOCKET_ERROR == ::connect(m_sock, (struct sockaddr*)&hostAddr, sizeof(hostAddr)))
{
CCLOG("CONNECT FAILED");
return false;
}
//u_long arg = 1;
//ioctlsocket(mSocket, FIONBIO, &arg);
/// nagle ˰
int opt = 1;
setsockopt(m_sock, IPPROTO_TCP, TCP_NODELAY, (const char*)&opt, sizeof(int));
return true;
}
bool TcpClient::send(const char* data, int length)
{
int count = 0;
while (count < length)
{
int n = ::send(m_sock, data + count, length, 0);
if (n == SOCKET_ERROR)
{
CCLOG("SEND ERROR");
return false;
}
count += n;
length -= n;
}
return true;
}
void TcpClient::networkThread()
{
while ( true )
{
char inBuf[4096] = { 0, };
int n = ::recv(m_sock, inBuf, 4096, 0);
if (n < 1)
{
sleep(0); ///< for cpu low-utilization
continue;
}
if (!m_recvBuffer.Write(inBuf, n))
{
/// á.
assert(false);
}
processPacket();
}
}
void TcpClient::processPacket()
{
auto scheduler = cocos2d::Director::getInstance()->getScheduler();
/// Ŷ Ľؼ ϼǴ Ŷ , ش ݹ ҷش.
while (true)
{
PacketHeader header;
if (false == m_recvBuffer.Peek((char*)&header, sizeof(PacketHeader)))
break;
if (header.mSize > m_recvBuffer.GetStoredSize())
break;
switch (header.mType)
{
case PKT_SC_LOGIN:
{
LoginResult recvData;
bool ret = m_recvBuffer.Read((char*)&recvData, recvData.mSize);
assert(ret && recvData.mPlayerId != -1);
CCLOG("LOGIN OK: ID[%d] Name[%s] POS[%.4f, %.4f]", recvData.mPlayerId, recvData.mName, recvData.mPosX, recvData.mPosY);
m_loginId = recvData.mPlayerId;
}
break;
case PKT_SC_CHAT:
{
ChatBroadcastResult recvData;
bool ret = m_recvBuffer.Read((char*)&recvData, recvData.mSize);
assert(ret && recvData.mPlayerId != -1);
auto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(std::string("base_layer"));
scheduler->performFunctionInCocosThread(CC_CALLBACK_0(HelloWorld::chatDraw, dynamic_cast<HelloWorld*>(layer), std::string(recvData.mName), std::string(recvData.mChat)));
}
break;
case PKT_SC_MOVE:
{
MoveBroadcastResult recvData;
bool ret = m_recvBuffer.Read((char*)&recvData, recvData.mSize);
assert(ret && recvData.mPlayerId != -1);
auto layer = cocos2d::Director::getInstance()->getRunningScene()->getChildByName(std::string("base_layer"));
if ( recvData.mPlayerId == m_loginId ) ///< in case of me
scheduler->performFunctionInCocosThread(CC_CALLBACK_0(HelloWorld::updateMe, dynamic_cast<HelloWorld*>(layer), recvData.mPosX, recvData.mPosY));
else
scheduler->performFunctionInCocosThread(CC_CALLBACK_0(HelloWorld::updatePeer, dynamic_cast<HelloWorld*>(layer), recvData.mPlayerId, recvData.mPosX, recvData.mPosY));
}
break;
default:
assert(false);
}
}
}
void TcpClient::loginRequest()
{
if (m_loginId > 0)
return;
srand(time(NULL));
/// 뷫 Ʒ id α Ʈ..
LoginRequest sendData;
sendData.mPlayerId = 1000 + rand() % 101;
send((const char*)&sendData, sizeof(LoginRequest));
}
void TcpClient::chatRequest(const char* chat)
{
if (m_loginId < 0)
return;
ChatBroadcastRequest sendData;
sendData.mPlayerId = m_loginId;
memcpy(sendData.mChat, chat, strlen(chat));
send((const char*)&sendData, sizeof(ChatBroadcastRequest));
}
void TcpClient::moveRequest(float x, float y)
{
if (m_loginId < 0)
return;
MoveRequest sendData;
sendData.mPlayerId = m_loginId;
sendData.mPosX = x;
sendData.mPosY = y;
send((const char*)&sendData, sizeof(MoveRequest));
}
<|endoftext|> |
<commit_before><commit_msg>coverity#705222 Missing break in switch<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: presvish.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: af $ $Date: 2004-08-02 16:55:04 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "PresentationViewShell.hxx"
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFX_TOPFRM_HXX
#include <sfx2/topfrm.hxx>
#endif
#ifndef _SFX_DISPATCH_HXX
#include <sfx2/dispatch.hxx>
#endif
#include <svx/svxids.hrc>
#include <sfx2/app.hxx>
#ifndef SD_FRAME_VIEW
#include "FrameView.hxx"
#endif
#include "sdresid.hxx"
#include "DrawDocShell.hxx"
#ifndef SD_FU_SLIDE_SHOW_HXX
#include "fuslshow.hxx"
#endif
#include "sdattr.hxx"
#include "sdpage.hxx"
#include "drawdoc.hxx"
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
#include "app.hrc"
#include "strings.hrc"
#include "glob.hrc"
#include "PaneManager.hxx"
#ifndef SD_VIEW_SHELL_BASE_HXX
#include "ViewShellBase.hxx"
#endif
#ifndef SD_FACTORY_IDS_HXX
#include "FactoryIds.hxx"
#endif
#define PresentationViewShell
using namespace sd;
#include "sdslots.hxx"
namespace {
/** Objects of this class wait for the execution of an asynchronous view
shell change and finish the initialization of a new
PresentationViewShell object.
After it has done its job the object removes itself as listener from the
view shell base and destroyes itself.
*/
class ViewShellChangeListener
{
public:
ViewShellChangeListener (
ViewShellBase& rBase,
FrameView* pFrameView,
USHORT nPageNumber,
const SfxRequest& rRequest)
: mrBase (rBase),
mpFrameView(pFrameView),
mnPageNumber(nPageNumber),
maRequest(rRequest)
{
if (mpFrameView != NULL)
mpFrameView->Connect();
rBase.GetPaneManager().AddEventListener (
LINK(this, ViewShellChangeListener, HandleViewShellChange));
}
private:
ViewShellBase& mrBase;
FrameView* const mpFrameView;
const USHORT mnPageNumber;
SfxRequest maRequest;
DECL_LINK(HandleViewShellChange, PaneManagerEvent*);
};
IMPL_LINK(ViewShellChangeListener, HandleViewShellChange,
PaneManagerEvent*, pEvent)
{
if (pEvent->meEventId == PaneManagerEvent::EID_VIEW_SHELL_ADDED
&& pEvent->mePane == PaneManager::PT_CENTER)
{
if (pEvent->mpShell->ISA(PresentationViewShell))
{
PresentationViewShell* pShell
= PTR_CAST(PresentationViewShell, pEvent->mpShell);
pShell->FinishInitialization (
mpFrameView,
maRequest,
mnPageNumber);
if (mpFrameView != NULL)
mpFrameView->Disconnect();
/*
mpFrameView->Connect();
pShell->GetFrameView()->Disconnect();
pShell->SetFrameView (mpFrameView);
pShell->SwitchPage (mnPageNumber);
pShell->WriteFrameViewData();
SfxBoolItem aShowItem (SID_SHOWPOPUPS, FALSE);
SfxUInt16Item aId (SID_CONFIGITEMID, SID_NAVIGATOR);
pShell->GetViewFrame()->GetDispatcher()->Execute(
SID_SHOWPOPUPS, SFX_CALLMODE_SYNCHRON, &aShowItem, &aId, 0L );
pShell->GetViewFrame()->Show();
pShell->SetSlideShowFunction (new FuSlideShow(
pShell,
pShell->GetActiveWindow(),
pShell->GetView(),
pShell->GetDoc(),
maRequest));
pShell->GetActiveWindow()->GrabFocus();
pShell->GetSlideShow()->Activate();
pShell->GetSlideShow()->StartShow();
*/
}
// Remove this listener from the view shell base and destroy it.
mrBase.GetPaneManager().RemoveEventListener (
LINK(this,ViewShellChangeListener,HandleViewShellChange));
delete this;
}
return 0;
}
} // end of anonymouse namespace
namespace sd {
// -------------------
// - PresentationViewShell -
// -------------------
SFX_IMPL_INTERFACE( PresentationViewShell, DrawViewShell, SdResId( STR_PRESVIEWSHELL ) )
{
SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_TOOLS | SFX_VISIBILITY_STANDARD |
SFX_VISIBILITY_FULLSCREEN | SFX_VISIBILITY_SERVER,
SdResId(RID_DRAW_TOOLBOX));
SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_APPLICATION | SFX_VISIBILITY_DESKTOP | SFX_VISIBILITY_STANDARD | SFX_VISIBILITY_CLIENT | SFX_VISIBILITY_VIEWER | SFX_VISIBILITY_READONLYDOC,
SdResId(RID_DRAW_VIEWER_TOOLBOX) );
SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_OPTIONS | SFX_VISIBILITY_STANDARD |
SFX_VISIBILITY_SERVER,
SdResId(RID_DRAW_OPTIONS_TOOLBOX));
SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_COMMONTASK | SFX_VISIBILITY_STANDARD |
SFX_VISIBILITY_SERVER,
SdResId(RID_DRAW_COMMONTASK_TOOLBOX));
}
TYPEINIT1( PresentationViewShell, DrawViewShell );
PresentationViewShell::PresentationViewShell (
SfxViewFrame* pFrame,
ViewShellBase& rViewShellBase,
::Window* pParentWindow,
FrameView* pFrameView)
: DrawViewShell (
pFrame,
rViewShellBase,
pParentWindow,
PK_STANDARD,
pFrameView),
mbShowStarted( sal_False )
{
if( GetDocSh() && GetDocSh()->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED )
maOldVisArea = GetDocSh()->GetVisArea( ASPECT_CONTENT );
meShellType = ST_PRESENTATION;
}
PresentationViewShell::PresentationViewShell (
SfxViewFrame* pFrame,
::Window* pParentWindow,
const DrawViewShell& rShell)
: DrawViewShell (pFrame, pParentWindow, rShell),
mbShowStarted( sal_False )
{
if( GetDocSh() && GetDocSh()->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED )
maOldVisArea = GetDocSh()->GetVisArea( ASPECT_CONTENT );
meShellType = ST_PRESENTATION;
}
PresentationViewShell::~PresentationViewShell (void)
{
if( GetDocSh() && GetDocSh()->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED && !maOldVisArea.IsEmpty() )
GetDocSh()->SetVisArea( maOldVisArea );
if( GetViewFrame() && GetViewFrame()->GetTopFrame() )
{
WorkWindow* pWorkWindow = (WorkWindow*) GetViewFrame()->GetTopFrame()->GetWindow().GetParent();
if( pWorkWindow )
pWorkWindow->StartPresentationMode( FALSE, pFuSlideShow ? pFuSlideShow->IsAlwaysOnTop() : 0 );
}
if( pFuSlideShow )
{
pFuSlideShow->Deactivate();
pFuSlideShow->Terminate();
pFuSlideShow->Destroy();
pFuSlideShow = NULL;
}
}
void PresentationViewShell::FinishInitialization (
FrameView* pFrameView,
SfxRequest& rRequest,
USHORT nPageNumber)
{
DrawViewShell::Init();
// Use the frame view that comes form the view shell that initiated our
// creation.
if (pFrameView != NULL)
{
GetFrameView()->Disconnect();
SetFrameView (pFrameView);
pFrameView->Connect();
}
SwitchPage (nPageNumber);
WriteFrameViewData();
SfxBoolItem aShowItem (SID_SHOWPOPUPS, FALSE);
SfxUInt16Item aId (SID_CONFIGITEMID, SID_NAVIGATOR);
GetViewFrame()->GetDispatcher()->Execute(
SID_SHOWPOPUPS, SFX_CALLMODE_SYNCHRON, &aShowItem, &aId, 0L );
GetViewFrame()->Show();
SetSlideShowFunction (new FuSlideShow(
this,
GetActiveWindow(),
GetView(),
GetDoc(),
rRequest));
GetActiveWindow()->GrabFocus();
// Start the show.
GetSlideShow()->StartShow();
Activate(TRUE);
}
void PresentationViewShell::Activate( BOOL bIsMDIActivate )
{
DrawViewShell::Activate( bIsMDIActivate );
if( bIsMDIActivate )
{
::sd::View* pView = GetView();
SfxBoolItem aItem( SID_NAVIGATOR_INIT, TRUE );
GetViewFrame()->GetDispatcher()->Execute( SID_NAVIGATOR_INIT, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD, &aItem, 0L );
if( pFuSlideShow && !pFuSlideShow->IsTerminated() )
pFuSlideShow->Activate();
if( pFuActual )
pFuActual->Activate();
if( pView )
pView->ShowMarkHdl( NULL );
}
if( bIsMDIActivate )
ReadFrameViewData( pFrameView );
GetDocSh()->Connect( this );
if( pFuSlideShow && !mbShowStarted )
{
pFuSlideShow->StartShow();
mbShowStarted = sal_True;
}
}
// -----------------------------------------------------------------------------
void PresentationViewShell::Paint( const Rectangle& rRect, ::sd::Window* pWin )
{
// allow paints only if show is already started
if( mbShowStarted )
DrawViewShell::Paint( rRect, pWin );
}
// -----------------------------------------------------------------------------
void PresentationViewShell::CreateFullScreenShow (
ViewShell* pOriginShell,
SfxRequest& rRequest)
{
SFX_REQUEST_ARG (rRequest, pAlwaysOnTop, SfxBoolItem,
ATTR_PRESENT_ALWAYS_ON_TOP, FALSE);
WorkWindow* pWorkWindow = new WorkWindow (
NULL,
WB_HIDE | WB_CLIPCHILDREN);
SdDrawDocument* pDoc = pOriginShell->GetDoc();
SdPage* pCurrentPage = pOriginShell->GetActualPage();
bool bAlwaysOnTop =
((rRequest.GetSlot() != SID_REHEARSE_TIMINGS) && pAlwaysOnTop )
? pAlwaysOnTop->GetValue()
: pDoc->GetPresAlwaysOnTop();
pWorkWindow->StartPresentationMode (
TRUE,
bAlwaysOnTop ? PRESENTATION_HIDEALLAPPS : 0);
if (pWorkWindow->IsVisible())
{
//AF The bHidden paramter (the fourth one) was previously set to
// TRUE. This does not work anymore for some unknown reason. The
// ViewShellBase does then not get activated and the whole
// initialization process is not started: the screen becomes blank.
SfxTopFrame* pNewFrame = SfxTopFrame::Create (
pDoc->GetDocSh(),
pWorkWindow,
PRESENTATION_FACTORY_ID,
FALSE/*TRUE*/);
pNewFrame->SetPresentationMode (TRUE);
ViewShellBase* pBase = static_cast<ViewShellBase*>(
pNewFrame->GetCurrentViewFrame()->GetViewShell());
if (pBase != NULL)
{
// Get the page where the show is to be started. This normally
// is the current page of the shell from which the show has been
// started. This, however, may be NULL, e.g. when started from
// the slide sorter and that has an empty selection.
USHORT nStartPage = 0;
if (pCurrentPage != NULL)
nStartPage = (pCurrentPage->GetPageNum() - 1) / 2;
// The rest of the initialization is done by an object that
// waits until the PresentationViewShell object has been
// created. This is necessary because the creation is done
// asynchronously.
new ViewShellChangeListener(
*pBase,
pOriginShell->GetFrameView(),
nStartPage,
rRequest);
pBase->LateInit();
pBase->GetViewFrame()->Show();
}
}
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS c02v1 (1.17.10); FILE MERGED 2004/08/23 12:49:20 af 1.17.10.1: #i31584# The work window is created hidden again.<commit_after>/*************************************************************************
*
* $RCSfile: presvish.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: kz $ $Date: 2004-08-31 13:50:27 $
*
* 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 "PresentationViewShell.hxx"
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFX_TOPFRM_HXX
#include <sfx2/topfrm.hxx>
#endif
#ifndef _SFX_DISPATCH_HXX
#include <sfx2/dispatch.hxx>
#endif
#include <svx/svxids.hrc>
#include <sfx2/app.hxx>
#ifndef SD_FRAME_VIEW
#include "FrameView.hxx"
#endif
#include "sdresid.hxx"
#include "DrawDocShell.hxx"
#ifndef SD_FU_SLIDE_SHOW_HXX
#include "fuslshow.hxx"
#endif
#include "sdattr.hxx"
#include "sdpage.hxx"
#include "drawdoc.hxx"
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
#include "app.hrc"
#include "strings.hrc"
#include "glob.hrc"
#include "PaneManager.hxx"
#ifndef SD_VIEW_SHELL_BASE_HXX
#include "ViewShellBase.hxx"
#endif
#ifndef SD_FACTORY_IDS_HXX
#include "FactoryIds.hxx"
#endif
#define PresentationViewShell
using namespace sd;
#include "sdslots.hxx"
namespace {
/** Objects of this class wait for the execution of an asynchronous view
shell change and finish the initialization of a new
PresentationViewShell object.
After it has done its job the object removes itself as listener from the
view shell base and destroyes itself.
*/
class ViewShellChangeListener
{
public:
ViewShellChangeListener (
ViewShellBase& rBase,
FrameView* pFrameView,
USHORT nPageNumber,
const SfxRequest& rRequest)
: mrBase (rBase),
mpFrameView(pFrameView),
mnPageNumber(nPageNumber),
maRequest(rRequest)
{
if (mpFrameView != NULL)
mpFrameView->Connect();
rBase.GetPaneManager().AddEventListener (
LINK(this, ViewShellChangeListener, HandleViewShellChange));
}
private:
ViewShellBase& mrBase;
FrameView* const mpFrameView;
const USHORT mnPageNumber;
SfxRequest maRequest;
DECL_LINK(HandleViewShellChange, PaneManagerEvent*);
};
IMPL_LINK(ViewShellChangeListener, HandleViewShellChange,
PaneManagerEvent*, pEvent)
{
if (pEvent->meEventId == PaneManagerEvent::EID_VIEW_SHELL_ADDED
&& pEvent->mePane == PaneManager::PT_CENTER)
{
if (pEvent->mpShell->ISA(PresentationViewShell))
{
PresentationViewShell* pShell
= PTR_CAST(PresentationViewShell, pEvent->mpShell);
pShell->FinishInitialization (
mpFrameView,
maRequest,
mnPageNumber);
if (mpFrameView != NULL)
mpFrameView->Disconnect();
/*
mpFrameView->Connect();
pShell->GetFrameView()->Disconnect();
pShell->SetFrameView (mpFrameView);
pShell->SwitchPage (mnPageNumber);
pShell->WriteFrameViewData();
SfxBoolItem aShowItem (SID_SHOWPOPUPS, FALSE);
SfxUInt16Item aId (SID_CONFIGITEMID, SID_NAVIGATOR);
pShell->GetViewFrame()->GetDispatcher()->Execute(
SID_SHOWPOPUPS, SFX_CALLMODE_SYNCHRON, &aShowItem, &aId, 0L );
pShell->GetViewFrame()->Show();
pShell->SetSlideShowFunction (new FuSlideShow(
pShell,
pShell->GetActiveWindow(),
pShell->GetView(),
pShell->GetDoc(),
maRequest));
pShell->GetActiveWindow()->GrabFocus();
pShell->GetSlideShow()->Activate();
pShell->GetSlideShow()->StartShow();
*/
}
// Remove this listener from the view shell base and destroy it.
mrBase.GetPaneManager().RemoveEventListener (
LINK(this,ViewShellChangeListener,HandleViewShellChange));
delete this;
}
return 0;
}
} // end of anonymouse namespace
namespace sd {
// -------------------
// - PresentationViewShell -
// -------------------
SFX_IMPL_INTERFACE( PresentationViewShell, DrawViewShell, SdResId( STR_PRESVIEWSHELL ) )
{
SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_TOOLS | SFX_VISIBILITY_STANDARD |
SFX_VISIBILITY_FULLSCREEN | SFX_VISIBILITY_SERVER,
SdResId(RID_DRAW_TOOLBOX));
SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_APPLICATION | SFX_VISIBILITY_DESKTOP | SFX_VISIBILITY_STANDARD | SFX_VISIBILITY_CLIENT | SFX_VISIBILITY_VIEWER | SFX_VISIBILITY_READONLYDOC,
SdResId(RID_DRAW_VIEWER_TOOLBOX) );
SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_OPTIONS | SFX_VISIBILITY_STANDARD |
SFX_VISIBILITY_SERVER,
SdResId(RID_DRAW_OPTIONS_TOOLBOX));
SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_COMMONTASK | SFX_VISIBILITY_STANDARD |
SFX_VISIBILITY_SERVER,
SdResId(RID_DRAW_COMMONTASK_TOOLBOX));
}
TYPEINIT1( PresentationViewShell, DrawViewShell );
PresentationViewShell::PresentationViewShell (
SfxViewFrame* pFrame,
ViewShellBase& rViewShellBase,
::Window* pParentWindow,
FrameView* pFrameView)
: DrawViewShell (
pFrame,
rViewShellBase,
pParentWindow,
PK_STANDARD,
pFrameView),
mbShowStarted( sal_False )
{
if( GetDocSh() && GetDocSh()->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED )
maOldVisArea = GetDocSh()->GetVisArea( ASPECT_CONTENT );
meShellType = ST_PRESENTATION;
}
PresentationViewShell::PresentationViewShell (
SfxViewFrame* pFrame,
::Window* pParentWindow,
const DrawViewShell& rShell)
: DrawViewShell (pFrame, pParentWindow, rShell),
mbShowStarted( sal_False )
{
if( GetDocSh() && GetDocSh()->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED )
maOldVisArea = GetDocSh()->GetVisArea( ASPECT_CONTENT );
meShellType = ST_PRESENTATION;
}
PresentationViewShell::~PresentationViewShell (void)
{
if( GetDocSh() && GetDocSh()->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED && !maOldVisArea.IsEmpty() )
GetDocSh()->SetVisArea( maOldVisArea );
if( GetViewFrame() && GetViewFrame()->GetTopFrame() )
{
WorkWindow* pWorkWindow = (WorkWindow*) GetViewFrame()->GetTopFrame()->GetWindow().GetParent();
if( pWorkWindow )
pWorkWindow->StartPresentationMode( FALSE, pFuSlideShow ? pFuSlideShow->IsAlwaysOnTop() : 0 );
}
if( pFuSlideShow )
{
pFuSlideShow->Deactivate();
pFuSlideShow->Terminate();
pFuSlideShow->Destroy();
pFuSlideShow = NULL;
}
}
void PresentationViewShell::FinishInitialization (
FrameView* pFrameView,
SfxRequest& rRequest,
USHORT nPageNumber)
{
DrawViewShell::Init();
// Use the frame view that comes form the view shell that initiated our
// creation.
if (pFrameView != NULL)
{
GetFrameView()->Disconnect();
SetFrameView (pFrameView);
pFrameView->Connect();
}
SwitchPage (nPageNumber);
WriteFrameViewData();
SfxBoolItem aShowItem (SID_SHOWPOPUPS, FALSE);
SfxUInt16Item aId (SID_CONFIGITEMID, SID_NAVIGATOR);
GetViewFrame()->GetDispatcher()->Execute(
SID_SHOWPOPUPS, SFX_CALLMODE_SYNCHRON, &aShowItem, &aId, 0L );
GetViewFrame()->Show();
SetSlideShowFunction (new FuSlideShow(
this,
GetActiveWindow(),
GetView(),
GetDoc(),
rRequest));
GetActiveWindow()->GrabFocus();
// Start the show.
GetSlideShow()->StartShow();
Activate(TRUE);
}
void PresentationViewShell::Activate( BOOL bIsMDIActivate )
{
DrawViewShell::Activate( bIsMDIActivate );
if( bIsMDIActivate )
{
::sd::View* pView = GetView();
SfxBoolItem aItem( SID_NAVIGATOR_INIT, TRUE );
GetViewFrame()->GetDispatcher()->Execute( SID_NAVIGATOR_INIT, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD, &aItem, 0L );
if( pFuSlideShow && !pFuSlideShow->IsTerminated() )
pFuSlideShow->Activate();
if( pFuActual )
pFuActual->Activate();
if( pView )
pView->ShowMarkHdl( NULL );
}
if( bIsMDIActivate )
ReadFrameViewData( pFrameView );
GetDocSh()->Connect( this );
if( pFuSlideShow && !mbShowStarted )
{
pFuSlideShow->StartShow();
mbShowStarted = sal_True;
}
}
// -----------------------------------------------------------------------------
void PresentationViewShell::Paint( const Rectangle& rRect, ::sd::Window* pWin )
{
// allow paints only if show is already started
if( mbShowStarted )
DrawViewShell::Paint( rRect, pWin );
}
// -----------------------------------------------------------------------------
void PresentationViewShell::CreateFullScreenShow (
ViewShell* pOriginShell,
SfxRequest& rRequest)
{
SdDrawDocument* pDoc = pOriginShell->GetDoc();
SdPage* pCurrentPage = pOriginShell->GetActualPage();
SFX_REQUEST_ARG (rRequest, pAlwaysOnTop, SfxBoolItem,
ATTR_PRESENT_ALWAYS_ON_TOP, FALSE);
bool bAlwaysOnTop =
((rRequest.GetSlot() != SID_REHEARSE_TIMINGS) && pAlwaysOnTop )
? pAlwaysOnTop->GetValue()
: pDoc->GetPresAlwaysOnTop();
WorkWindow* pWorkWindow = new WorkWindow (
NULL,
WB_HIDE | WB_CLIPCHILDREN);
pWorkWindow->StartPresentationMode (
TRUE,
bAlwaysOnTop ? PRESENTATION_HIDEALLAPPS : 0);
pWorkWindow->SetBackground(Wallpaper(COL_BLACK));
if (pWorkWindow->IsVisible())
{
// The new frame is created hidden. To make it visible and activate
// the new view shell--a prerequisite to process slot calls and
// initialize its panes--a GrabFocus() has to be called later on.
SfxTopFrame* pNewFrame = SfxTopFrame::Create (
pDoc->GetDocSh(),
pWorkWindow,
PRESENTATION_FACTORY_ID,
TRUE);
pNewFrame->SetPresentationMode (TRUE);
ViewShellBase* pBase = static_cast<ViewShellBase*>(
pNewFrame->GetCurrentViewFrame()->GetViewShell());
if (pBase != NULL)
{
// Get the page where the show is to be started. This normally
// is the current page of the shell from which the show has been
// started. This, however, may be NULL, e.g. when started from
// the slide sorter and that has an empty selection.
USHORT nStartPage = 0;
if (pCurrentPage != NULL)
nStartPage = (pCurrentPage->GetPageNum() - 1) / 2;
// The rest of the initialization is done by an object that
// waits until the PresentationViewShell object has been
// created. This is necessary because the creation is done
// asynchronously.
new ViewShellChangeListener(
*pBase,
pOriginShell->GetFrameView(),
nStartPage,
rRequest);
pBase->GetViewFrame()->Show();
// The following GrabFocus() is responsible for activating the
// new view shell. Without it the screen remains blank (under
// Windows and some Linux variants.)
pBase->GetWindow()->GrabFocus();
}
}
}
} // end of namespace sd
<|endoftext|> |
<commit_before>#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "sensor_msgs/LaserScan.h"
#include <nav_msgs/Odometry.h>
#include "std_msgs/String.h"
#include "se306Project/SheepMoveMsg.h"
#include <cstdlib> // Needed for rand()
#include <ctime> // Needed to seed random number generator with a time value
enum FSM {FSM_MOVE_FORWARD, FSM_ROTATE};
// Tunable parameters
// TODO: tune parameters as you see fit
const static double MIN_SCAN_ANGLE_RAD = -10.0/180*M_PI;
const static double MAX_SCAN_ANGLE_RAD = +10.0/180*M_PI;
const static float PROXIMITY_RANGE_M = 1; // Should be smaller than sensor_msgs::LaserScan::range_max
const static double FORWARD_SPEED_MPS = 0.2;
const static double ROTATE_SPEED_RADPS = M_PI/2;
class SheepMove {
public:
float prevclosestRange;
double linear_x;
double angular_z;
//pose of the robot
double px;
double py;
double theta;
double prevpx;
double prevpy;
bool isRotate;
int checkcount;
int sheepNum;
int robotNum;
std::string moveStatus;
//methods
SheepMove(int);
void StageOdom_callback(nav_msgs::Odometry);
void move(double, double);
void statusCallback(se306Project::SheepMoveMsg);
void commandCallback(const sensor_msgs::LaserScan::ConstPtr&);
void spin();
void rosSetup(int argc, char **argv);
protected:
//talkie things
ros::Publisher commandPub; // Publisher to the simulated robot's velocity command topic
ros::Publisher sheepPosPub;
ros::Subscriber laserSub; // Subscriber to the simulated robot's laser scan topic
ros::Subscriber sheepStatusSub; //Subscriber to sheep_[sheepNum]/move topic
//move state things
enum FSM fsm; // Finite state machine for the random walk algorithm
ros::Time rotateStartTime; // Start time of the rotation
ros::Time rotateEndTime;
ros::Duration rotateDuration; // Duration of the rotation
ros::Subscriber StageOdo_sub;
};
void SheepMove::StageOdom_callback(nav_msgs::Odometry msg) {
//This is the call back function to process odometry messages coming from Stage.
px = 5 + msg.pose.pose.position.x;
py = 10 + msg.pose.pose.position.y;
//printf("%f",px);
// If the current position is the same the previous position, then the robot is stuck and needs to move around
if ((px == prevpx) && (py == prevpy)) {
//msg.pose.pose.position.x = 5;
//ROS_INFO("Prevpx: %f",prevpx);
// Note the negative linear_x
//linear_x=-0.2;
//angular_z=1;
//theta=10;
//px = 5;
//py= 5;
//printf("Robot stuck");
if (!isRotate) {
ROS_INFO("Robot stuck");
double r2 = (double)rand()/((double)RAND_MAX/(M_PI/2));
double m2 = (double)rand()/((double)RAND_MAX/0.5);
//ROS_INFO("r2" << r2);
move(-m2, r2);
}
} else {
// One the robot becomes unstuck, then it moves around again normally
//linear_x = 0.2;
//angular_z = 0.2;
//ROS_INFO("Robot unstuck");
//checkcount=0;
}
//ROS_INFO("Current x position is: %f", px);
//ROS_INFO("Current y position is: %f", py);
prevpx = px;
prevpy = py;
}
// Send a velocity command
void SheepMove::move(double linearVelMPS, double angularVelRadPS) {
geometry_msgs::Twist msg; // The default constructor will set all commands to 0
msg.linear.x = linearVelMPS;
msg.angular.z = angularVelRadPS;
commandPub.publish(msg);
}
void SheepMove::statusCallback(se306Project::SheepMoveMsg msg) {
moveStatus = msg.moveCommand;
//TODO: set velocity from msg
}
// Process the incoming laser scan message
void SheepMove::commandCallback(const sensor_msgs::LaserScan::ConstPtr& msg) {
if (fsm == FSM_MOVE_FORWARD) {
// Compute the average range value between MIN_SCAN_ANGLE and MAX_SCAN_ANGLE
//
// NOTE: ideally, the following loop should have additional checks to ensure
// that indices are not out of bounds, by computing:
//
//- currAngle = msg->angle_min + msg->angle_increment*currIndex
//
// and then ensuring that currAngle <= msg->angle_max
unsigned int minIndex = ceil((MIN_SCAN_ANGLE_RAD - msg->angle_min) / msg->angle_increment);
unsigned int maxIndex = ceil((MAX_SCAN_ANGLE_RAD - msg->angle_min) / msg->angle_increment);
float closestRange = msg->ranges[minIndex];
for (unsigned int currIndex = minIndex + 1; currIndex < maxIndex; currIndex++) {
if (msg->ranges[currIndex] < closestRange) {
closestRange = msg->ranges[currIndex];
}
}
//if (closestRange == prevclosestRange) {
// ROS_INFO_STREAM("STUCK");
// move(-FORWARD_SPEED_MPS, ROTATE_SPEED_RADPS);
// //move(0, ROTATE_SPEED_RADPS);
//} else {
//ROS_INFO_STREAM("Range: " << closestRange);
prevclosestRange = closestRange;
if (closestRange < PROXIMITY_RANGE_M) {
fsm=FSM_ROTATE;
rotateStartTime=ros::Time::now();
//TODO: wtf is r2 for?
float r2 = (float)rand()/((float)RAND_MAX/100);
rotateDuration=ros::Duration(rand() % 2);
//fsm= FSM_MOVE_FORWARD;
}
//}
}
}
// Main FSM loop for ensuring that ROS messages are
// processed in a timely manner, and also for sending
// velocity controls to the simulated robot based on the FSM state
void SheepMove::spin() {
ros::Rate rate(10); // Specify the FSM loop rate in Hz
while (ros::ok()) { // Keep spinning loop until user presses Ctrl+C
if(moveStatus.compare("GO") == 0) {
std_msgs::String msg;
std::stringstream ss;
ss << "sheep_" << sheepNum << " -- px:" << px << " py:" << py << " theta:" << theta << " isRotate:" << isRotate;
msg.data = ss.str();
//ROS_INFO("%s", msg.data.c_str());
if (fsm == FSM_MOVE_FORWARD) {
//ROS_INFO_STREAM("Start forward");
move(FORWARD_SPEED_MPS, 0);
checkcount++;
if (checkcount > 3) {
isRotate=false;
}
}
if (fsm == FSM_ROTATE) {
//ROS_INFO_STREAM("Start rotate");
move(0, ROTATE_SPEED_RADPS);
rotateEndTime=ros::Time::now();
isRotate=true;
//ROS_INFO_STREAM("Time: " << rotateEndTime);
if ((rotateEndTime - rotateStartTime) > rotateDuration) {
fsm=FSM_MOVE_FORWARD;
//ROS_INFO_STREAM("End rotate");
checkcount=0;
}
}
sheepPosPub.publish(msg);
}//if not move, do anything?
ros::spinOnce(); // Need to call this function often to allow ROS to process incoming messages
rate.sleep(); // Sleep for the rest of the cycle, to enforce the FSM loop rate
}
}
SheepMove::SheepMove(int number) {
// Construst a new SheepMove object and hook up this ROS node
// to the simulated robot's velocity control and laser topics
//sheepNum = number;
// Initialize random time generator
srand(time(NULL));
moveStatus = "GO";
prevclosestRange = 0;
checkcount = 0;
prevpx = 0;
prevpx = 0;
sheepNum = number;
robotNum = 0;
}
void SheepMove::rosSetup(int argc, char **argv) {
std::ostringstream convertS;
std::ostringstream convertR;
std::string out;
ros::init(argc, argv, "sheepMove", ros::init_options::AnonymousName); // Initiate new ROS node named "sheepMoveX"
ros::NodeHandle nh;
ros::NodeHandle n("~");
if(n.getParam("sheepNum", sheepNum))
{
ROS_INFO_STREAM("Got sheepNum");
}else {
ROS_INFO_STREAM("Dafuq, ROS?");
}
if(n.getParam("robotNum", robotNum))
{
ROS_INFO_STREAM("Got robotNum");
}else {
ROS_INFO_STREAM("Dafuq, ROS?");
}
fsm = FSM_MOVE_FORWARD;
rotateStartTime = ros::Time(ros::Time::now());
rotateDuration = ros::Duration(0.f);
//setup talkies
// Advertise a new publisher for the simulated robot's velocity command topic
// (the second argument indicates that if multiple command messages are in
// the queue to be sent, only the last command will be sent)
convertR << robotNum; //needed as all stage robots are called robot_X
convertS << sheepNum;
std::string r = "robot_" + convertR.str();
ROS_INFO_STREAM(r);
std::string s = "sheep_" + convertS.str();
ROS_INFO_STREAM(s);
commandPub = nh.advertise<geometry_msgs::Twist>(r + "/cmd_vel",1000);
sheepPosPub = nh.advertise<std_msgs::String>("sheep_position",1000);
// Subscribe to the simulated robot's laser scan topic and tell ROS to call
// this->commandCallback() whenever a new message is published on that topic
laserSub = nh.subscribe<sensor_msgs::LaserScan>(r + "/base_scan", 1000, &SheepMove::commandCallback, this);
sheepStatusSub = nh.subscribe<se306Project::SheepMoveMsg>(s + "/move", 1000, &SheepMove::statusCallback, this);
StageOdo_sub = nh.subscribe<nav_msgs::Odometry>(r + "/odom",1000, &SheepMove::StageOdom_callback,this);
//ros::Subscriber StageOdo_sub = n.subscribe<nav_msgs::Odometry>("robot_0/odom",1000, StageOdom_callback);
SheepMove::spin(); // Execute FSM loop
}
int main(int argc, char **argv) {
//int number = 0;
//ros::param::get("sheepNum", number);
SheepMove walker(0); // Create new random walk object
walker.rosSetup(argc, argv);
return 0;
}
<commit_msg>Sheep basic goal movement implemented<commit_after>#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "sensor_msgs/LaserScan.h"
#include <nav_msgs/Odometry.h>
#include "std_msgs/String.h"
#include "se306Project/SheepMoveMsg.h"
#include <angles/angles.h>
#include <cstdlib> // Needed for rand()
#include <ctime> // Needed to seed random number generator with a time value
enum FSM {FSM_MOVE_FORWARD, FSM_ROTATE, FSM_GOTO_GOAL};
// Tunable parameters
// TODO: tune parameters as you see fit
const static double MIN_SCAN_ANGLE_RAD = -10.0/180*M_PI;
const static double MAX_SCAN_ANGLE_RAD = +10.0/180*M_PI;
const static float PROXIMITY_RANGE_M = .9; // Should be smaller than sensor_msgs::LaserScan::range_max
const static double FORWARD_SPEED_MPS = 0.2;
const static double ROTATE_SPEED_RADPS = M_PI/2;
class SheepMove {
public:
float prevclosestRange;
double linear_x;
double angular_z;
//pose of the robot
double px;
double py;
double theta;
double prevpx;
double prevpy;
double goalpx;
double goalpy;
bool isRotate;
bool isGoal;
bool correctHeading;
double currentHeading;
double goalHeading;
double dx;
double dy;
int checkcount;
int sheepNum;
int robotNum;
std::string moveStatus;
//methods
SheepMove(int);
void StageOdom_callback(nav_msgs::Odometry);
void move(double, double);
void statusCallback(se306Project::SheepMoveMsg);
void commandCallback(const sensor_msgs::LaserScan::ConstPtr&);
void spin();
void rosSetup(int argc, char **argv);
protected:
//talkie things
ros::Publisher commandPub; // Publisher to the simulated robot's velocity command topic
ros::Publisher sheepPosPub;
ros::Subscriber laserSub; // Subscriber to the simulated robot's laser scan topic
ros::Subscriber sheepStatusSub; //Subscriber to sheep_[sheepNum]/move topic
//move state things
enum FSM fsm; // Finite state machine for the random walk algorithm
ros::Time rotateStartTime; // Start time of the rotation
ros::Time rotateEndTime;
ros::Duration rotateDuration; // Duration of the rotation
ros::Subscriber StageOdo_sub;
};
void SheepMove::StageOdom_callback(nav_msgs::Odometry msg) {
//This is the call back function to process odometry messages coming from Stage.
px = msg.pose.pose.position.x;
//px = 5 + msg.pose.pose.position.x;
//py = 10 + msg.pose.pose.position.y;
py = msg.pose.pose.position.y;
//printf("%f",px);
if (!isGoal) {
// If the current position is the same the previous position, then the robot is stuck and needs to move around
if ((px == prevpx) && (py == prevpy)) {
//msg.pose.pose.position.x = 5;
//ROS_INFO("Prevpx: %f",prevpx);
// Note the negative linear_x
//linear_x=-0.2;
//angular_z=1;
//theta=10;
//px = 5;
//py= 5;
//printf("Robot stuck");
if (!isRotate) {
ROS_INFO("Robot stuck");
double r2 = (double)rand()/((double)RAND_MAX/(M_PI/2));
double m2 = (double)rand()/((double)RAND_MAX/0.5);
//ROS_INFO("r2" << r2);
move(-m2, r2);
}
} else {
// One the robot becomes unstuck, then it moves around again normally
//linear_x = 0.2;
//angular_z = 0.2;
//ROS_INFO("Robot unstuck");
//checkcount=0;
}
} else {
// Goal positions, need to do something like making this a new method that gets passed in the goal positions for where the grass is
goalpx=3;
goalpy=2;
px = msg.pose.pose.position.x;
py = msg.pose.pose.position.y;
// This is to currently stop them from wandering around.
//fsm = FSM_GOTO_GOAL;
px= floorf(px * 10 + 0.5) / 10;
py= floorf(py * 10 + 0.5) / 10;
currentHeading = angles::normalize_angle_positive(asin(msg.pose.pose.orientation.z) * 2); // Between (0,2Pi)
//if ((goalpx != round(px)) && (goalpy != round(py))) {
if ((fabs(goalpx-px) > 0.1 ) && (fabs(goalpy-py) > 0.1 )) { // Slightly more accurate when going to goal position
if (!correctHeading) {
// Distance between current position and goal position
dx = fabs(goalpx - px);
dy = fabs(goalpy - py);
// Calculates angle based on right-hand triangle trigonometry rules
goalHeading = atan(dy/dx);
//ROS_INFO("goalHeading: %f", goalHeading);
//ROS_INFO("currentHeading: %f", currentHeading);
// Below checks are to calculate what the final goalHeading is with respect to the whole world
if ((goalpx > px) && (goalpy > py)) {
// Don't need to actually do anything to goalHeading here
//ROS_INFO("goalpx > px & goalpy > py");
}
if ((goalpx < px) && (goalpy < py)) {
goalHeading= (M_PI + goalHeading);
//ROS_INFO("goalpx < px & goalpy < py");
}
if ((goalpx < px) && (goalpy > py)) {
goalHeading= M_PI - goalHeading;
//ROS_INFO("goalpx < px & goalpy > py");
}
if ((goalpx > px) && (goalpy < py)) {
goalHeading= (2*M_PI) - goalHeading;
//ROS_INFO("goalpx > px & goalpy < py");
}
// Rounds to 1dp, otherwise it would be near impossible for both headings to be the same
goalHeading= floorf(goalHeading * 10 + 0.5) / 10; // To round to 2dp, change the 10's to 100
currentHeading= floorf(currentHeading * 10 + 0.5) / 10;
ROS_INFO("currentHeading rounded: %f", currentHeading);
ROS_INFO("goalHeading rounded: %f", goalHeading);
if (currentHeading != goalHeading) {
move(0,1);
} else {
ROS_INFO("Correct heading");
correctHeading=true;
}
} else {
move(.2,0);
}
} else {
ROS_INFO("Reached goal");
isGoal=false;
fsm= FSM_MOVE_FORWARD;
// If the sheep is dragged to another position, the whole goal process is recalculated
correctHeading=false;
}
}
//ROS_INFO("Current x position is: %f", px);
//ROS_INFO("Current y position is: %f", py);
prevpx = px;
prevpy = py;
}
// Send a velocity command
void SheepMove::move(double linearVelMPS, double angularVelRadPS) {
geometry_msgs::Twist msg; // The default constructor will set all commands to 0
msg.linear.x = linearVelMPS;
msg.angular.z = angularVelRadPS;
commandPub.publish(msg);
}
void SheepMove::statusCallback(se306Project::SheepMoveMsg msg) {
moveStatus = msg.moveCommand;
//TODO: set velocity from msg
}
// Process the incoming laser scan message
void SheepMove::commandCallback(const sensor_msgs::LaserScan::ConstPtr& msg) {
if (fsm == FSM_MOVE_FORWARD) {
// Compute the average range value between MIN_SCAN_ANGLE and MAX_SCAN_ANGLE
//
// NOTE: ideally, the following loop should have additional checks to ensure
// that indices are not out of bounds, by computing:
//
//- currAngle = msg->angle_min + msg->angle_increment*currIndex
//
// and then ensuring that currAngle <= msg->angle_max
unsigned int minIndex = ceil((MIN_SCAN_ANGLE_RAD - msg->angle_min) / msg->angle_increment);
unsigned int maxIndex = ceil((MAX_SCAN_ANGLE_RAD - msg->angle_min) / msg->angle_increment);
float closestRange = msg->ranges[minIndex];
for (unsigned int currIndex = minIndex + 1; currIndex < maxIndex; currIndex++) {
if (msg->ranges[currIndex] < closestRange) {
closestRange = msg->ranges[currIndex];
}
}
//if (closestRange == prevclosestRange) {
// ROS_INFO_STREAM("STUCK");
// move(-FORWARD_SPEED_MPS, ROTATE_SPEED_RADPS);
// //move(0, ROTATE_SPEED_RADPS);
//} else {
//ROS_INFO_STREAM("Range: " << closestRange);
prevclosestRange = closestRange;
if (closestRange < PROXIMITY_RANGE_M) {
fsm=FSM_ROTATE;
rotateStartTime=ros::Time::now();
//TODO: wtf is r2 for?
float r2 = (float)rand()/((float)RAND_MAX/100);
rotateDuration=ros::Duration(rand() % 2);
//fsm= FSM_MOVE_FORWARD;
}
//}
}
}
// Main FSM loop for ensuring that ROS messages are
// processed in a timely manner, and also for sending
// velocity controls to the simulated robot based on the FSM state
void SheepMove::spin() {
ros::Rate rate(10); // Specify the FSM loop rate in Hz
while (ros::ok()) { // Keep spinning loop until user presses Ctrl+C
if(moveStatus.compare("GO") == 0) {
std_msgs::String msg;
std::stringstream ss;
ss << "sheep_" << sheepNum << " -- px:" << px << " py:" << py << " theta:" << theta << " isRotate:" << isRotate;
msg.data = ss.str();
//ROS_INFO("%s", msg.data.c_str());
if (fsm == FSM_MOVE_FORWARD) {
//ROS_INFO_STREAM("Start forward");
move(FORWARD_SPEED_MPS, 0);
checkcount++;
if (checkcount > 3) {
isRotate=false;
isGoal=false;
}
}
if (fsm == FSM_ROTATE) {
//ROS_INFO_STREAM("Start rotate");
move(0, ROTATE_SPEED_RADPS);
rotateEndTime=ros::Time::now();
isRotate=true;
isGoal=false;
//ROS_INFO_STREAM("Time: " << rotateEndTime);
if ((rotateEndTime - rotateStartTime) > rotateDuration) {
fsm=FSM_MOVE_FORWARD;
//ROS_INFO_STREAM("End rotate");
checkcount=0;
}
}
if (fsm == FSM_GOTO_GOAL) {
isGoal=true;
}
sheepPosPub.publish(msg);
}//if not move, do anything?
ros::spinOnce(); // Need to call this function often to allow ROS to process incoming messages
rate.sleep(); // Sleep for the rest of the cycle, to enforce the FSM loop rate
}
}
SheepMove::SheepMove(int number) {
// Construst a new SheepMove object and hook up this ROS node
// to the simulated robot's velocity control and laser topics
//sheepNum = number;
// Initialize random time generator
srand(time(NULL));
moveStatus = "GO";
prevclosestRange = 0;
checkcount = 0;
prevpx = 0;
prevpx = 0;
sheepNum = number;
robotNum = 0;
correctHeading = false;
}
void SheepMove::rosSetup(int argc, char **argv) {
std::ostringstream convertS;
std::ostringstream convertR;
std::string out;
ros::init(argc, argv, "sheepMove", ros::init_options::AnonymousName); // Initiate new ROS node named "sheepMoveX"
ros::NodeHandle nh;
ros::NodeHandle n("~");
if(n.getParam("sheepNum", sheepNum))
{
ROS_INFO_STREAM("Got sheepNum");
}else {
ROS_INFO_STREAM("Dafuq, ROS?");
}
if(n.getParam("robotNum", robotNum))
{
ROS_INFO_STREAM("Got robotNum");
}else {
ROS_INFO_STREAM("Dafuq, ROS?");
}
//fsm = FSM_MOVE_FORWARD;
fsm = FSM_GOTO_GOAL;
rotateStartTime = ros::Time(ros::Time::now());
rotateDuration = ros::Duration(0.f);
//setup talkies
// Advertise a new publisher for the simulated robot's velocity command topic
// (the second argument indicates that if multiple command messages are in
// the queue to be sent, only the last command will be sent)
convertR << robotNum; //needed as all stage robots are called robot_X
convertS << sheepNum;
std::string r = "robot_" + convertR.str();
ROS_INFO_STREAM(r);
std::string s = "sheep_" + convertS.str();
ROS_INFO_STREAM(s);
commandPub = nh.advertise<geometry_msgs::Twist>(r + "/cmd_vel",1000);
sheepPosPub = nh.advertise<std_msgs::String>("sheep_position",1000);
// Subscribe to the simulated robot's laser scan topic and tell ROS to call
// this->commandCallback() whenever a new message is published on that topic
laserSub = nh.subscribe<sensor_msgs::LaserScan>(r + "/base_scan", 1000, &SheepMove::commandCallback, this);
sheepStatusSub = nh.subscribe<se306Project::SheepMoveMsg>(s + "/move", 1000, &SheepMove::statusCallback, this);
StageOdo_sub = nh.subscribe<nav_msgs::Odometry>(r + "/odom",1000, &SheepMove::StageOdom_callback,this);
//ros::Subscriber StageOdo_sub = n.subscribe<nav_msgs::Odometry>("robot_0/odom",1000, StageOdom_callback);
SheepMove::spin(); // Execute FSM loop
}
int main(int argc, char **argv) {
//int number = 0;
//ros::param::get("sheepNum", number);
SheepMove walker(0); // Create new random walk object
walker.rosSetup(argc, argv);
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include "acmacs-base/sfinae.hh"
#include "acmacs-base/fmt.hh"
// ----------------------------------------------------------------------
#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wold-style-cast"
#pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
#pragma GCC diagnostic ignored "-Wdeprecated-volatile"
#pragma GCC diagnostic ignored "-Wundef"
#pragma GCC diagnostic ignored "-Wreserved-id-macro"
#pragma GCC diagnostic ignored "-Wsign-conversion"
#pragma GCC diagnostic ignored "-Wextra-semi-stmt"
// #pragma GCC diagnostic ignored ""
#endif
#ifdef __GNUG__
#endif
#include <libguile.h>
namespace guile
{
const inline auto VOID = SCM_UNSPECIFIED;
}
#pragma GCC diagnostic pop
// ----------------------------------------------------------------------
namespace guile
{
// struct Error : public std::runtime_error
// {
// using std::runtime_error::runtime_error;
// };
template <typename Func> constexpr inline auto subr(Func func) { return reinterpret_cast<scm_t_subr>(func); }
inline void load(std::string_view filename) { scm_c_primitive_load(filename.data()); }
inline void load(const std::vector<std::string_view>& filenames)
{
for (const auto& filename : filenames)
scm_c_primitive_load(filename.data());
}
inline std::string to_string(SCM src)
{
// if (!scm_is_string(src))
// throw Error{fmt::format("expected string but passed {}", "?")};
std::string result(scm_c_string_length(src), '?');
scm_to_locale_stringbuf(src, result.data(), result.size());
return result;
}
// https://devblogs.microsoft.com/oldnewthing/20200713-00/?p=103978
template <typename F> struct FunctionTraits;
template <typename R, typename... Args> struct FunctionTraits<R (*)(Args...)>
{
using Pointer = R (*)(Args...);
using RetType = R;
using ArgTypes = std::tuple<Args...>;
static constexpr std::size_t ArgCount = sizeof...(Args);
// template <std::size_t N> using NthArg = std::tuple_element_t<N, ArgTypes>;
};
// template <typename Arg> inline SCM to_scm(Arg arg)
// {
// static_assert(std::is_same_v<std::decay<Arg>, int>, "no to_scm specialization defined");
// return scm_from_signed_integer(arg);
// }
inline SCM to_scm(double arg) { return scm_from_double(arg); }
inline SCM to_scm(const std::string& arg) { return scm_from_locale_stringn(arg.data(), arg.size()); }
inline SCM to_scm() { return VOID; }
template <typename Value> inline Value from_scm(SCM arg)
{
static_assert(std::is_same_v<std::decay<Value>, int>, "no from_scm specialization defined");
return scm_to_int(arg);
}
template <> inline double from_scm<double>(SCM arg) { return scm_to_double(arg); }
template <> inline std::string from_scm<std::string>(SCM arg) { return to_string(arg); }
template <typename Name, typename Func> requires acmacs::sfinae::is_string_v<Name> void define(Name&& name, Func func)
{
const char* name_ptr{nullptr};
if constexpr (acmacs::sfinae::is_const_char_ptr_v<Name>)
name_ptr = name;
else
name_ptr = name.data();
scm_c_define_gsubr(name_ptr, FunctionTraits<Func>::ArgCount, 0, 0, guile::subr(func));
}
// initialize guile, call passed functions to define functions or load scripts from files
template <typename... Arg> inline void init(Arg&&... arg)
{
scm_init_guile();
const auto process = []<typename Val>(Val&& val) -> void {
if constexpr (std::is_invocable_v<Val>)
val();
else if constexpr (std::is_same_v<std::decay_t<Val>, std::string_view> || std::is_same_v<std::decay_t<Val>, std::vector<std::string_view>>)
load(val);
else
static_assert(std::is_same_v<Val, void>);
};
(process(std::forward<Arg>(arg)), ...);
}
} // namespace guile
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>guile interface improvements<commit_after>#pragma once
#include "acmacs-base/sfinae.hh"
#include "acmacs-base/fmt.hh"
// ----------------------------------------------------------------------
#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wold-style-cast"
#pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
#pragma GCC diagnostic ignored "-Wdeprecated-volatile"
#pragma GCC diagnostic ignored "-Wundef"
#pragma GCC diagnostic ignored "-Wreserved-id-macro"
#pragma GCC diagnostic ignored "-Wsign-conversion"
#pragma GCC diagnostic ignored "-Wextra-semi-stmt"
// #pragma GCC diagnostic ignored ""
#endif
#ifdef __GNUG__
#endif
#include <libguile.h>
namespace guile
{
const inline auto VOID = SCM_UNSPECIFIED;
}
#pragma GCC diagnostic pop
// ----------------------------------------------------------------------
namespace guile
{
// struct Error : public std::runtime_error
// {
// using std::runtime_error::runtime_error;
// };
// ----------------------------------------------------------------------
// init
// ----------------------------------------------------------------------
inline void load_script(std::string_view filename) { scm_c_primitive_load(filename.data()); }
inline void load_script(const std::vector<std::string_view>& filenames)
{
for (const auto& filename : filenames)
scm_c_primitive_load(filename.data());
}
// initialize guile, call passed functions to define functions or load scripts from files
template <typename... Arg> inline void init(Arg&&... arg)
{
scm_init_guile();
const auto process = []<typename Val>(Val&& val) -> void {
if constexpr (std::is_invocable_v<Val>)
val();
else if constexpr (std::is_same_v<std::decay_t<Val>, std::string_view> || std::is_same_v<std::decay_t<Val>, std::vector<std::string_view>>)
load_script(val);
else
static_assert(std::is_same_v<Val, void>);
};
(process(std::forward<Arg>(arg)), ...);
}
// ----------------------------------------------------------------------
// define
// ----------------------------------------------------------------------
template <typename Func> constexpr inline auto subr(Func func) { return reinterpret_cast<scm_t_subr>(func); }
// https://devblogs.microsoft.com/oldnewthing/20200713-00/?p=103978
template <typename F> struct FunctionTraits;
template <typename R, typename... Args> struct FunctionTraits<R (*)(Args...)>
{
using Pointer = R (*)(Args...);
using RetType = R;
using ArgTypes = std::tuple<Args...>;
static constexpr std::size_t ArgCount = sizeof...(Args);
// template <std::size_t N> using NthArg = std::tuple_element_t<N, ArgTypes>;
};
template <typename Name, typename Func> requires acmacs::sfinae::is_string_v<Name> void define(Name&& name, Func func)
{
const char* name_ptr{nullptr};
if constexpr (acmacs::sfinae::is_const_char_ptr_v<Name>)
name_ptr = name;
else
name_ptr = name.data();
scm_c_define_gsubr(name_ptr, FunctionTraits<Func>::ArgCount, 0, 0, guile::subr(func));
}
// ----------------------------------------------------------------------
// convert
// ----------------------------------------------------------------------
inline SCM symbol(const char* arg) { return scm_from_utf8_symbol(arg); }
inline SCM to_scm() { return VOID; }
inline SCM to_scm(double arg) { return scm_from_double(arg); }
inline SCM to_scm(size_t arg) { return scm_from_size_t(arg); }
inline SCM to_scm(ssize_t arg) { return scm_from_ssize_t(arg); }
inline SCM to_scm(const std::string& arg) { return scm_from_locale_stringn(arg.data(), arg.size()); }
template <typename Value> inline Value from_scm(SCM arg)
{
if constexpr (std::is_same_v<Value, std::string>) {
std::string result(scm_c_string_length(arg), '?');
scm_to_locale_stringbuf(arg, result.data(), result.size());
return result;
}
else if constexpr (std::is_convertible_v<Value, size_t>)
return scm_to_size_t(arg);
else if constexpr (std::is_same_v<Value, double>) // || std::is_same_v<Value, float>)
return scm_to_double(arg);
else
static_assert(std::is_same_v<std::decay<Value>, int>, "no from_scm specialization defined");
}
} // namespace guile
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>#include <Halide.h>
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <iostream>
using namespace Halide;
Var x, y, c;
double square(double x) {
return x * x;
}
template <typename T>
void test_function(Expr e, Image<T> &cpu_result, Image<T> &gpu_result) {
Func cpu, gpu;
Target cpu_target = get_host_target();
Target gpu_target = get_host_target();
gpu_target.set_feature(Target::OpenGL);
cpu(x, y, c) = e;
gpu(x, y, c) = e;
cpu.compile_jit(cpu_target);
gpu.compile_jit(gpu_target);
cpu.realize(cpu_result);
gpu.bound(c, 0, 3).glsl(x, y, c);
gpu.realize(gpu_result);
gpu_result.copy_to_host();
}
template <typename T>
bool test_exact(Expr r, Expr g, Expr b) {
Expr e = cast<T>(select(c == 0, r, c == 1, g, b));
const int W = 256, H = 256;
Image<T> cpu_result(W, H, 3);
Image<T> gpu_result(W, H, 3);
test_function(e, cpu_result, gpu_result);
double err = 0.0;
for (int y=0; y<gpu_result.height(); y++) {
for (int x=0; x<gpu_result.width(); x++) {
if (!(gpu_result(x, y, 0) == cpu_result(x, y, 0) &&
gpu_result(x, y, 1) == cpu_result(x, y, 1) &&
gpu_result(x, y, 2) == cpu_result(x, y, 2))) {
std::cerr << "Incorrect pixel for " << e << " at (" << x << ", " << y << ")\n"
<< " ("
<< (int)gpu_result(x, y, 0) << ", "
<< (int)gpu_result(x, y, 1) << ", "
<< (int)gpu_result(x, y, 2) << ") != ("
<< (int)cpu_result(x, y, 0) << ", "
<< (int)cpu_result(x, y, 1) << ", "
<< (int)cpu_result(x, y, 2)
<< ")\n";
return false;
}
}
}
return true;
}
template <typename T>
bool test_approx(Expr r, Expr g, Expr b, double rms_error) {
Expr e = cast<T>(select(c == 0, r, c == 1, g, b));
const int W = 256, H = 256;
Image<T> cpu_result(W, H, 3);
Image<T> gpu_result(W, H, 3);
test_function(e, cpu_result, gpu_result);
double err = 0.0;
for (int y=0; y<gpu_result.height(); y++) {
for (int x=0; x<gpu_result.width(); x++) {
err += square(gpu_result(x, y, 0) - cpu_result(x, y, 0));
err += square(gpu_result(x, y, 1) - cpu_result(x, y, 1));
err += square(gpu_result(x, y, 2) - cpu_result(x, y, 2));
}
}
err = sqrt(err / (W * H));
if (err > rms_error) {
std::cerr << "RMS error too large for " << e << ": "
<< err << " > " << rms_error << "\n";
return false;
} else {
return true;
}
}
int main() {
bool ok = true;
double rms;
ok = ok && test_exact<uint8_t>(0, 0, 0);
ok = ok && test_exact<uint8_t>(clamp(x + y, 0, 255), 0, 0);
ok = ok && test_exact<uint8_t>(
max(x, y),
cast<int>(min(cast<float>(x), cast<float>(y))),
clamp(x, 0, 10));
// Trigonometric functions in GLSL are fast but not very accurate,
// especially outside of 0..2pi.
Expr r = (256 * x + y) / ceilf(65536.f / (2 * 3.1415926536f));
ok = test_approx<float>(sin(r), cos(r), 0, 5e-7);
ok = ok && test_exact<uint8_t>(
(x - 127) / 3 + 127,
(x - 127) % 3 + 127,
0);
ok = ok && test_exact<uint8_t>(
lerp(cast<uint8_t>(x), cast<uint8_t>(y), cast<uint8_t>(128)),
lerp(cast<uint8_t>(x), cast<uint8_t>(y), 0.5f),
cast<uint8_t>(lerp(cast<float>(x), cast<float>(y), 0.2f)));
if (ok) {
printf("Success!\n");
return 0;
} else {
return 1;
}
}
<commit_msg>Fixed warnings in test for -Werror builds<commit_after>#include <Halide.h>
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <iostream>
using namespace Halide;
Var x, y, c;
double square(double x) {
return x * x;
}
template <typename T>
void test_function(Expr e, Image<T> &cpu_result, Image<T> &gpu_result) {
Func cpu, gpu;
Target cpu_target = get_host_target();
Target gpu_target = get_host_target();
gpu_target.set_feature(Target::OpenGL);
cpu(x, y, c) = e;
gpu(x, y, c) = e;
cpu.compile_jit(cpu_target);
gpu.compile_jit(gpu_target);
cpu.realize(cpu_result);
gpu.bound(c, 0, 3).glsl(x, y, c);
gpu.realize(gpu_result);
gpu_result.copy_to_host();
}
template <typename T>
bool test_exact(Expr r, Expr g, Expr b) {
Expr e = cast<T>(select(c == 0, r, c == 1, g, b));
const int W = 256, H = 256;
Image<T> cpu_result(W, H, 3);
Image<T> gpu_result(W, H, 3);
test_function(e, cpu_result, gpu_result);
for (int y=0; y<gpu_result.height(); y++) {
for (int x=0; x<gpu_result.width(); x++) {
if (!(gpu_result(x, y, 0) == cpu_result(x, y, 0) &&
gpu_result(x, y, 1) == cpu_result(x, y, 1) &&
gpu_result(x, y, 2) == cpu_result(x, y, 2))) {
std::cerr << "Incorrect pixel for " << e << " at (" << x << ", " << y << ")\n"
<< " ("
<< (int)gpu_result(x, y, 0) << ", "
<< (int)gpu_result(x, y, 1) << ", "
<< (int)gpu_result(x, y, 2) << ") != ("
<< (int)cpu_result(x, y, 0) << ", "
<< (int)cpu_result(x, y, 1) << ", "
<< (int)cpu_result(x, y, 2)
<< ")\n";
return false;
}
}
}
return true;
}
template <typename T>
bool test_approx(Expr r, Expr g, Expr b, double rms_error) {
Expr e = cast<T>(select(c == 0, r, c == 1, g, b));
const int W = 256, H = 256;
Image<T> cpu_result(W, H, 3);
Image<T> gpu_result(W, H, 3);
test_function(e, cpu_result, gpu_result);
double err = 0.0;
for (int y=0; y<gpu_result.height(); y++) {
for (int x=0; x<gpu_result.width(); x++) {
err += square(gpu_result(x, y, 0) - cpu_result(x, y, 0));
err += square(gpu_result(x, y, 1) - cpu_result(x, y, 1));
err += square(gpu_result(x, y, 2) - cpu_result(x, y, 2));
}
}
err = sqrt(err / (W * H));
if (err > rms_error) {
std::cerr << "RMS error too large for " << e << ": "
<< err << " > " << rms_error << "\n";
return false;
} else {
return true;
}
}
int main() {
bool ok = true;
ok = ok && test_exact<uint8_t>(0, 0, 0);
ok = ok && test_exact<uint8_t>(clamp(x + y, 0, 255), 0, 0);
ok = ok && test_exact<uint8_t>(
max(x, y),
cast<int>(min(cast<float>(x), cast<float>(y))),
clamp(x, 0, 10));
// Trigonometric functions in GLSL are fast but not very accurate,
// especially outside of 0..2pi.
Expr r = (256 * x + y) / ceilf(65536.f / (2 * 3.1415926536f));
ok = test_approx<float>(sin(r), cos(r), 0, 5e-7);
ok = ok && test_exact<uint8_t>(
(x - 127) / 3 + 127,
(x - 127) % 3 + 127,
0);
ok = ok && test_exact<uint8_t>(
lerp(cast<uint8_t>(x), cast<uint8_t>(y), cast<uint8_t>(128)),
lerp(cast<uint8_t>(x), cast<uint8_t>(y), 0.5f),
cast<uint8_t>(lerp(cast<float>(x), cast<float>(y), 0.2f)));
if (ok) {
printf("Success!\n");
return 0;
} else {
return 1;
}
}
<|endoftext|> |
<commit_before>
#include <cstdlib>
#include <iostream>
#include "gl-batch-context/Context.hpp"
int main(int /*argc*/, char** /*argv*/)
{
CPM_GL_CONTEXT_NS::Context* glContext =
CPM_GL_CONTEXT_NS::Context::createBatchContext(
640, 480, 32, 32, 0, false, false);
// Add a few quick OpenGL calls here to verify the context is working.
// Now that we are finished, delete the context.
delete glContext;
}
<commit_msg>Always return 0.<commit_after>
#include <cstdlib>
#include <iostream>
#include "gl-batch-context/Context.hpp"
int main(int /*argc*/, char** /*argv*/)
{
CPM_GL_CONTEXT_NS::Context* glContext =
CPM_GL_CONTEXT_NS::Context::createBatchContext(
640, 480, 32, 32, 0, false, false);
// Add a few quick OpenGL calls here to verify the context is working.
// Now that we are finished, delete the context.
delete glContext;
return 0;
}
<|endoftext|> |
<commit_before>//
// State.cpp
// Clock Signal
//
// Created by Thomas Harte on 14/05/2020.
// Copyright © 2020 Thomas Harte. All rights reserved.
//
#include "State.hpp"
#include <cassert>
using namespace CPU::MC68000;
State::State(const ProcessorBase &src): State() {
// Registers.
for(int c = 0; c < 7; ++c) {
registers.address[c] = src.address_[c].full;
registers.data[c] = src.data_[c].full;
}
registers.data[7] = src.data_[7].full;
registers.user_stack_pointer = src.is_supervisor_ ? src.stack_pointers_[0].full : src.address_[7].full;
registers.supervisor_stack_pointer = src.is_supervisor_ ? src.address_[7].full : src.stack_pointers_[1].full;
registers.status = src.get_status();
registers.program_counter = src.program_counter_.full;
registers.prefetch = src.prefetch_queue_.full;
registers.instruction = src.decoded_instruction_.full;
// Inputs.
inputs.bus_interrupt_level = uint8_t(src.bus_interrupt_level_);
inputs.dtack = src.dtack_;
inputs.is_peripheral_address = src.is_peripheral_address_;
inputs.bus_error = src.bus_error_;
inputs.bus_request = src.bus_request_;
inputs.bus_grant = false; // TODO (within the 68000).
inputs.halt = src.halt_;
// Execution state.
execution_state.e_clock_phase = src.e_clock_phase_.as<uint8_t>();
execution_state.effective_address[0] = src.effective_address_[0].full;
execution_state.effective_address[1] = src.effective_address_[1].full;
execution_state.source_data = src.source_bus_data_.full;
execution_state.destination_data = src.destination_bus_data_.full;
execution_state.last_trace_flag = src.last_trace_flag_;
execution_state.next_word = src.next_word_;
execution_state.dbcc_false_address = src.dbcc_false_address_;
execution_state.is_starting_interrupt = src.is_starting_interrupt_;
execution_state.pending_interrupt_level = uint8_t(src.pending_interrupt_level_);
execution_state.accepted_interrupt_level = uint8_t(src.accepted_interrupt_level_);
execution_state.movem_final_address = src.movem_final_address_;
static_assert(sizeof(execution_state.source_addresses) == sizeof(src.precomputed_addresses_));
memcpy(&execution_state.source_addresses, &src.precomputed_addresses_, sizeof(src.precomputed_addresses_));
// This is collapsed to a Boolean; if there is an active program then it's the
// one implied by the current instruction.
execution_state.active_program = src.active_program_;
// Slightly dodgy assumption here: the Phase enum will always exactly track
// the 68000's ExecutionState enum.
execution_state.phase = ExecutionState::Phase(src.execution_state_);
auto contained_by = [](const auto *source, const auto *reference) -> bool {
while(true) {
if(source == reference) return true;
if(source->is_terminal()) return false;
++source;
}
};
// Store enough information to relocate the MicroOp.
const ProcessorBase::MicroOp *micro_op_base = nullptr;
if(src.active_program_) {
micro_op_base = &src.all_micro_ops_[src.instructions[src.decoded_instruction_.full].micro_operations];
assert(contained_by(micro_op_base, src.active_micro_op_));
execution_state.micro_op_source = ExecutionState::MicroOpSource::ActiveProgram;
} else {
if(contained_by(src.long_exception_micro_ops_, src.active_micro_op_)) {
execution_state.micro_op_source = ExecutionState::MicroOpSource::LongException;
micro_op_base = src.long_exception_micro_ops_;
} else if(contained_by(src.short_exception_micro_ops_, src.active_micro_op_)) {
execution_state.micro_op_source = ExecutionState::MicroOpSource::ShortException;
micro_op_base = src.short_exception_micro_ops_;
} else if(contained_by(src.interrupt_micro_ops_, src.active_micro_op_)) {
execution_state.micro_op_source = ExecutionState::MicroOpSource::Interrupt;
micro_op_base = src.interrupt_micro_ops_;
} else {
assert(false);
}
}
execution_state.micro_op = uint8_t(src.active_micro_op_ - micro_op_base);
// Encode the BusStep.
struct BusStepOption {
const ProcessorBase::BusStep *const base;
const ExecutionState::BusStepSource source;
};
BusStepOption bus_step_options[] = {
{
src.reset_bus_steps_,
ExecutionState::BusStepSource::Reset
},
{
src.branch_taken_bus_steps_,
ExecutionState::BusStepSource::BranchTaken
},
{
src.branch_byte_not_taken_bus_steps_,
ExecutionState::BusStepSource::BranchByteNotTaken
},
{
src.branch_word_not_taken_bus_steps_,
ExecutionState::BusStepSource::BranchWordNotTaken
},
{
src.bsr_bus_steps_,
ExecutionState::BusStepSource::BSR
},
{
src.dbcc_condition_true_steps_,
ExecutionState::BusStepSource::DBccConditionTrue
},
{
src.dbcc_condition_false_no_branch_steps_,
ExecutionState::BusStepSource::DBccConditionFalseNoBranch
},
{
src.dbcc_condition_false_branch_steps_,
ExecutionState::BusStepSource::DBccConditionFalseBranch
},
{
src.movem_read_steps_,
ExecutionState::BusStepSource::MovemRead
},
{
src.movem_write_steps_,
ExecutionState::BusStepSource::MovemWrite
},
{
src.trap_steps_,
ExecutionState::BusStepSource::Trap
},
{
src.bus_error_steps_,
ExecutionState::BusStepSource::BusError
},
{
&src.all_bus_steps_[src.active_micro_op_->bus_program],
ExecutionState::BusStepSource::FollowMicroOp
},
{nullptr}
};
const BusStepOption *bus_step_option = bus_step_options;
const ProcessorBase::BusStep *bus_step_base = nullptr;
while(bus_step_option->base) {
if(contained_by(bus_step_option->base, src.active_step_)) {
bus_step_base = bus_step_option->base;
execution_state.bus_step_source = bus_step_option->source;
break;
}
++bus_step_option;
}
assert(bus_step_base);
execution_state.bus_step = uint8_t(src.active_step_ - bus_step_base);
}
void State::apply(ProcessorBase &target) {
}
// Boilerplate follows here, to establish 'reflection'.
State::State() {
if(needs_declare()) {
DeclareField(registers);
DeclareField(execution_state);
DeclareField(inputs);
}
}
State::Registers::Registers() {
if(needs_declare()) {
DeclareField(data);
DeclareField(address);
DeclareField(user_stack_pointer);
DeclareField(supervisor_stack_pointer);
DeclareField(status);
DeclareField(program_counter);
DeclareField(prefetch);
DeclareField(instruction);
}
}
State::Inputs::Inputs() {
if(needs_declare()) {
DeclareField(bus_interrupt_level);
DeclareField(dtack);
DeclareField(is_peripheral_address);
DeclareField(bus_error);
DeclareField(bus_request);
DeclareField(bus_grant);
DeclareField(halt);
}
}
State::ExecutionState::ExecutionState() {
if(needs_declare()) {
DeclareField(e_clock_phase);
DeclareField(effective_address);
DeclareField(source_data);
DeclareField(destination_data);
DeclareField(last_trace_flag);
DeclareField(next_word);
DeclareField(dbcc_false_address);
DeclareField(is_starting_interrupt);
DeclareField(pending_interrupt_level);
DeclareField(accepted_interrupt_level);
DeclareField(active_program);
DeclareField(movem_final_address);
DeclareField(source_addresses);
AnnounceEnum(Phase);
DeclareField(phase);
AnnounceEnum(MicroOpSource);
DeclareField(micro_op_source);
DeclareField(micro_op);
AnnounceEnum(BusStepSource);
DeclareField(bus_step_source);
DeclareField(bus_step);
}
}
<commit_msg>Implements `apply`.<commit_after>//
// State.cpp
// Clock Signal
//
// Created by Thomas Harte on 14/05/2020.
// Copyright © 2020 Thomas Harte. All rights reserved.
//
#include "State.hpp"
#include <cassert>
using namespace CPU::MC68000;
State::State(const ProcessorBase &src): State() {
// Registers.
for(int c = 0; c < 7; ++c) {
registers.address[c] = src.address_[c].full;
registers.data[c] = src.data_[c].full;
}
registers.data[7] = src.data_[7].full;
registers.user_stack_pointer = src.is_supervisor_ ? src.stack_pointers_[0].full : src.address_[7].full;
registers.supervisor_stack_pointer = src.is_supervisor_ ? src.address_[7].full : src.stack_pointers_[1].full;
registers.status = src.get_status();
registers.program_counter = src.program_counter_.full;
registers.prefetch = src.prefetch_queue_.full;
registers.instruction = src.decoded_instruction_.full;
// Inputs.
inputs.bus_interrupt_level = uint8_t(src.bus_interrupt_level_);
inputs.dtack = src.dtack_;
inputs.is_peripheral_address = src.is_peripheral_address_;
inputs.bus_error = src.bus_error_;
inputs.bus_request = src.bus_request_;
inputs.bus_grant = false; // TODO (within the 68000).
inputs.halt = src.halt_;
// Execution state.
execution_state.e_clock_phase = src.e_clock_phase_.as<uint8_t>();
execution_state.effective_address[0] = src.effective_address_[0].full;
execution_state.effective_address[1] = src.effective_address_[1].full;
execution_state.source_data = src.source_bus_data_.full;
execution_state.destination_data = src.destination_bus_data_.full;
execution_state.last_trace_flag = src.last_trace_flag_;
execution_state.next_word = src.next_word_;
execution_state.dbcc_false_address = src.dbcc_false_address_;
execution_state.is_starting_interrupt = src.is_starting_interrupt_;
execution_state.pending_interrupt_level = uint8_t(src.pending_interrupt_level_);
execution_state.accepted_interrupt_level = uint8_t(src.accepted_interrupt_level_);
execution_state.movem_final_address = src.movem_final_address_;
static_assert(sizeof(execution_state.source_addresses) == sizeof(src.precomputed_addresses_));
memcpy(&execution_state.source_addresses, &src.precomputed_addresses_, sizeof(src.precomputed_addresses_));
// This is collapsed to a Boolean; if there is an active program then it's the
// one implied by the current instruction.
execution_state.active_program = src.active_program_;
// Slightly dodgy assumption here: the Phase enum will always exactly track
// the 68000's ExecutionState enum.
execution_state.phase = ExecutionState::Phase(src.execution_state_);
auto contained_by = [](const auto *source, const auto *reference) -> bool {
while(true) {
if(source == reference) return true;
if(source->is_terminal()) return false;
++source;
}
};
// Store enough information to relocate the MicroOp.
const ProcessorBase::MicroOp *micro_op_base = nullptr;
if(src.active_program_) {
micro_op_base = &src.all_micro_ops_[src.instructions[src.decoded_instruction_.full].micro_operations];
assert(contained_by(micro_op_base, src.active_micro_op_));
execution_state.micro_op_source = ExecutionState::MicroOpSource::ActiveProgram;
} else {
if(contained_by(src.long_exception_micro_ops_, src.active_micro_op_)) {
execution_state.micro_op_source = ExecutionState::MicroOpSource::LongException;
micro_op_base = src.long_exception_micro_ops_;
} else if(contained_by(src.short_exception_micro_ops_, src.active_micro_op_)) {
execution_state.micro_op_source = ExecutionState::MicroOpSource::ShortException;
micro_op_base = src.short_exception_micro_ops_;
} else if(contained_by(src.interrupt_micro_ops_, src.active_micro_op_)) {
execution_state.micro_op_source = ExecutionState::MicroOpSource::Interrupt;
micro_op_base = src.interrupt_micro_ops_;
} else {
assert(false);
}
}
execution_state.micro_op = uint8_t(src.active_micro_op_ - micro_op_base);
// Encode the BusStep.
struct BusStepOption {
const ProcessorBase::BusStep *const base;
const ExecutionState::BusStepSource source;
};
BusStepOption bus_step_options[] = {
{
src.reset_bus_steps_,
ExecutionState::BusStepSource::Reset
},
{
src.branch_taken_bus_steps_,
ExecutionState::BusStepSource::BranchTaken
},
{
src.branch_byte_not_taken_bus_steps_,
ExecutionState::BusStepSource::BranchByteNotTaken
},
{
src.branch_word_not_taken_bus_steps_,
ExecutionState::BusStepSource::BranchWordNotTaken
},
{
src.bsr_bus_steps_,
ExecutionState::BusStepSource::BSR
},
{
src.dbcc_condition_true_steps_,
ExecutionState::BusStepSource::DBccConditionTrue
},
{
src.dbcc_condition_false_no_branch_steps_,
ExecutionState::BusStepSource::DBccConditionFalseNoBranch
},
{
src.dbcc_condition_false_branch_steps_,
ExecutionState::BusStepSource::DBccConditionFalseBranch
},
{
src.movem_read_steps_,
ExecutionState::BusStepSource::MovemRead
},
{
src.movem_write_steps_,
ExecutionState::BusStepSource::MovemWrite
},
{
src.trap_steps_,
ExecutionState::BusStepSource::Trap
},
{
src.bus_error_steps_,
ExecutionState::BusStepSource::BusError
},
{
&src.all_bus_steps_[src.active_micro_op_->bus_program],
ExecutionState::BusStepSource::FollowMicroOp
},
{nullptr}
};
const BusStepOption *bus_step_option = bus_step_options;
const ProcessorBase::BusStep *bus_step_base = nullptr;
while(bus_step_option->base) {
if(contained_by(bus_step_option->base, src.active_step_)) {
bus_step_base = bus_step_option->base;
execution_state.bus_step_source = bus_step_option->source;
break;
}
++bus_step_option;
}
assert(bus_step_base);
execution_state.bus_step = uint8_t(src.active_step_ - bus_step_base);
}
void State::apply(ProcessorBase &target) {
// Registers.
for(int c = 0; c < 7; ++c) {
target.address_[c].full = registers.address[c];
target.data_[c].full = registers.data[c];
}
target.data_[7].full = registers.data[7];
target.stack_pointers_[0] = registers.user_stack_pointer;
target.stack_pointers_[1] = registers.supervisor_stack_pointer;
target.address_[7] = target.stack_pointers_[(registers.status & 0x2000) >> 13];
target.set_status(registers.status);
target.program_counter_.full = registers.program_counter;
target.prefetch_queue_.full = registers.prefetch;
target.decoded_instruction_.full = registers.instruction;
// Inputs.
target.bus_interrupt_level_ = inputs.bus_interrupt_level;
target.dtack_ = inputs.dtack;
target.is_peripheral_address_ = inputs.is_peripheral_address;
target.bus_error_ = inputs.bus_error;
target.bus_request_ = inputs.bus_request;
// TODO: bus_grant.
target.halt_ = inputs.halt;
// Execution state.
target.e_clock_phase_ = HalfCycles(execution_state.e_clock_phase);
target.effective_address_[0].full = execution_state.effective_address[0];
target.effective_address_[1].full = execution_state.effective_address[1];
target.source_bus_data_.full = execution_state.source_data;
target.destination_bus_data_.full = execution_state.destination_data;
target.last_trace_flag_ = execution_state.last_trace_flag;
target.next_word_ = execution_state.next_word;
target.dbcc_false_address_ = execution_state.dbcc_false_address;
target.is_starting_interrupt_ = execution_state.is_starting_interrupt;
target.pending_interrupt_level_ = execution_state.pending_interrupt_level;
target.accepted_interrupt_level_ = execution_state.accepted_interrupt_level;
target.movem_final_address_ = execution_state.movem_final_address;
static_assert(sizeof(execution_state.source_addresses) == sizeof(target.precomputed_addresses_));
memcpy(&target.precomputed_addresses_, &execution_state.source_addresses, sizeof(target.precomputed_addresses_));
// See above; this flag indicates whether to populate the field.
target.active_program_ =
execution_state.active_program ?
&target.instructions[target.decoded_instruction_.full] : nullptr;
// Dodgy assumption duplicated here from above.
target.execution_state_ = CPU::MC68000::ProcessorStorage::ExecutionState(execution_state.phase);
// Decode the MicroOp.
switch(execution_state.micro_op_source) {
case ExecutionState::MicroOpSource::ActiveProgram:
target.active_micro_op_ = &target.all_micro_ops_[target.active_program_->micro_operations];
break;
case ExecutionState::MicroOpSource::LongException:
target.active_micro_op_ = target.long_exception_micro_ops_;
break;
case ExecutionState::MicroOpSource::ShortException:
target.active_micro_op_ = target.short_exception_micro_ops_;
break;
case ExecutionState::MicroOpSource::Interrupt:
target.active_micro_op_ = target.interrupt_micro_ops_;
break;
}
target.active_micro_op_ += execution_state.micro_op;
// Decode the BusStep.
switch(execution_state.bus_step_source) {
case ExecutionState::BusStepSource::Reset:
target.active_step_ = target.reset_bus_steps_;
break;
case ExecutionState::BusStepSource::BranchTaken:
target.active_step_ = target.branch_taken_bus_steps_;
break;
case ExecutionState::BusStepSource::BranchByteNotTaken:
target.active_step_ = target.branch_byte_not_taken_bus_steps_;
break;
case ExecutionState::BusStepSource::BranchWordNotTaken:
target.active_step_ = target.branch_word_not_taken_bus_steps_;
break;
case ExecutionState::BusStepSource::BSR:
target.active_step_ = target.bsr_bus_steps_;
break;
case ExecutionState::BusStepSource::DBccConditionTrue:
target.active_step_ = target.dbcc_condition_true_steps_;
break;
case ExecutionState::BusStepSource::DBccConditionFalseNoBranch:
target.active_step_ = target.dbcc_condition_false_no_branch_steps_;
break;
case ExecutionState::BusStepSource::DBccConditionFalseBranch:
target.active_step_ = target.dbcc_condition_false_branch_steps_;
break;
case ExecutionState::BusStepSource::MovemRead:
target.active_step_ = target.movem_read_steps_;
break;
case ExecutionState::BusStepSource::MovemWrite:
target.active_step_ = target.movem_write_steps_;
break;
case ExecutionState::BusStepSource::Trap:
target.active_step_ = target.trap_steps_;
break;
case ExecutionState::BusStepSource::BusError:
target.active_step_ = target.bus_error_steps_;
break;
case ExecutionState::BusStepSource::FollowMicroOp:
target.active_step_ = &target.all_bus_steps_[target.active_micro_op_->bus_program];
break;
}
target.active_step_ += execution_state.bus_step;
}
// Boilerplate follows here, to establish 'reflection'.
State::State() {
if(needs_declare()) {
DeclareField(registers);
DeclareField(execution_state);
DeclareField(inputs);
}
}
State::Registers::Registers() {
if(needs_declare()) {
DeclareField(data);
DeclareField(address);
DeclareField(user_stack_pointer);
DeclareField(supervisor_stack_pointer);
DeclareField(status);
DeclareField(program_counter);
DeclareField(prefetch);
DeclareField(instruction);
}
}
State::Inputs::Inputs() {
if(needs_declare()) {
DeclareField(bus_interrupt_level);
DeclareField(dtack);
DeclareField(is_peripheral_address);
DeclareField(bus_error);
DeclareField(bus_request);
DeclareField(bus_grant);
DeclareField(halt);
}
}
State::ExecutionState::ExecutionState() {
if(needs_declare()) {
DeclareField(e_clock_phase);
DeclareField(effective_address);
DeclareField(source_data);
DeclareField(destination_data);
DeclareField(last_trace_flag);
DeclareField(next_word);
DeclareField(dbcc_false_address);
DeclareField(is_starting_interrupt);
DeclareField(pending_interrupt_level);
DeclareField(accepted_interrupt_level);
DeclareField(active_program);
DeclareField(movem_final_address);
DeclareField(source_addresses);
AnnounceEnum(Phase);
DeclareField(phase);
AnnounceEnum(MicroOpSource);
DeclareField(micro_op_source);
DeclareField(micro_op);
AnnounceEnum(BusStepSource);
DeclareField(bus_step_source);
DeclareField(bus_step);
}
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <iostream>
#include <fstream>
#include <istream>
#include <exception>
#include <stdexcept>
#include "stan/gm/ast_def.cpp"
#include "stan/gm/parser.hpp"
#include <stan/gm/generator.hpp>
#include <stan/gm/grammars/program_grammar_def.hpp>
#include <stan/gm/grammars/whitespace_grammar_def.hpp>
#include <stan/gm/grammars/expression_grammar_def.hpp>
#include <stan/gm/grammars/statement_grammar_def.hpp>
#include <stan/gm/grammars/var_decls_grammar_def.hpp>
bool is_parsable(const std::string& file_name) {
stan::gm::program prog;
std::ifstream fs(file_name.c_str());
bool parsable = stan::gm::parse(0, fs, file_name, prog);
return parsable;
}
TEST(gm_parser,eight_schools) {
EXPECT_TRUE(is_parsable("src/models/misc/eight_schools/eight_schools.stan"));
}
TEST(gm_parser,bugs_1_kidney) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/kidney/kidney.stan"));
}
/*TEST(gm_parser,bugs_1_leuk) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/leuk/leuk.stan"));
}*/
/*TEST(gm_parser,bugs_1_leukfr) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/leukfr/leukfr.stan"));
}*/
TEST(gm_parser,bugs_1_mice) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/mice/mice.stan"));
}
TEST(gm_parser,bugs_1_oxford) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/oxford/oxford.stan"));
}
TEST(gm_parser,bugs_1_rats) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/rats/rats.stan"));
}
TEST(gm_parser,bugs_1_salm) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/salm/salm.stan"));
}
TEST(gm_parser,bugs_1_seeds) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/seeds/seeds.stan"));
}
TEST(gm_parser,bugs_1_surgical) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/surgical/surgical.stan"));
}
TEST(gm_parser,bugs_2_beetles_cloglog) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/beetles/beetles_cloglog.stan"));
}
TEST(gm_parser,bugs_2_beetles_logit) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/beetles/beetles_logit.stan"));
}
TEST(gm_parser,bugs_2_beetles_probit) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/beetles/beetles_probit.stan"));
}
TEST(gm_parser,bugs_2_birats) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/birats/birats.stan"));
}
TEST(gm_parser,bugs_2_dugongs) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/dugongs/dugongs.stan"));
}
TEST(gm_parser,bugs_2_eyes) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/eyes/eyes.stan"));
}
TEST(gm_parser,bugs_2_ice) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/ice/ice.stan"));
}
/*TEST(gm_parser,bugs_2_stagnant) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/stagnant/stagnant.stan"));
}*/
TEST(gm_parser,good_trunc) {
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_trunc.stan"));
}
TEST(gm_parser,good_vec_constraints) {
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_trunc.stan"));
}
TEST(gm_parser,good_const) {
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_const.stan"));
}
TEST(gm_parser,good_matrix_ops) {
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_matrix_ops.stan"));
}
TEST(gm_parser,good_funs) {
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_funs.stan"));
}
TEST(gm_parser,triangle_lp) {
EXPECT_TRUE(is_parsable("src/models/basic_distributions/triangle.stan"));
}
TEST(gm_parser,good_vars) {
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_vars.stan"));
}
TEST(gm_parser,good_intercept_var) {
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_intercept_var.stan"));
}
TEST(gm_parser,good_cov) {
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_cov.stan"));
}
TEST(gm_parser,parsable_test_bad1) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad1.stan"),
std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad2) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad2.stan"),
std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad3) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad3.stan"),
std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad4) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad4.stan"),
std::invalid_argument);
}
// TEST(gm_parser,parsable_test_bad5) {
// EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad5.stan"),
// std::invalid_argument);
// }
TEST(gm_parser,parsable_test_bad6) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad6.stan"),
std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad7) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad7.stan"),
std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad8) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad8.stan"),
std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad9) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad9.stan"),
std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad10) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad10.stan"),
std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad11) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad11.stan"),
std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad_trunc) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_trunc1.stan"),
std::invalid_argument);
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_trunc2.stan"),
std::invalid_argument);
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_trunc3.stan"),
std::invalid_argument);
}
TEST(gm_parser,function_signatures) {
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/function_signatures1.stan"));
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/function_signatures2.stan"));
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/function_signatures3.stan"));
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/function_signatures4.stan"));
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/function_signatures5.stan"));
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/function_signatures6.stan"));
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/function_signatures7.stan"));
}
<commit_msg>replaced _def.hpp with .hpp includes for grammars/ast<commit_after>#include <gtest/gtest.h>
#include <iostream>
#include <fstream>
#include <istream>
#include <exception>
#include <stdexcept>
#include "stan/gm/ast.hpp"
#include "stan/gm/parser.hpp"
#include <stan/gm/generator.hpp>
#include <stan/gm/grammars/program_grammar.hpp>
#include <stan/gm/grammars/whitespace_grammar.hpp>
#include <stan/gm/grammars/expression_grammar.hpp>
#include <stan/gm/grammars/statement_grammar.hpp>
#include <stan/gm/grammars/var_decls_grammar.hpp>
bool is_parsable(const std::string& file_name) {
stan::gm::program prog;
std::ifstream fs(file_name.c_str());
bool parsable = stan::gm::parse(0, fs, file_name, prog);
return parsable;
}
TEST(gm_parser,eight_schools) {
EXPECT_TRUE(is_parsable("src/models/misc/eight_schools/eight_schools.stan"));
}
TEST(gm_parser,bugs_1_kidney) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/kidney/kidney.stan"));
}
/*TEST(gm_parser,bugs_1_leuk) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/leuk/leuk.stan"));
}*/
/*TEST(gm_parser,bugs_1_leukfr) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/leukfr/leukfr.stan"));
}*/
TEST(gm_parser,bugs_1_mice) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/mice/mice.stan"));
}
TEST(gm_parser,bugs_1_oxford) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/oxford/oxford.stan"));
}
TEST(gm_parser,bugs_1_rats) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/rats/rats.stan"));
}
TEST(gm_parser,bugs_1_salm) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/salm/salm.stan"));
}
TEST(gm_parser,bugs_1_seeds) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/seeds/seeds.stan"));
}
TEST(gm_parser,bugs_1_surgical) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol1/surgical/surgical.stan"));
}
TEST(gm_parser,bugs_2_beetles_cloglog) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/beetles/beetles_cloglog.stan"));
}
TEST(gm_parser,bugs_2_beetles_logit) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/beetles/beetles_logit.stan"));
}
TEST(gm_parser,bugs_2_beetles_probit) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/beetles/beetles_probit.stan"));
}
TEST(gm_parser,bugs_2_birats) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/birats/birats.stan"));
}
TEST(gm_parser,bugs_2_dugongs) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/dugongs/dugongs.stan"));
}
TEST(gm_parser,bugs_2_eyes) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/eyes/eyes.stan"));
}
TEST(gm_parser,bugs_2_ice) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/ice/ice.stan"));
}
/*TEST(gm_parser,bugs_2_stagnant) {
EXPECT_TRUE(is_parsable("src/models/bugs_examples/vol2/stagnant/stagnant.stan"));
}*/
TEST(gm_parser,good_trunc) {
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_trunc.stan"));
}
TEST(gm_parser,good_vec_constraints) {
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_trunc.stan"));
}
TEST(gm_parser,good_const) {
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_const.stan"));
}
TEST(gm_parser,good_matrix_ops) {
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_matrix_ops.stan"));
}
TEST(gm_parser,good_funs) {
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_funs.stan"));
}
TEST(gm_parser,triangle_lp) {
EXPECT_TRUE(is_parsable("src/models/basic_distributions/triangle.stan"));
}
TEST(gm_parser,good_vars) {
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_vars.stan"));
}
TEST(gm_parser,good_intercept_var) {
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_intercept_var.stan"));
}
TEST(gm_parser,good_cov) {
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/good_cov.stan"));
}
TEST(gm_parser,parsable_test_bad1) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad1.stan"),
std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad2) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad2.stan"),
std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad3) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad3.stan"),
std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad4) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad4.stan"),
std::invalid_argument);
}
// TEST(gm_parser,parsable_test_bad5) {
// EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad5.stan"),
// std::invalid_argument);
// }
TEST(gm_parser,parsable_test_bad6) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad6.stan"),
std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad7) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad7.stan"),
std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad8) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad8.stan"),
std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad9) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad9.stan"),
std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad10) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad10.stan"),
std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad11) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad11.stan"),
std::invalid_argument);
}
TEST(gm_parser,parsable_test_bad_trunc) {
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_trunc1.stan"),
std::invalid_argument);
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_trunc2.stan"),
std::invalid_argument);
EXPECT_THROW(is_parsable("src/test/gm/model_specs/bad_trunc3.stan"),
std::invalid_argument);
}
TEST(gm_parser,function_signatures) {
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/function_signatures1.stan"));
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/function_signatures2.stan"));
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/function_signatures3.stan"));
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/function_signatures4.stan"));
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/function_signatures5.stan"));
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/function_signatures6.stan"));
EXPECT_TRUE(is_parsable("src/test/gm/model_specs/function_signatures7.stan"));
}
<|endoftext|> |
<commit_before>#include <iostream>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Main
#include <boost/test/unit_test.hpp>
#include "protocolparser.h"
using namespace Akumuli;
BOOST_AUTO_TEST_CASE(Test_protocol_parse_1) {
BOOST_FAIL("Implement tests!");
}
<commit_msg>Fix build<commit_after>#include <iostream>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Main
#include <boost/test/unit_test.hpp>
#include "protocolparser.h"
using namespace Akumuli;
BOOST_AUTO_TEST_CASE(Test_protocol_parse_1) {
}
<|endoftext|> |
<commit_before>// - Tested
#define MSOFACTIONS
#define CRB_CONVOYS
#define RMM_ENEMYPOP
#define CRB_TERRORISTS
#define RMM_ZORA
// - To Test
#define WICT_ENEMYPOP
#define BIS_WARFARE<commit_msg>- Warfare module disabled by default<commit_after>// - Tested
#define MSOFACTIONS
#define CRB_CONVOYS
#define RMM_ENEMYPOP
#define CRB_TERRORISTS
#define RMM_ZORA
// - To Test
#define WICT_ENEMYPOP
//#define BIS_WARFARE<|endoftext|> |
<commit_before>#include <algorithm>
#include "Game_state_machine.h"
#include "utils.h"
void Game_state_machine::push_state(Game_state* state) {
m_states.push_back(state);
m_states.back()->on_enter();
LOG << "PSH states:"; std::for_each(m_states.begin(), m_states.end(), [](Game_state* gs) {LOG << gs->get_state_id(); });
}
void Game_state_machine::pop_state() {
if (!m_states.empty()) {
if (m_states.back()->on_exit()) {
delete m_states.back();
m_states.pop_back();
}
}
LOG << "POP states:"; std::for_each(m_states.begin(), m_states.end(), [](Game_state* gs) {LOG << gs->get_state_id(); });
}
void Game_state_machine::change_state(Game_state* state) {
if (!m_states.empty()) {
if (m_states.back()->get_state_id() == state->get_state_id())
return;
pop_state();
}
push_state(state);
LOG << "CHG states:"; std::for_each(m_states.begin(), m_states.end(), [](Game_state* gs) {LOG << gs->get_state_id(); });
}
void Game_state_machine::update() {
if (!m_states.empty())
m_states.back()->update();
}
void Game_state_machine::render() {
if (!m_states.empty())
m_states.back()->render();
}
const Game_state* Game_state_machine::get_current_state() const {
if (!m_states.empty())
return m_states.back();
return 0;
}
<commit_msg>fixed memory corruption<commit_after>#include <algorithm>
#include "Game_state_machine.h"
#include "utils.h"
void Game_state_machine::push_state(Game_state* state) {
m_states.push_back(state);
m_states.back()->on_enter();
LOG << "PSH states:"; std::for_each(m_states.begin(), m_states.end(), [](Game_state* gs) {LOG << gs->get_state_id(); });
}
void Game_state_machine::pop_state() {
if (!m_states.empty()) {
if (m_states.back()->on_exit()) {
//delete m_states.back();
m_states.pop_back();
}
}
LOG << "POP states:"; std::for_each(m_states.begin(), m_states.end(), [](Game_state* gs) {LOG << gs->get_state_id(); });
}
void Game_state_machine::change_state(Game_state* state) {
if (!m_states.empty()) {
if (m_states.back()->get_state_id() == state->get_state_id())
return;
pop_state();
}
push_state(state);
LOG << "CHG states:"; std::for_each(m_states.begin(), m_states.end(), [](Game_state* gs) {LOG << gs->get_state_id(); });
}
void Game_state_machine::update() {
if (!m_states.empty())
m_states.back()->update();
}
void Game_state_machine::render() {
if (!m_states.empty())
m_states.back()->render();
}
const Game_state* Game_state_machine::get_current_state() const {
if (!m_states.empty())
return m_states.back();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)
*
* 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.
*
*/
// Standard includes
#include <iostream>
// Third party includes
#include <boost/algorithm/string/replace.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
// Local VOTCA includes
#include "votca/tools/application.h"
#include "votca/tools/globals.h"
#include "votca/tools/property.h"
#include "votca/tools/propertyiomanipulator.h"
#include "votca/tools/version.h"
using namespace std;
using namespace votca::tools;
namespace po = boost::program_options;
class VotcaProperty final : public Application {
public:
VotcaProperty() = default;
~VotcaProperty() = default;
string ProgramName() { return "votca_property"; }
void HelpText(ostream& out) { out << "Helper for parsing XML files"; }
void Initialize() {
format = "XML";
level = 1;
AddProgramOptions()("file", po::value<string>(), "xml file to parse")(
"format", po::value<string>(), "output format [XML TXT]")(
"level", po::value<votca::Index>(), "output from this level ");
};
bool EvaluateOptions() {
CheckRequired("file", "Missing XML file");
return true;
};
void Run() {
file = OptionsMap()["file"].as<string>();
if (OptionsMap().count("format")) {
format = OptionsMap()["format"].as<string>();
}
if (OptionsMap().count("level")) {
level = OptionsMap()["level"].as<votca::Index>();
}
try {
Property p;
map<string, PropertyIOManipulator*> mformat_;
mformat_["XML"] = &XML;
mformat_["TXT"] = &TXT;
mformat_["HLP"] = &HLP;
p.LoadFromXML(file);
if (mformat_.find(format) != mformat_.end()) {
PropertyIOManipulator* piom = mformat_.find(format)->second;
piom->setLevel(level);
piom->setIndentation("");
piom->setColorScheme<csRGB>();
cout << *piom << p;
} else {
cout << "format " << format << " not supported \n";
}
} catch (std::exception& error) {
cerr << "an error occurred:\n" << error.what() << endl;
}
};
private:
string file;
string format;
votca::Index level;
};
int main(int argc, char** argv) {
VotcaProperty vp;
return vp.Exec(argc, argv);
}
<commit_msg>Format code using clang-format version 12.0.0 (Fedora 12.0.0-2.fc34)<commit_after>/*
* Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)
*
* 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.
*
*/
// Standard includes
#include <iostream>
// Third party includes
#include <boost/algorithm/string/replace.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
// Local VOTCA includes
#include "votca/tools/application.h"
#include "votca/tools/globals.h"
#include "votca/tools/property.h"
#include "votca/tools/propertyiomanipulator.h"
#include "votca/tools/version.h"
using namespace std;
using namespace votca::tools;
namespace po = boost::program_options;
class VotcaProperty final : public Application {
public:
VotcaProperty() = default;
~VotcaProperty() = default;
string ProgramName() { return "votca_property"; }
void HelpText(ostream& out) { out << "Helper for parsing XML files"; }
void Initialize() {
format = "XML";
level = 1;
AddProgramOptions()("file", po::value<string>(), "xml file to parse")(
"format", po::value<string>(),
"output format [XML TXT]")("level", po::value<votca::Index>(),
"output from this level ");
};
bool EvaluateOptions() {
CheckRequired("file", "Missing XML file");
return true;
};
void Run() {
file = OptionsMap()["file"].as<string>();
if (OptionsMap().count("format")) {
format = OptionsMap()["format"].as<string>();
}
if (OptionsMap().count("level")) {
level = OptionsMap()["level"].as<votca::Index>();
}
try {
Property p;
map<string, PropertyIOManipulator*> mformat_;
mformat_["XML"] = &XML;
mformat_["TXT"] = &TXT;
mformat_["HLP"] = &HLP;
p.LoadFromXML(file);
if (mformat_.find(format) != mformat_.end()) {
PropertyIOManipulator* piom = mformat_.find(format)->second;
piom->setLevel(level);
piom->setIndentation("");
piom->setColorScheme<csRGB>();
cout << *piom << p;
} else {
cout << "format " << format << " not supported \n";
}
} catch (std::exception& error) {
cerr << "an error occurred:\n" << error.what() << endl;
}
};
private:
string file;
string format;
votca::Index level;
};
int main(int argc, char** argv) {
VotcaProperty vp;
return vp.Exec(argc, argv);
}
<|endoftext|> |
<commit_before>//
// $Id: fcgio.cpp,v 1.13 2002/02/24 20:12:22 robs Exp $
//
// Allows you communicate with FastCGI streams using C++ iostreams
//
// ORIGINAL AUTHOR: George Feinberg
// REWRITTEN BY: Michael Richards 06/20/1999
// REWRITTEN AGAIN BY: Michael Shell 02/23/2000
// REWRITTEN AGAIN BY: Rob Saccoccio 11 Nov 2001
//
// Copyright (c) 2000 Tux the Linux Penguin
//
// You are free to use this software without charge or royalty
// as long as this notice is not removed or altered, and recognition
// is given to the author(s)
//
// This code is offered as-is without any warranty either expressed or
// implied; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
#ifdef _WIN32
#define DLLAPI __declspec(dllexport)
#endif
#include <limits.h>
#include "fcgio.h"
using std::streambuf;
using std::istream;
using std::ostream;
using std::streamsize;
fcgi_streambuf::fcgi_streambuf(FCGX_Stream * fs, char * b, int bs)
{
init(fs, b, bs);
}
fcgi_streambuf::fcgi_streambuf(char_type * b, streamsize bs)
{
init(0, b, bs);
}
fcgi_streambuf::fcgi_streambuf(FCGX_Stream * fs)
{
init(fs, 0, 0);
}
fcgi_streambuf::~fcgi_streambuf(void)
{
overflow(EOF);
// FCGX_Finish()/FCGX_Accept() will flush and close
}
void fcgi_streambuf::init(FCGX_Stream * fs, char_type * b, streamsize bs)
{
this->fcgx = fs;
this->buf = 0;
this->bufsize = 0;
setbuf(b, bs);
}
int fcgi_streambuf::overflow(int c)
{
if (this->bufsize)
{
int plen = pptr() - pbase();
if (plen)
{
if (FCGX_PutStr(pbase(), plen, this->fcgx) != plen) return EOF;
pbump(-plen);
}
}
if (c != EOF)
{
if (FCGX_PutChar(c, this->fcgx) != c) return EOF;
}
return 0;
}
// default base class behaviour seems to be inconsistent
int fcgi_streambuf::sync()
{
if (overflow(EOF)) return EOF;
if (FCGX_FFlush(this->fcgx)) return EOF;
return 0;
}
// uflow() removes the char, underflow() doesn't
int fcgi_streambuf::uflow()
{
int rv = underflow();
if (this->bufsize) gbump(1);
return rv;
}
// Note that the expected behaviour when there is no buffer varies
int fcgi_streambuf::underflow()
{
if (this->bufsize)
{
if (in_avail() == 0)
{
int glen = FCGX_GetStr(eback(), this->bufsize, this->fcgx);
if (glen <= 0) return EOF;
setg(eback(), eback(), eback() + glen);
}
return (unsigned char) *gptr();
}
else
{
return FCGX_GetChar(this->fcgx);
}
}
void fcgi_streambuf::reset(void)
{
// it should be ok to set up both the get and put areas
setg(this->buf, this->buf, this->buf);
setp(this->buf, this->buf + this->bufsize);
}
std::streambuf * fcgi_streambuf::setbuf(char_type * b, streamsize bs)
{
// XXX support moving data from an old buffer
if (this->bufsize) return 0;
this->buf = b;
this->bufsize = bs;
// the base setbuf() *has* to be called
streambuf::setbuf(b, bs);
reset();
return this;
}
int fcgi_streambuf::attach(FCGX_Stream * fs)
{
this->fcgx = fs;
if (this->bufsize)
{
reset();
}
return 0;
}
streamsize fcgi_streambuf::xsgetn(char_type * s, streamsize n)
{
if (n > INT_MAX) return 0;
return (this->bufsize)
? streambuf::xsgetn(s, n)
: (streamsize) FCGX_GetStr((char *) s, (int) n, this->fcgx);
}
streamsize fcgi_streambuf::xsputn(const char_type * s, streamsize n)
{
if (n > INT_MAX) return 0;
return (this->bufsize)
? streambuf::xsputn(s, n)
: (streamsize) FCGX_PutStr((char *) s, (int) n, this->fcgx);
}
// deprecated
fcgi_istream::fcgi_istream(FCGX_Stream * fs) :
istream(&fcgi_strmbuf)
{
fcgi_strmbuf.attach(fs);
}
// deprecated
void fcgi_istream::attach(FCGX_Stream * fs)
{
fcgi_strmbuf.attach(fs);
}
// deprecated
fcgi_ostream::fcgi_ostream(FCGX_Stream * fs) :
ostream(&fcgi_strmbuf)
{
fcgi_strmbuf.attach(fs);
}
// deprecated
void fcgi_ostream::attach(FCGX_Stream * fs)
{
fcgi_strmbuf.attach(fs);
}
<commit_msg>patch code<commit_after>//
// $Id: fcgio.cpp,v 1.13 2002/02/24 20:12:22 robs Exp $
//
// Allows you communicate with FastCGI streams using C++ iostreams
//
// ORIGINAL AUTHOR: George Feinberg
// REWRITTEN BY: Michael Richards 06/20/1999
// REWRITTEN AGAIN BY: Michael Shell 02/23/2000
// REWRITTEN AGAIN BY: Rob Saccoccio 11 Nov 2001
//
// Copyright (c) 2000 Tux the Linux Penguin
//
// You are free to use this software without charge or royalty
// as long as this notice is not removed or altered, and recognition
// is given to the author(s)
//
// This code is offered as-is without any warranty either expressed or
// implied; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
#ifdef _WIN32
#define DLLAPI __declspec(dllexport)
#endif
//include stido
#ifndef _STDIO_H_
#include <stdio.h>
#endif
#include <limits.h>
#include "fcgio.h"
using std::streambuf;
using std::istream;
using std::ostream;
using std::streamsize;
fcgi_streambuf::fcgi_streambuf(FCGX_Stream * fs, char * b, int bs)
{
init(fs, b, bs);
}
fcgi_streambuf::fcgi_streambuf(char_type * b, streamsize bs)
{
init(0, b, bs);
}
fcgi_streambuf::fcgi_streambuf(FCGX_Stream * fs)
{
init(fs, 0, 0);
}
fcgi_streambuf::~fcgi_streambuf(void)
{
overflow(EOF);
// FCGX_Finish()/FCGX_Accept() will flush and close
}
void fcgi_streambuf::init(FCGX_Stream * fs, char_type * b, streamsize bs)
{
this->fcgx = fs;
this->buf = 0;
this->bufsize = 0;
setbuf(b, bs);
}
int fcgi_streambuf::overflow(int c)
{
if (this->bufsize)
{
int plen = pptr() - pbase();
if (plen)
{
if (FCGX_PutStr(pbase(), plen, this->fcgx) != plen) return EOF;
pbump(-plen);
}
}
if (c != EOF)
{
if (FCGX_PutChar(c, this->fcgx) != c) return EOF;
}
return 0;
}
// default base class behaviour seems to be inconsistent
int fcgi_streambuf::sync()
{
if (overflow(EOF)) return EOF;
if (FCGX_FFlush(this->fcgx)) return EOF;
return 0;
}
// uflow() removes the char, underflow() doesn't
int fcgi_streambuf::uflow()
{
int rv = underflow();
if (this->bufsize) gbump(1);
return rv;
}
// Note that the expected behaviour when there is no buffer varies
int fcgi_streambuf::underflow()
{
if (this->bufsize)
{
if (in_avail() == 0)
{
int glen = FCGX_GetStr(eback(), this->bufsize, this->fcgx);
if (glen <= 0) return EOF;
setg(eback(), eback(), eback() + glen);
}
return (unsigned char) *gptr();
}
else
{
return FCGX_GetChar(this->fcgx);
}
}
void fcgi_streambuf::reset(void)
{
// it should be ok to set up both the get and put areas
setg(this->buf, this->buf, this->buf);
setp(this->buf, this->buf + this->bufsize);
}
std::streambuf * fcgi_streambuf::setbuf(char_type * b, streamsize bs)
{
// XXX support moving data from an old buffer
if (this->bufsize) return 0;
this->buf = b;
this->bufsize = bs;
// the base setbuf() *has* to be called
streambuf::setbuf(b, bs);
reset();
return this;
}
int fcgi_streambuf::attach(FCGX_Stream * fs)
{
this->fcgx = fs;
if (this->bufsize)
{
reset();
}
return 0;
}
streamsize fcgi_streambuf::xsgetn(char_type * s, streamsize n)
{
if (n > INT_MAX) return 0;
return (this->bufsize)
? streambuf::xsgetn(s, n)
: (streamsize) FCGX_GetStr((char *) s, (int) n, this->fcgx);
}
streamsize fcgi_streambuf::xsputn(const char_type * s, streamsize n)
{
if (n > INT_MAX) return 0;
return (this->bufsize)
? streambuf::xsputn(s, n)
: (streamsize) FCGX_PutStr((char *) s, (int) n, this->fcgx);
}
// deprecated
fcgi_istream::fcgi_istream(FCGX_Stream * fs) :
istream(&fcgi_strmbuf)
{
fcgi_strmbuf.attach(fs);
}
// deprecated
void fcgi_istream::attach(FCGX_Stream * fs)
{
fcgi_strmbuf.attach(fs);
}
// deprecated
fcgi_ostream::fcgi_ostream(FCGX_Stream * fs) :
ostream(&fcgi_strmbuf)
{
fcgi_strmbuf.attach(fs);
}
// deprecated
void fcgi_ostream::attach(FCGX_Stream * fs)
{
fcgi_strmbuf.attach(fs);
}
<|endoftext|> |
<commit_before>#include "catch.hpp"
#include <iostream>
#include <exception> // std::bad_function_call, std::runtime_error
#include <thread> // std::thread, std::this_thread::yield
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
#include <functional> // std::function
class EventThreader {
public:
std::condition_variable event_waiter;
std::condition_variable calling_waiter;
std::unique_lock<std::mutex>* event_lock = nullptr;
std::unique_lock<std::mutex>* calling_lock = nullptr;
std::mutex mtx;
std::mutex allocation_mtx;
std::thread event_thread;
void switchToCallingThread();
bool require_switch_from_event = false;
std::function<void(void)> event_cleanup;
std::runtime_error* exception_from_the_event_thread;
void deallocate();
public:
EventThreader(std::function<void (std::function<void (void)>)> func);
~EventThreader();
void switchToEventThread();
void join();
void setEventCleanup(std::function<void(void)>);
};
EventThreader::EventThreader(std::function<void (std::function<void (void)>)> func) {
allocation_mtx.lock();
exception_from_the_event_thread = nullptr;
event_lock = nullptr;
calling_lock = nullptr;
calling_lock = new std::unique_lock<std::mutex>(et.mtx);
allocation_mtx.unlock();
exception_from_the_event_thread = nullptr;
event_cleanup = [](){}; // empty function
auto event = [&](){
/* mtx force switch to calling - blocked by the mutex */
allocation_mtx.lock();
event_lock = new std::unique_lock<std::mutex>(mtx);
allocation_mtx.unlock();
calling_waiter.notify_one();
event_waiter.wait(*event_lock);
std::this_thread::yield();
try {
func([&](){switchToCallingThread();});
if (require_switch_from_event) { // the event has ended, but not ready to join
// rejoin the calling thread after dealing with this exception
throw std::runtime_error("switch to event not matched with a switch to calling");
}
} catch (const std::runtime_error &e) {
/* report the exception to the calling thread */
allocation_mtx.lock();
exception_from_the_event_thread = new std::runtime_error(e);
allocation_mtx.unlock();
calling_waiter.notify_one();
std::this_thread::yield();
}
allocation_mtx.lock();
delete event_lock;
event_lock = nullptr;
allocation_mtx.unlock();
event_cleanup();
};
event_thread = std::thread(event);
std::this_thread::yield();
calling_waiter.wait(*calling_lock);
std::this_thread::yield();
}
EventThreader::~EventThreader() {
}
void EventThreader::deallocate() {
allocation_mtx.lock();
if (exception_from_the_event_thread != nullptr) {
delete exception_from_the_event_thread;
exception_from_the_event_thread = nullptr;
}
if (calling_lock != nullptr) {
delete calling_lock;
calling_lock = nullptr;
}
if (event_lock != nullptr) {
delete event_lock;
event_lock = nullptr;
}
allocation_mtx.unlock();
}
void EventThreader::switchToCallingThread() {
if (!require_switch_from_event) {
throw std::runtime_error("switch to calling not matched with a switch to event");
}
require_switch_from_event = false;
/* switch to calling */
calling_waiter.notify_one();
std::this_thread::yield();
event_waiter.wait(*(event_lock));
std::this_thread::yield();
/* back from calling */
}
void EventThreader::switchToEventThread() {
}
void EventThreader::join() {
allocation_mtx.lock();
delete calling_lock; // remove lock on this thread, allow event to run
calling_lock = nullptr;
allocation_mtx.unlock();
if (event_lock != nullptr) {
event_waiter.notify_one();
std::this_thread::yield();
}
event_thread.join();
if (exception_from_the_event_thread != nullptr) {
/* an exception occured */
std::runtime_error e_copy(exception_from_the_event_thread->what());
allocation_mtx.lock();
delete exception_from_the_event_thread;
exception_from_the_event_thread = nullptr;
allocation_mtx.unlock();
throw e_copy;
}
deallocate();
}
void EventThreader::setEventCleanup(std::function<void(void)> cleanup) {
event_cleanup = cleanup;
}
TEST_CASE( "EventThreader", "[EventThreader]" ) {
std::stringstream ss;
SECTION("Finding the error") {
/* Example of most basic use */
auto f = [&ss](std::function<void(void)> switchToMainThread){
for(int i = 0; i < 100; i++) { ss << "*"; }
switchToMainThread();
for(int i = 0; i < 50; i++) { ss << "*"; }
switchToMainThread();
};
EventThreader et(f);
// class variables
// class functions
auto deallocate = [&]() {
et.deallocate();
};
auto join = [&]() {
et.join();
};
auto switchToCallingThread = [&]() {
et.switchToCallingThread();
};
auto switchToEventThread= [&]() {
if (et.require_switch_from_event) {
throw std::runtime_error("switch to event not matched with a switch to calling");
}
et.require_switch_from_event = true;
/* switch to event */
et.event_waiter.notify_one();
std::this_thread::yield();
et.calling_waiter.wait(*et.calling_lock);
std::this_thread::yield();
/* back from event */
if (et.require_switch_from_event) {
/* this exception is thrown if switchToCallingThread() was not used, which means the thread ended */
join();
}
};
// Start construction
// End constuction
//EventThreader et(f);
switchToEventThread();
for(int i = 0; i < 75; i++) { ss << "$"; }
switchToEventThread();
for(int i = 0; i < 25; i++) { ss << "$"; }
join();
/* Generate what the result should look like */
std::string requirement;
for(int i = 0; i < 100; i++) { requirement += "*"; }
for(int i = 0; i < 75; i++) { requirement += "$"; }
for(int i = 0; i < 50; i++) { requirement += "*"; }
for(int i = 0; i < 25; i++) { requirement += "$"; }
REQUIRE( requirement == ss.str());
deallocate();
}
/* SECTION("Abitrary use") {
// Example of most basic use
auto f = [&ss](std::function<void(void)> switchToMainThread){
for(int i = 0; i < 100; i++) { ss << "*"; }
switchToMainThread();
for(int i = 0; i < 50; i++) { ss << "*"; }
switchToMainThread();
};
EventThreader et(f);
switchToEventThread();
for(int i = 0; i < 75; i++) { ss << "$"; }
switchToEventThread();
for(int i = 0; i < 25; i++) { ss << "$"; }
join();
// Generate what the result should look like
std::string requirement;
for(int i = 0; i < 100; i++) { requirement += "*"; }
for(int i = 0; i < 75; i++) { requirement += "$"; }
for(int i = 0; i < 50; i++) { requirement += "*"; }
for(int i = 0; i < 25; i++) { requirement += "$"; }
REQUIRE( requirement == ss.str());
} */
}
<commit_msg>constructor func<commit_after>#include "catch.hpp"
#include <iostream>
#include <exception> // std::bad_function_call, std::runtime_error
#include <thread> // std::thread, std::this_thread::yield
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
#include <functional> // std::function
class EventThreader {
public:
std::condition_variable event_waiter;
std::condition_variable calling_waiter;
std::unique_lock<std::mutex>* event_lock = nullptr;
std::unique_lock<std::mutex>* calling_lock = nullptr;
std::mutex mtx;
std::mutex allocation_mtx;
std::thread event_thread;
void switchToCallingThread();
bool require_switch_from_event = false;
std::function<void(void)> event_cleanup;
std::runtime_error* exception_from_the_event_thread;
void deallocate();
public:
EventThreader(std::function<void (std::function<void (void)>)> func);
~EventThreader();
void switchToEventThread();
void join();
void setEventCleanup(std::function<void(void)>);
};
EventThreader::EventThreader(std::function<void (std::function<void (void)>)> func) {
allocation_mtx.lock();
exception_from_the_event_thread = nullptr;
event_lock = nullptr;
calling_lock = nullptr;
calling_lock = new std::unique_lock<std::mutex>(mtx);
allocation_mtx.unlock();
exception_from_the_event_thread = nullptr;
event_cleanup = [](){}; // empty function
auto event = [&](){
/* mtx force switch to calling - blocked by the mutex */
allocation_mtx.lock();
event_lock = new std::unique_lock<std::mutex>(mtx);
allocation_mtx.unlock();
calling_waiter.notify_one();
event_waiter.wait(*event_lock);
std::this_thread::yield();
try {
func([&](){switchToCallingThread();});
if (require_switch_from_event) { // the event has ended, but not ready to join
// rejoin the calling thread after dealing with this exception
throw std::runtime_error("switch to event not matched with a switch to calling");
}
} catch (const std::runtime_error &e) {
/* report the exception to the calling thread */
allocation_mtx.lock();
exception_from_the_event_thread = new std::runtime_error(e);
allocation_mtx.unlock();
calling_waiter.notify_one();
std::this_thread::yield();
}
allocation_mtx.lock();
delete event_lock;
event_lock = nullptr;
allocation_mtx.unlock();
event_cleanup();
};
event_thread = std::thread(event);
std::this_thread::yield();
calling_waiter.wait(*calling_lock);
std::this_thread::yield();
}
EventThreader::~EventThreader() {
}
void EventThreader::deallocate() {
allocation_mtx.lock();
if (exception_from_the_event_thread != nullptr) {
delete exception_from_the_event_thread;
exception_from_the_event_thread = nullptr;
}
if (calling_lock != nullptr) {
delete calling_lock;
calling_lock = nullptr;
}
if (event_lock != nullptr) {
delete event_lock;
event_lock = nullptr;
}
allocation_mtx.unlock();
}
void EventThreader::switchToCallingThread() {
if (!require_switch_from_event) {
throw std::runtime_error("switch to calling not matched with a switch to event");
}
require_switch_from_event = false;
/* switch to calling */
calling_waiter.notify_one();
std::this_thread::yield();
event_waiter.wait(*(event_lock));
std::this_thread::yield();
/* back from calling */
}
void EventThreader::switchToEventThread() {
}
void EventThreader::join() {
allocation_mtx.lock();
delete calling_lock; // remove lock on this thread, allow event to run
calling_lock = nullptr;
allocation_mtx.unlock();
if (event_lock != nullptr) {
event_waiter.notify_one();
std::this_thread::yield();
}
event_thread.join();
if (exception_from_the_event_thread != nullptr) {
/* an exception occured */
std::runtime_error e_copy(exception_from_the_event_thread->what());
allocation_mtx.lock();
delete exception_from_the_event_thread;
exception_from_the_event_thread = nullptr;
allocation_mtx.unlock();
throw e_copy;
}
deallocate();
}
void EventThreader::setEventCleanup(std::function<void(void)> cleanup) {
event_cleanup = cleanup;
}
TEST_CASE( "EventThreader", "[EventThreader]" ) {
std::stringstream ss;
SECTION("Finding the error") {
/* Example of most basic use */
auto f = [&ss](std::function<void(void)> switchToMainThread){
for(int i = 0; i < 100; i++) { ss << "*"; }
switchToMainThread();
for(int i = 0; i < 50; i++) { ss << "*"; }
switchToMainThread();
};
EventThreader et(f);
// class variables
// class functions
auto deallocate = [&]() {
et.deallocate();
};
auto join = [&]() {
et.join();
};
auto switchToCallingThread = [&]() {
et.switchToCallingThread();
};
auto switchToEventThread= [&]() {
if (et.require_switch_from_event) {
throw std::runtime_error("switch to event not matched with a switch to calling");
}
et.require_switch_from_event = true;
/* switch to event */
et.event_waiter.notify_one();
std::this_thread::yield();
et.calling_waiter.wait(*et.calling_lock);
std::this_thread::yield();
/* back from event */
if (et.require_switch_from_event) {
/* this exception is thrown if switchToCallingThread() was not used, which means the thread ended */
join();
}
};
// Start construction
// End constuction
//EventThreader et(f);
switchToEventThread();
for(int i = 0; i < 75; i++) { ss << "$"; }
switchToEventThread();
for(int i = 0; i < 25; i++) { ss << "$"; }
join();
/* Generate what the result should look like */
std::string requirement;
for(int i = 0; i < 100; i++) { requirement += "*"; }
for(int i = 0; i < 75; i++) { requirement += "$"; }
for(int i = 0; i < 50; i++) { requirement += "*"; }
for(int i = 0; i < 25; i++) { requirement += "$"; }
REQUIRE( requirement == ss.str());
deallocate();
}
/* SECTION("Abitrary use") {
// Example of most basic use
auto f = [&ss](std::function<void(void)> switchToMainThread){
for(int i = 0; i < 100; i++) { ss << "*"; }
switchToMainThread();
for(int i = 0; i < 50; i++) { ss << "*"; }
switchToMainThread();
};
EventThreader et(f);
switchToEventThread();
for(int i = 0; i < 75; i++) { ss << "$"; }
switchToEventThread();
for(int i = 0; i < 25; i++) { ss << "$"; }
join();
// Generate what the result should look like
std::string requirement;
for(int i = 0; i < 100; i++) { requirement += "*"; }
for(int i = 0; i < 75; i++) { requirement += "$"; }
for(int i = 0; i < 50; i++) { requirement += "*"; }
for(int i = 0; i < 25; i++) { requirement += "$"; }
REQUIRE( requirement == ss.str());
} */
}
<|endoftext|> |
<commit_before>// @(#)root/proof:$Id$
// Author: G. Ganis, Oct 2011
/*************************************************************************
* Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/** \class TLockPath
\ingroup proofkernel
Path locking class allowing shared and exclusive locks
*/
#include "TLockPath.h"
#include "TSystem.h"
#include <sys/file.h>
////////////////////////////////////////////////////////////////////////////////
/// Locks the directory. Waits if lock is hold by an other process.
/// Returns 0 on success, -1 in case of error.
TLockPath::TLockPath(const char *path) : fName(path), fLockId(-1)
{
// Work with full names
if (gSystem->ExpandPathName(fName))
Warning("TLockPath", "problems expanding path '%s'", fName.Data());
}
Int_t TLockPath::Lock(Bool_t shared)
{
const char *pname = GetName();
if (gSystem->AccessPathName(pname))
fLockId = open(pname, O_CREAT|O_RDWR, 0644);
else
fLockId = open(pname, O_RDWR);
if (fLockId == -1) {
SysError("Lock", "cannot open lock file %s", pname);
return -1;
}
if (gDebug > 1)
Info("Lock", "%d: locking file %s ...", gSystem->GetPid(), pname);
// lock the file
#if !defined(R__WIN32) && !defined(R__WINGCC)
int op = (shared) ? LOCK_SH : LOCK_EX ;
if (flock(fLockId, op) == -1) {
SysError("Lock", "error locking %s", pname);
close(fLockId);
fLockId = -1;
return -1;
}
#endif
if (gDebug > 1)
Info("Lock", "%d: file %s locked", gSystem->GetPid(), pname);
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Unlock the directory. Returns 0 in case of success,
/// -1 in case of error.
Int_t TLockPath::Unlock()
{
if (!IsLocked())
return 0;
if (gDebug > 1)
Info("Unlock", "%d: unlocking file %s ...", gSystem->GetPid(), GetName());
// unlock the file
lseek(fLockId, 0, SEEK_SET);
#if !defined(R__WIN32) && !defined(R__WINGCC)
if (flock(fLockId, LOCK_UN) == -1) {
SysError("Unlock", "error unlocking %s", GetName());
close(fLockId);
fLockId = -1;
return -1;
}
#endif
if (gDebug > 1)
Info("Unlock", "%d: file %s unlocked", gSystem->GetPid(), GetName());
close(fLockId);
fLockId = -1;
return 0;
}
<commit_msg>Fix Proof compilation on Windows<commit_after>// @(#)root/proof:$Id$
// Author: G. Ganis, Oct 2011
/*************************************************************************
* Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/** \class TLockPath
\ingroup proofkernel
Path locking class allowing shared and exclusive locks
*/
#include "TLockPath.h"
#include "TSystem.h"
#ifndef R__WIN32
#include <sys/file.h>
#else
#include <io.h>
#define lseek(fd, offset, origin) _lseek(fd, offset, origin)
#define close(fd) _close(fd)
#endif
////////////////////////////////////////////////////////////////////////////////
/// Locks the directory. Waits if lock is hold by an other process.
/// Returns 0 on success, -1 in case of error.
TLockPath::TLockPath(const char *path) : fName(path), fLockId(-1)
{
// Work with full names
if (gSystem->ExpandPathName(fName))
Warning("TLockPath", "problems expanding path '%s'", fName.Data());
}
Int_t TLockPath::Lock(Bool_t shared)
{
const char *pname = GetName();
#if defined(R__WIN32) && !defined(R__WINGCC)
if (gSystem->AccessPathName(pname))
fLockId = _open(pname, _O_CREAT|_O_RDWR, 0644);
else
fLockId = _open(pname, _O_RDWR);
#else
if (gSystem->AccessPathName(pname))
fLockId = open(pname, O_CREAT|O_RDWR, 0644);
else
fLockId = open(pname, O_RDWR);
#endif
if (fLockId == -1) {
SysError("Lock", "cannot open lock file %s", pname);
return -1;
}
if (gDebug > 1)
Info("Lock", "%d: locking file %s ...", gSystem->GetPid(), pname);
// lock the file
#if !defined(R__WIN32) && !defined(R__WINGCC)
int op = (shared) ? LOCK_SH : LOCK_EX ;
if (flock(fLockId, op) == -1) {
SysError("Lock", "error locking %s", pname);
close(fLockId);
fLockId = -1;
return -1;
}
#endif
if (gDebug > 1)
Info("Lock", "%d: file %s locked", gSystem->GetPid(), pname);
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Unlock the directory. Returns 0 in case of success,
/// -1 in case of error.
Int_t TLockPath::Unlock()
{
if (!IsLocked())
return 0;
if (gDebug > 1)
Info("Unlock", "%d: unlocking file %s ...", gSystem->GetPid(), GetName());
// unlock the file
lseek(fLockId, 0, SEEK_SET);
#if !defined(R__WIN32) && !defined(R__WINGCC)
if (flock(fLockId, LOCK_UN) == -1) {
SysError("Unlock", "error unlocking %s", GetName());
close(fLockId);
fLockId = -1;
return -1;
}
#endif
if (gDebug > 1)
Info("Unlock", "%d: file %s unlocked", gSystem->GetPid(), GetName());
close(fLockId);
fLockId = -1;
return 0;
}
<|endoftext|> |
<commit_before>//===-- StackProtector.cpp - Stack Protector Insertion --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass inserts stack protectors into functions which need them. A variable
// with a random value in it is stored onto the stack before the local variables
// are allocated. Upon exiting the block, the stored value is checked. If it's
// changed, then there was some sort of violation and the program aborts.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "stack-protector"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Attributes.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetLowering.h"
using namespace llvm;
// SSPBufferSize - The lower bound for a buffer to be considered for stack
// smashing protection.
static cl::opt<unsigned>
SSPBufferSize("stack-protector-buffer-size", cl::init(8),
cl::desc("Lower bound for a buffer to be considered for "
"stack protection"));
namespace {
class StackProtector : public FunctionPass {
/// TLI - Keep a pointer of a TargetLowering to consult for determining
/// target type sizes.
const TargetLowering *TLI;
Function *F;
Module *M;
DominatorTree* DT;
/// InsertStackProtectors - Insert code into the prologue and epilogue of
/// the function.
///
/// - The prologue code loads and stores the stack guard onto the stack.
/// - The epilogue checks the value stored in the prologue against the
/// original value. It calls __stack_chk_fail if they differ.
bool InsertStackProtectors();
/// CreateFailBB - Create a basic block to jump to when the stack protector
/// check fails.
BasicBlock *CreateFailBB();
/// RequiresStackProtector - Check whether or not this function needs a
/// stack protector based upon the stack protector level.
bool RequiresStackProtector() const;
public:
static char ID; // Pass identification, replacement for typeid.
StackProtector() : FunctionPass(ID), TLI(0) {
initializeStackProtectorPass(*PassRegistry::getPassRegistry());
}
StackProtector(const TargetLowering *tli)
: FunctionPass(ID), TLI(tli) {
initializeStackProtectorPass(*PassRegistry::getPassRegistry());
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addPreserved<DominatorTree>();
}
virtual bool runOnFunction(Function &Fn);
};
} // end anonymous namespace
char StackProtector::ID = 0;
INITIALIZE_PASS(StackProtector, "stack-protector",
"Insert stack protectors", false, false)
FunctionPass *llvm::createStackProtectorPass(const TargetLowering *tli) {
return new StackProtector(tli);
}
bool StackProtector::runOnFunction(Function &Fn) {
F = &Fn;
M = F->getParent();
DT = getAnalysisIfAvailable<DominatorTree>();
if (!RequiresStackProtector()) return false;
return InsertStackProtectors();
}
/// RequiresStackProtector - Check whether or not this function needs a stack
/// protector based upon the stack protector level. The heuristic we use is to
/// add a guard variable to functions that call alloca, and functions with
/// buffers larger than SSPBufferSize bytes.
bool StackProtector::RequiresStackProtector() const {
if (F->hasFnAttr(Attribute::StackProtectReq))
return true;
if (!F->hasFnAttr(Attribute::StackProtect))
return false;
const TargetData *TD = TLI->getTargetData();
for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
BasicBlock *BB = I;
for (BasicBlock::iterator
II = BB->begin(), IE = BB->end(); II != IE; ++II)
if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
if (AI->isArrayAllocation())
// This is a call to alloca with a variable size. Emit stack
// protectors.
return true;
if (const ArrayType *AT = dyn_cast<ArrayType>(AI->getAllocatedType())) {
// We apparently only care about character arrays.
if (!AT->getElementType()->isIntegerTy(8))
continue;
// If an array has more than SSPBufferSize bytes of allocated space,
// then we emit stack protectors.
if (SSPBufferSize <= TD->getTypeAllocSize(AT))
return true;
}
}
}
return false;
}
/// InsertStackProtectors - Insert code into the prologue and epilogue of the
/// function.
///
/// - The prologue code loads and stores the stack guard onto the stack.
/// - The epilogue checks the value stored in the prologue against the original
/// value. It calls __stack_chk_fail if they differ.
bool StackProtector::InsertStackProtectors() {
BasicBlock *FailBB = 0; // The basic block to jump to if check fails.
BasicBlock *FailBBDom = 0; // FailBB's dominator.
AllocaInst *AI = 0; // Place on stack that stores the stack guard.
Value *StackGuardVar = 0; // The stack guard variable.
BasicBlock &Entry = F->getEntryBlock();
for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
BasicBlock *BB = I++;
if (BB->getNumUses() == 0 && BB != &Entry) continue;
ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
if (!RI) continue;
if (!FailBB) {
// Insert code into the entry block that stores the __stack_chk_guard
// variable onto the stack:
//
// entry:
// StackGuardSlot = alloca i8*
// StackGuard = load __stack_chk_guard
// call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
//
const PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
unsigned AddressSpace, Offset;
if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
Constant *OffsetVal =
ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,
PointerType::get(PtrTy, AddressSpace));
} else {
StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
}
Instruction *InsPt = &Entry.front();
AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
Value *Args[] = { LI, AI };
CallInst::
Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
&Args[0], array_endof(Args), "", InsPt);
// Create the basic block to jump to when the guard check fails.
FailBB = CreateFailBB();
if (DT)
FailBBDom = DT->isReachableFromEntry(BB) ? BB : 0;
}
// For each block with a return instruction, convert this:
//
// return:
// ...
// ret ...
//
// into this:
//
// return:
// ...
// %1 = load __stack_chk_guard
// %2 = load StackGuardSlot
// %3 = cmp i1 %1, %2
// br i1 %3, label %SP_return, label %CallStackCheckFailBlk
//
// SP_return:
// ret ...
//
// CallStackCheckFailBlk:
// call void @__stack_chk_fail()
// unreachable
// Split the basic block before the return instruction.
BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
if (DT && DT->isReachableFromEntry(BB)) {
DT->addNewBlock(NewBB, BB);
if (FailBBDom)
FailBBDom = DT->findNearestCommonDominator(FailBBDom, BB);
}
// Remove default branch instruction to the new BB.
BB->getTerminator()->eraseFromParent();
// Move the newly created basic block to the point right after the old basic
// block so that it's in the "fall through" position.
NewBB->moveAfter(BB);
// Generate the stack protector instructions in the old basic block.
LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
LoadInst *LI2 = new LoadInst(AI, "", true, BB);
ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, "");
BranchInst::Create(NewBB, FailBB, Cmp, BB);
}
// Return if we didn't modify any basic blocks. I.e., there are no return
// statements in the function.
if (!FailBB) return false;
if (DT && FailBBDom)
DT->addNewBlock(FailBB, FailBBDom);
return true;
}
/// CreateFailBB - Create a basic block to jump to when the stack protector
/// check fails.
BasicBlock *StackProtector::CreateFailBB() {
BasicBlock *FailBB = BasicBlock::Create(F->getContext(),
"CallStackCheckFailBlk", F);
Constant *StackChkFail =
M->getOrInsertFunction("__stack_chk_fail",
Type::getVoidTy(F->getContext()), NULL);
CallInst::Create(StackChkFail, "", FailBB);
new UnreachableInst(F->getContext(), FailBB);
return FailBB;
}
<commit_msg>Rework the logic (and removing the bad check for an unreachable block) so that the FailBB dominator is correctly calculated. Believe it or not, there isn't a functionality change here.<commit_after>//===-- StackProtector.cpp - Stack Protector Insertion --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass inserts stack protectors into functions which need them. A variable
// with a random value in it is stored onto the stack before the local variables
// are allocated. Upon exiting the block, the stored value is checked. If it's
// changed, then there was some sort of violation and the program aborts.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "stack-protector"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Attributes.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetLowering.h"
using namespace llvm;
// SSPBufferSize - The lower bound for a buffer to be considered for stack
// smashing protection.
static cl::opt<unsigned>
SSPBufferSize("stack-protector-buffer-size", cl::init(8),
cl::desc("Lower bound for a buffer to be considered for "
"stack protection"));
namespace {
class StackProtector : public FunctionPass {
/// TLI - Keep a pointer of a TargetLowering to consult for determining
/// target type sizes.
const TargetLowering *TLI;
Function *F;
Module *M;
DominatorTree* DT;
/// InsertStackProtectors - Insert code into the prologue and epilogue of
/// the function.
///
/// - The prologue code loads and stores the stack guard onto the stack.
/// - The epilogue checks the value stored in the prologue against the
/// original value. It calls __stack_chk_fail if they differ.
bool InsertStackProtectors();
/// CreateFailBB - Create a basic block to jump to when the stack protector
/// check fails.
BasicBlock *CreateFailBB();
/// RequiresStackProtector - Check whether or not this function needs a
/// stack protector based upon the stack protector level.
bool RequiresStackProtector() const;
public:
static char ID; // Pass identification, replacement for typeid.
StackProtector() : FunctionPass(ID), TLI(0) {
initializeStackProtectorPass(*PassRegistry::getPassRegistry());
}
StackProtector(const TargetLowering *tli)
: FunctionPass(ID), TLI(tli) {
initializeStackProtectorPass(*PassRegistry::getPassRegistry());
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addPreserved<DominatorTree>();
}
virtual bool runOnFunction(Function &Fn);
};
} // end anonymous namespace
char StackProtector::ID = 0;
INITIALIZE_PASS(StackProtector, "stack-protector",
"Insert stack protectors", false, false)
FunctionPass *llvm::createStackProtectorPass(const TargetLowering *tli) {
return new StackProtector(tli);
}
bool StackProtector::runOnFunction(Function &Fn) {
F = &Fn;
M = F->getParent();
DT = getAnalysisIfAvailable<DominatorTree>();
if (!RequiresStackProtector()) return false;
return InsertStackProtectors();
}
/// RequiresStackProtector - Check whether or not this function needs a stack
/// protector based upon the stack protector level. The heuristic we use is to
/// add a guard variable to functions that call alloca, and functions with
/// buffers larger than SSPBufferSize bytes.
bool StackProtector::RequiresStackProtector() const {
if (F->hasFnAttr(Attribute::StackProtectReq))
return true;
if (!F->hasFnAttr(Attribute::StackProtect))
return false;
const TargetData *TD = TLI->getTargetData();
for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
BasicBlock *BB = I;
for (BasicBlock::iterator
II = BB->begin(), IE = BB->end(); II != IE; ++II)
if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
if (AI->isArrayAllocation())
// This is a call to alloca with a variable size. Emit stack
// protectors.
return true;
if (const ArrayType *AT = dyn_cast<ArrayType>(AI->getAllocatedType())) {
// We apparently only care about character arrays.
if (!AT->getElementType()->isIntegerTy(8))
continue;
// If an array has more than SSPBufferSize bytes of allocated space,
// then we emit stack protectors.
if (SSPBufferSize <= TD->getTypeAllocSize(AT))
return true;
}
}
}
return false;
}
/// InsertStackProtectors - Insert code into the prologue and epilogue of the
/// function.
///
/// - The prologue code loads and stores the stack guard onto the stack.
/// - The epilogue checks the value stored in the prologue against the original
/// value. It calls __stack_chk_fail if they differ.
bool StackProtector::InsertStackProtectors() {
BasicBlock *FailBB = 0; // The basic block to jump to if check fails.
BasicBlock *FailBBDom = 0; // FailBB's dominator.
AllocaInst *AI = 0; // Place on stack that stores the stack guard.
Value *StackGuardVar = 0; // The stack guard variable.
for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
BasicBlock *BB = I++;
ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
if (!RI) continue;
if (!FailBB) {
// Insert code into the entry block that stores the __stack_chk_guard
// variable onto the stack:
//
// entry:
// StackGuardSlot = alloca i8*
// StackGuard = load __stack_chk_guard
// call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
//
const PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
unsigned AddressSpace, Offset;
if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
Constant *OffsetVal =
ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,
PointerType::get(PtrTy, AddressSpace));
} else {
StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
}
BasicBlock &Entry = F->getEntryBlock();
Instruction *InsPt = &Entry.front();
AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
Value *Args[] = { LI, AI };
CallInst::
Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
&Args[0], array_endof(Args), "", InsPt);
// Create the basic block to jump to when the guard check fails.
FailBB = CreateFailBB();
}
// For each block with a return instruction, convert this:
//
// return:
// ...
// ret ...
//
// into this:
//
// return:
// ...
// %1 = load __stack_chk_guard
// %2 = load StackGuardSlot
// %3 = cmp i1 %1, %2
// br i1 %3, label %SP_return, label %CallStackCheckFailBlk
//
// SP_return:
// ret ...
//
// CallStackCheckFailBlk:
// call void @__stack_chk_fail()
// unreachable
// Split the basic block before the return instruction.
bool BBIsReachable = (DT && DT->isReachableFromEntry(BB));
BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
if (BBIsReachable) {
DT->addNewBlock(NewBB, BB);
FailBBDom = FailBBDom ? DT->findNearestCommonDominator(FailBBDom, BB) :BB;
}
// Remove default branch instruction to the new BB.
BB->getTerminator()->eraseFromParent();
// Move the newly created basic block to the point right after the old basic
// block so that it's in the "fall through" position.
NewBB->moveAfter(BB);
// Generate the stack protector instructions in the old basic block.
LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
LoadInst *LI2 = new LoadInst(AI, "", true, BB);
ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, "");
BranchInst::Create(NewBB, FailBB, Cmp, BB);
}
// Return if we didn't modify any basic blocks. I.e., there are no return
// statements in the function.
if (!FailBB) return false;
if (DT && FailBBDom)
DT->addNewBlock(FailBB, FailBBDom);
return true;
}
/// CreateFailBB - Create a basic block to jump to when the stack protector
/// check fails.
BasicBlock *StackProtector::CreateFailBB() {
BasicBlock *FailBB = BasicBlock::Create(F->getContext(),
"CallStackCheckFailBlk", F);
Constant *StackChkFail =
M->getOrInsertFunction("__stack_chk_fail",
Type::getVoidTy(F->getContext()), NULL);
CallInst::Create(StackChkFail, "", FailBB);
new UnreachableInst(F->getContext(), FailBB);
return FailBB;
}
<|endoftext|> |
<commit_before>#include "threadpool.h"
ThreadPool::ThreadPool(size_t size)
{
for (auto i=0; i<size; ++i) {
workers.emplace_back([this] {
for (;;) {
std::unique_lock<std::mutex> lock(this->queue_mutex);
while (!this->m_stop && this->tasks.empty())
this->condition.wait(lock);
if (this->m_stop && this->tasks.empty())
return;
std::function<void()> task(this->tasks.front());
this->tasks.pop();
lock.unlock();
task();
}
});
}
}
ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
m_stop = true;
}
condition.notify_all();
for (auto i=0; i<workers.size(); ++i)
workers[i].join();
}
<commit_msg>Fix compilation warning caused by use of "auto"<commit_after>#include "threadpool.h"
ThreadPool::ThreadPool(size_t size)
{
for (size_t i=0; i<size; ++i) {
workers.emplace_back([this] {
for (;;) {
std::unique_lock<std::mutex> lock(this->queue_mutex);
while (!this->m_stop && this->tasks.empty())
this->condition.wait(lock);
if (this->m_stop && this->tasks.empty())
return;
std::function<void()> task(this->tasks.front());
this->tasks.pop();
lock.unlock();
task();
}
});
}
}
ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
m_stop = true;
}
condition.notify_all();
for (auto i=0; i<workers.size(); ++i)
workers[i].join();
}
<|endoftext|> |
<commit_before>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#include <fstream>
#include <float.h>
#ifdef _WIN32
#include <winsock2.h>
#else
#include <netdb.h>
#endif
#include <string.h>
#include <stdio.h>
#include <map>
#include "parse_example.h"
#include "constant.h"
#include "sparse_dense.h"
#include "gd.h"
#include "cache.h"
#include "simple_label.h"
#include "rand48.h"
#include "vw.h"
#include <algorithm>
#include "hash.h"
#include <sstream>
#include "parse_primitives.h"
using namespace std;
namespace MF {
struct mf {
learner base;
vector<string> pairs;
uint32_t rank;
uint32_t increment;
// array to cache w*x, (l^k * x_l) and (r^k * x_r)
// [ w*(1,x_l,x_r) , l^1*x_l, r^1*x_r, l^2*x_l, r^2*x_2, ... ]
v_array<float> sub_predictions;
// array for temp storage of indices
v_array<unsigned char> indices;
// array for temp storage of features
v_array<feature> temp_features;
vw* all;
};
void inline_predict(mf* data, vw* all, example* &ec) {
float prediction = 0;
data->sub_predictions.erase();
// set weight to 0 to indicate test example (predict only)
float weight = ((label_data*) ec->ld)->weight;
((label_data*) ec->ld)->weight = 0;
// predict from linear terms
data->base.learn(ec);
// store linear prediction
data->sub_predictions.push_back(ec->partial_prediction);
prediction += ec->partial_prediction;
// store namespace indices
copy_array(data->indices, ec->indices);
// store namespace indices
//copy_array(data->indices, ec->indices);
// add interaction terms to prediction
for (vector<string>::iterator i = data->pairs.begin(); i != data->pairs.end(); i++) {
if (ec->atomics[(int) (*i)[0]].size() > 0 && ec->atomics[(int) (*i)[1]].size() > 0) {
for (size_t k = 1; k <= all->rank; k++) {
// set example to left namespace only
ec->indices.erase();
ec->indices.push_back((int) (*i)[0]);
// compute l^k * x_l using base learner
update_example_indicies(all->audit, ec, data->increment*k);
data->base.learn(ec);
float x_dot_l = ec->partial_prediction;
data->sub_predictions.push_back(ec->partial_prediction);
update_example_indicies(all->audit, ec, -data->increment*k);
// set example to right namespace only
ec->indices.erase();
ec->indices.push_back((int) (*i)[1]);
// compute r^k * x_r using base learner
update_example_indicies(all->audit, ec, data->increment*(k + data->rank));
data->base.learn(ec);
float x_dot_r = ec->partial_prediction;
data->sub_predictions.push_back(ec->partial_prediction);
update_example_indicies(all->audit, ec, -data->increment*(k + data->rank));
// accumulate prediction
prediction += (x_dot_l * x_dot_r);
}
}
}
// restore namespace indices and label
copy_array(ec->indices, data->indices);
((label_data*) ec->ld)->weight = weight;
// finalize prediction
ec->partial_prediction = prediction;
ec->final_prediction = GD::finalize_prediction(*(data->all), ec->partial_prediction);
}
void learn(void* d, example* ec) {
mf* data = (mf*) d;
vw* all = data->all;
if (command_example(all, ec)) {
data->base.learn(ec);
return;
}
// predict with current weights
inline_predict(data, all, ec);
float err = fabs(((label_data*) ec->ld)->label - ec->final_prediction);
// force base learner to use precomputed prediction
ec->precomputed_prediction = true;
// update linear weights
data->base.learn(ec);
// store namespace indices
copy_array(data->indices, ec->indices);
// update interaction terms
// looping over all pairs of non-empty namespaces
for (vector<string>::iterator i = data->pairs.begin(); i != data->pairs.end(); i++) {
if (ec->atomics[(int) (*i)[0]].size() > 0 && ec->atomics[(int) (*i)[1]].size() > 0) {
for (size_t k = 1; k <= all->rank; k++) {
// set example to left namespace only
ec->indices.erase();
ec->indices.push_back((int) (*i)[0]);
// store feature values for left namespace
copy_array(data->temp_features, ec->atomics[(int) (*i)[0]]);
// multiply features in left namespace by r^k * x_r
for (feature* f = ec->atomics[(int) (*i)[0]].begin; f != ec->atomics[(int) (*i)[0]].end; f++)
f->x *= data->sub_predictions[2*k];
// update l^k using base learner
update_example_indicies(all->audit, ec, data->increment*k);
data->base.learn(ec);
update_example_indicies(all->audit, ec, -data->increment*k);
// restore left namespace features
copy_array(ec->atomics[(int) (*i)[0]], data->temp_features);
// set example to right namespace only
ec->indices.erase();
ec->indices.push_back((int) (*i)[1]);
// store feature values for right namespace
copy_array(data->temp_features, ec->atomics[(int) (*i)[1]]);
// multiply features in right namespace by l^k * x_l
for (feature* f = ec->atomics[(int) (*i)[1]].begin; f != ec->atomics[(int) (*i)[1]].end; f++)
f->x *= data->sub_predictions[2*k-1];
// update r^k using base learner
update_example_indicies(all->audit, ec, data->increment*(k + data->rank));
data->base.learn(ec);
update_example_indicies(all->audit, ec, -data->increment*(k + data->rank));
// restore right namespace features
copy_array(ec->atomics[(int) (*i)[1]], data->temp_features);
}
}
}
// restore namespace indices and unset precomputed prediction
copy_array(ec->indices, data->indices);
ec->precomputed_prediction = false;
// predict with current weights
//inline_predict(data, all, ec);
float new_err = fabs(((label_data*) ec->ld)->label - ec->final_prediction);
//if (new_err > err)
// cout << "error increased after training from " << err << " to " << new_err << endl;
}
void finish(void* data) {
mf* o = (mf*) data;
// restore global pairs
o->all->pairs = o->pairs;
o->base.finish();
// clean up local v_arrays
o->indices.delete_v();
o->sub_predictions.delete_v();
delete o;
}
void drive(vw* all, void* d) {
example* ec = NULL;
while (true) {
if ((ec = VW::get_example(all->p)) != NULL) //blocking operation.
{
learn(d, ec);
return_simple_example(*all, ec);
} else if (parser_done(all->p))
return;
else
; //busywait when we have predicted on all examples but not yet trained on all.
}
}
learner setup(vw& all, po::variables_map& vm) {
mf* data = new mf;
// copy global data locally
data->base = all.l;
data->all = &all;
data->rank = all.rank;
// store global pairs in local data structure and clear global pairs
// for eventual calls to base learner
data->pairs = all.pairs;
all.pairs.clear();
// set index increment between weights
data->increment = all.reg.stride * all.weights_per_problem;
all.weights_per_problem *= data->rank;
// initialize weights randomly
if(!vm.count("initial_regressor"))
{
for (size_t j = 0; j < (all.reg.weight_mask + 1) / all.reg.stride; j++)
all.reg.weight_vector[j*all.reg.stride] = (float) (0.1 * frand48());
}
learner ret(data, drive,learn, finish, all.l.sl);
return ret;
}
}
<commit_msg>switching branches<commit_after>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#include <fstream>
#include <float.h>
#ifdef _WIN32
#include <winsock2.h>
#else
#include <netdb.h>
#endif
#include <string.h>
#include <stdio.h>
#include <map>
#include "parse_example.h"
#include "constant.h"
#include "sparse_dense.h"
#include "gd.h"
#include "cache.h"
#include "simple_label.h"
#include "rand48.h"
#include "vw.h"
#include <algorithm>
#include "hash.h"
#include <sstream>
#include "parse_primitives.h"
using namespace std;
namespace MF {
struct mf {
learner base;
vector<string> pairs;
uint32_t rank;
uint32_t increment;
// array to cache w*x, (l^k * x_l) and (r^k * x_r)
// [ w*(1,x_l,x_r) , l^1*x_l, r^1*x_r, l^2*x_l, r^2*x_2, ... ]
v_array<float> sub_predictions;
// array for temp storage of indices
v_array<unsigned char> indices;
// array for temp storage of features
v_array<feature> temp_features;
vw* all;
};
void inline_predict(mf* data, vw* all, example* &ec) {
float prediction = 0;
data->sub_predictions.erase();
// set weight to 0 to indicate test example (predict only)
float weight = ((label_data*) ec->ld)->weight;
((label_data*) ec->ld)->weight = 0;
// predict from linear terms
data->base.learn(ec);
// store linear prediction
data->sub_predictions.push_back(ec->partial_prediction);
prediction += ec->partial_prediction;
// store namespace indices
copy_array(data->indices, ec->indices);
// add interaction terms to prediction
for (vector<string>::iterator i = data->pairs.begin(); i != data->pairs.end(); i++) {
if (ec->atomics[(int) (*i)[0]].size() > 0 && ec->atomics[(int) (*i)[1]].size() > 0) {
for (size_t k = 1; k <= all->rank; k++) {
// set example to left namespace only
ec->indices.erase();
ec->indices.push_back((int) (*i)[0]);
// compute l^k * x_l using base learner
update_example_indicies(all->audit, ec, data->increment*k);
data->base.learn(ec);
float x_dot_l = ec->partial_prediction;
data->sub_predictions.push_back(ec->partial_prediction);
update_example_indicies(all->audit, ec, -data->increment*k);
// set example to right namespace only
ec->indices.erase();
ec->indices.push_back((int) (*i)[1]);
// compute r^k * x_r using base learner
update_example_indicies(all->audit, ec, data->increment*(k + data->rank));
data->base.learn(ec);
float x_dot_r = ec->partial_prediction;
data->sub_predictions.push_back(ec->partial_prediction);
update_example_indicies(all->audit, ec, -data->increment*(k + data->rank));
// accumulate prediction
prediction += (x_dot_l * x_dot_r);
}
}
}
// restore namespace indices and label
copy_array(ec->indices, data->indices);
((label_data*) ec->ld)->weight = weight;
// finalize prediction
ec->partial_prediction = prediction;
ec->final_prediction = GD::finalize_prediction(*(data->all), ec->partial_prediction);
}
void learn(void* d, example* ec) {
mf* data = (mf*) d;
vw* all = data->all;
if (command_example(all, ec)) {
data->base.learn(ec);
return;
}
// predict with current weights
inline_predict(data, all, ec);
// force base learner to use precomputed prediction
ec->precomputed_prediction = true;
// update linear weights
data->base.learn(ec);
// store namespace indices
copy_array(data->indices, ec->indices);
// update interaction terms
// looping over all pairs of non-empty namespaces
for (vector<string>::iterator i = data->pairs.begin(); i != data->pairs.end(); i++) {
if (ec->atomics[(int) (*i)[0]].size() > 0 && ec->atomics[(int) (*i)[1]].size() > 0) {
for (size_t k = 1; k <= all->rank; k++) {
// set example to left namespace only
ec->indices.erase();
ec->indices.push_back((int) (*i)[0]);
// store feature values for left namespace
copy_array(data->temp_features, ec->atomics[(int) (*i)[0]]);
// multiply features in left namespace by r^k * x_r
for (feature* f = ec->atomics[(int) (*i)[0]].begin; f != ec->atomics[(int) (*i)[0]].end; f++)
f->x *= data->sub_predictions[2*k];
// update l^k using base learner
update_example_indicies(all->audit, ec, data->increment*k);
data->base.learn(ec);
update_example_indicies(all->audit, ec, -data->increment*k);
// restore left namespace features
copy_array(ec->atomics[(int) (*i)[0]], data->temp_features);
// set example to right namespace only
ec->indices.erase();
ec->indices.push_back((int) (*i)[1]);
// store feature values for right namespace
copy_array(data->temp_features, ec->atomics[(int) (*i)[1]]);
// multiply features in right namespace by l^k * x_l
for (feature* f = ec->atomics[(int) (*i)[1]].begin; f != ec->atomics[(int) (*i)[1]].end; f++)
f->x *= data->sub_predictions[2*k-1];
// update r^k using base learner
update_example_indicies(all->audit, ec, data->increment*(k + data->rank));
data->base.learn(ec);
update_example_indicies(all->audit, ec, -data->increment*(k + data->rank));
// restore right namespace features
copy_array(ec->atomics[(int) (*i)[1]], data->temp_features);
}
}
}
// restore namespace indices and unset precomputed prediction
copy_array(ec->indices, data->indices);
ec->precomputed_prediction = false;
}
void finish(void* data) {
mf* o = (mf*) data;
// restore global pairs
o->all->pairs = o->pairs;
o->base.finish();
// clean up local v_arrays
o->indices.delete_v();
o->sub_predictions.delete_v();
delete o;
}
void drive(vw* all, void* d) {
example* ec = NULL;
while (true) {
if ((ec = VW::get_example(all->p)) != NULL) //blocking operation.
{
learn(d, ec);
return_simple_example(*all, ec);
} else if (parser_done(all->p))
return;
else
; //busywait when we have predicted on all examples but not yet trained on all.
}
}
learner setup(vw& all, po::variables_map& vm) {
mf* data = new mf;
// copy global data locally
data->base = all.l;
data->all = &all;
data->rank = all.rank;
// store global pairs in local data structure and clear global pairs
// for eventual calls to base learner
data->pairs = all.pairs;
all.pairs.clear();
// set index increment between weights
data->increment = all.reg.stride * all.weights_per_problem;
all.weights_per_problem *= data->rank;
// initialize weights randomly
if(!vm.count("initial_regressor"))
{
for (size_t j = 0; j < (all.reg.weight_mask + 1) / all.reg.stride; j++)
all.reg.weight_vector[j*all.reg.stride] = (float) (0.1 * frand48());
}
learner ret(data, drive,learn, finish, all.l.sl);
return ret;
}
}
<|endoftext|> |
<commit_before>#pragma once
#ifndef BinaryTree_disabled
#ifndef BinaryTree_defined
// ReSharper disable CppUnusedIncludeDirective
#include <memory>
#include <functional>
#include <stack>
namespace lib {
template <typename T> using unidef_ptr = std::unique_ptr<T, std::default_delete<T>>;
}
/**
* \brief 遍历方式
*/
enum class Order{
PreOrder,
InOrder,
PostOrder,
};
/**
* \brief 二叉树的节点类型
* \tparam T 数据类型
*/
template<typename T, template<class> class P>
struct BinaryTree{
BinaryTree(P<BinaryTree<T, P>>&& l, P<BinaryTree<T, P>>&& r, T&& d)
:data(std::forward<T>(d)), left(std::forward<P<BinaryTree<T, P>>>(l)), right(std::forward<P<BinaryTree<T, P>>>(r)) {}
explicit BinaryTree(T&& d)
:data(std::forward<T>(d)){}
T data;
P<BinaryTree<T, P>> left;
P<BinaryTree<T, P>> right;
/**
* \brief 二叉树递归遍历
* \tparam O 遍历方式
* \tparam F 操作函数类型
* \param f 操作函数
*/
template<Order O,typename F>
void TreeTraversalRecursive(F&& f);
/**
* \brief 二叉树先序遍历
* \tparam O == Order::PreOrder
* \tparam F 操作函数类型
* \param f 操作函数
* \return void
*/
template<Order O, typename F>
typename std::enable_if<O == Order::PreOrder, void>::type
TreeTraversalIterative(F&& f){
std::stack<BinaryTree<T, P>*> s;
s.push(this);
while (!s.empty()) {
auto cur = s.top();
std::invoke(std::forward<F&&>(f), cur->data);
s.pop();
if (cur->right)s.emplace(cur->right.get());
if (cur->left)s.emplace(cur->left.get());
}
}
/**
* \brief 二叉树中序遍历
* \tparam O == Order::InOrder
* \tparam F 操作函数类型
* \param f 操作函数
* \return void
*/
template<Order O, typename F>
typename std::enable_if<O == Order::InOrder, void>::type
TreeTraversalIterative(F&& f){
std::stack<BinaryTree<T, P>*> s;
auto cur = this;
while (!s.empty() || cur) {
if (cur) {
s.push(cur);
cur = cur->left.get();
}
else {
cur = s.top();
s.pop();
std::invoke(std::forward<F&&>(f), cur->data);
cur = cur->right.get();
}
}
}
/**
* \brief 二叉树后序遍历
* \tparam O == Order::PostOrder
* \tparam F 操作函数类型
* \param f 操作函数
* \return void
*/
template<Order O, typename F>
typename std::enable_if<O == Order::PostOrder, void>::type
TreeTraversalIterative(F&& f){
std::stack<BinaryTree<T, P>*> trv;
std::stack<BinaryTree<T, P>*> out;
trv.push(this);
while (!trv.empty()) {
auto cur = trv.top();
trv.pop();
if (cur->left)trv.push(cur->left.get());
if (cur->right)trv.push(cur->right.get());
out.push(cur);
}
while (!out.empty()) {
std::invoke(std::forward<F&&>(f), out.top()->data);
out.pop();
}
}
template<Order O, int I, typename F>
typename std::enable_if <(I == 0 && O == Order::PreOrder)
|| (I == 1 && O == Order::InOrder)
|| (I == 2 && O == Order::PostOrder), void>::type
TreeTraversalRecursiveImpl(F&& f){
std::invoke(std::forward<F&&>(f), data);
}
template<Order O, int I, typename F>
typename std::enable_if <(I == 1 && O == Order::PreOrder)
|| (I == 0 && O == Order::InOrder)
|| (I == 0 && O == Order::PostOrder), void>::type
TreeTraversalRecursiveImpl(F&& f){
if(left)left->template TreeTraversalRecursive<O>(std::forward<F&&>(f));
}
template<Order O, int I, typename F>
typename std::enable_if <(I == 2 && O == Order::PreOrder)
|| (I == 2 && O == Order::InOrder)
|| (I == 1 && O == Order::PostOrder), void>::type
TreeTraversalRecursiveImpl(F&& f){
if(right)right->template TreeTraversalRecursive<O>(std::forward<F&&>(f));
}
};
template<typename T, template<class> class P>
template<Order O, typename F>
void BinaryTree<T, P>::TreeTraversalRecursive(F&& f){
TreeTraversalRecursiveImpl<O, 0>(std::forward<F&&>(f));
TreeTraversalRecursiveImpl<O, 1>(std::forward<F&&>(f));
TreeTraversalRecursiveImpl<O, 2>(std::forward<F&&>(f));
}
/**
* \brief 构造二叉树内节点
* \tparam T 数据类型
* \param left 左子树
* \param right 右子树
* \param t 数据
* \return 构造完成的树
*/
template<typename T>
lib::unidef_ptr<BinaryTree<T, lib::unidef_ptr>> MakeUniTree(lib::unidef_ptr<BinaryTree<T, lib::unidef_ptr>>&& left, lib::unidef_ptr<BinaryTree<T, lib::unidef_ptr>>&& right, T&& t) {
return std::make_unique<BinaryTree<T, lib::unidef_ptr>>(std::forward<lib::unidef_ptr<BinaryTree<T, lib::unidef_ptr>>>(left), std::forward<lib::unidef_ptr<BinaryTree<T, lib::unidef_ptr>>>(right), std::forward<T>(t));
}
/**
* \brief 构造二叉树叶子节点
* \tparam T 数据类型
* \param t 数据
* \return 构造完成的树
*/
template<typename T>
lib::unidef_ptr<BinaryTree<T, lib::unidef_ptr>> MakeUniTree(T&& t) {
return std::make_unique<BinaryTree<T, lib::unidef_ptr>>(std::forward<T>(t));
}
/**
* \brief 构造二叉树内节点
* \tparam T 数据类型
* \param left 左子树
* \param right 右子树
* \param t 数据
* \return 构造完成的树
*/
template<typename T>
std::shared_ptr<BinaryTree<T, std::shared_ptr>> MakeSrdTree(std::shared_ptr<BinaryTree<T, std::shared_ptr>>&& left, std::shared_ptr<BinaryTree<T, std::shared_ptr>>&& right, T&& t) {
return std::make_shared<BinaryTree<T, std::shared_ptr>>(std::forward<std::shared_ptr<BinaryTree<T, std::shared_ptr>>>(left), std::forward<std::shared_ptr<BinaryTree<T, std::shared_ptr>>>(right), std::forward<T>(t));
}
/**
* \brief 构造二叉树叶子节点
* \tparam T 数据类型
* \param t 数据
* \return 构造完成的树
*/
template<typename T>
std::shared_ptr<BinaryTree<T, std::shared_ptr>> MakeSrdTree(T&& t) {
return std::make_shared<BinaryTree<T, std::shared_ptr>>(std::forward<T>(t));
}
#define BinaryTree_defined
#endif
#endif<commit_msg>UPDATE templatize pointer type<commit_after>#pragma once
#ifndef BinaryTree_disabled
#ifndef BinaryTree_defined
// ReSharper disable CppUnusedIncludeDirective
#include <memory>
#include <functional>
#include <stack>
/**
* \brief 遍历方式
*/
enum class Order{
PreOrder,
InOrder,
PostOrder,
};
/**
* \brief 二叉树的节点类型
* \tparam T 数据类型
*/
template<typename T, template<class...> class P>
struct BinaryTree{
BinaryTree(P<BinaryTree<T, P>>&& l, P<BinaryTree<T, P>>&& r, T&& d)
:data(std::forward<T>(d)), left(std::forward<P<BinaryTree<T, P>>>(l)), right(std::forward<P<BinaryTree<T, P>>>(r)) {}
explicit BinaryTree(T&& d)
:data(std::forward<T>(d)){}
T data;
P<BinaryTree<T, P>> left;
P<BinaryTree<T, P>> right;
/**
* \brief 二叉树递归遍历
* \tparam O 遍历方式
* \tparam F 操作函数类型
* \param f 操作函数
*/
template<Order O,typename F>
void TreeTraversalRecursive(F&& f);
/**
* \brief 二叉树先序遍历
* \tparam O == Order::PreOrder
* \tparam F 操作函数类型
* \param f 操作函数
* \return void
*/
template<Order O, typename F>
typename std::enable_if<O == Order::PreOrder, void>::type
TreeTraversalIterative(F&& f){
std::stack<BinaryTree<T, P>*> s;
s.push(this);
while (!s.empty()) {
auto cur = s.top();
std::invoke(std::forward<F&&>(f), cur->data);
s.pop();
if (cur->right)s.emplace(cur->right.get());
if (cur->left)s.emplace(cur->left.get());
}
}
/**
* \brief 二叉树中序遍历
* \tparam O == Order::InOrder
* \tparam F 操作函数类型
* \param f 操作函数
* \return void
*/
template<Order O, typename F>
typename std::enable_if<O == Order::InOrder, void>::type
TreeTraversalIterative(F&& f){
std::stack<BinaryTree<T, P>*> s;
auto cur = this;
while (!s.empty() || cur) {
if (cur) {
s.push(cur);
cur = cur->left.get();
}
else {
cur = s.top();
s.pop();
std::invoke(std::forward<F&&>(f), cur->data);
cur = cur->right.get();
}
}
}
/**
* \brief 二叉树后序遍历
* \tparam O == Order::PostOrder
* \tparam F 操作函数类型
* \param f 操作函数
* \return void
*/
template<Order O, typename F>
typename std::enable_if<O == Order::PostOrder, void>::type
TreeTraversalIterative(F&& f){
std::stack<BinaryTree<T, P>*> trv;
std::stack<BinaryTree<T, P>*> out;
trv.push(this);
while (!trv.empty()) {
auto cur = trv.top();
trv.pop();
if (cur->left)trv.push(cur->left.get());
if (cur->right)trv.push(cur->right.get());
out.push(cur);
}
while (!out.empty()) {
std::invoke(std::forward<F&&>(f), out.top()->data);
out.pop();
}
}
template<Order O, int I, typename F>
typename std::enable_if <(I == 0 && O == Order::PreOrder)
|| (I == 1 && O == Order::InOrder)
|| (I == 2 && O == Order::PostOrder), void>::type
TreeTraversalRecursiveImpl(F&& f){
std::invoke(std::forward<F&&>(f), data);
}
template<Order O, int I, typename F>
typename std::enable_if <(I == 1 && O == Order::PreOrder)
|| (I == 0 && O == Order::InOrder)
|| (I == 0 && O == Order::PostOrder), void>::type
TreeTraversalRecursiveImpl(F&& f){
if(left)left->template TreeTraversalRecursive<O>(std::forward<F&&>(f));
}
template<Order O, int I, typename F>
typename std::enable_if <(I == 2 && O == Order::PreOrder)
|| (I == 2 && O == Order::InOrder)
|| (I == 1 && O == Order::PostOrder), void>::type
TreeTraversalRecursiveImpl(F&& f){
if(right)right->template TreeTraversalRecursive<O>(std::forward<F&&>(f));
}
};
template<typename T, template<class...> class P>
template<Order O, typename F>
void BinaryTree<T, P>::TreeTraversalRecursive(F&& f){
TreeTraversalRecursiveImpl<O, 0>(std::forward<F&&>(f));
TreeTraversalRecursiveImpl<O, 1>(std::forward<F&&>(f));
TreeTraversalRecursiveImpl<O, 2>(std::forward<F&&>(f));
}
/**
* \brief 构造二叉树内节点
* \tparam T 数据类型
* \param left 左子树
* \param right 右子树
* \param t 数据
* \return 构造完成的树
*/
template<typename T>
std::unique_ptr<BinaryTree<T, std::unique_ptr>> MakeUniTree(std::unique_ptr<BinaryTree<T, std::unique_ptr>>&& left, std::unique_ptr<BinaryTree<T, std::unique_ptr>>&& right, T&& t) {
return std::make_unique<BinaryTree<T, std::unique_ptr>>(std::forward<std::unique_ptr<BinaryTree<T, std::unique_ptr>>>(left), std::forward<std::unique_ptr<BinaryTree<T, std::unique_ptr>>>(right), std::forward<T>(t));
}
/**
* \brief 构造二叉树叶子节点
* \tparam T 数据类型
* \param t 数据
* \return 构造完成的树
*/
template<typename T>
std::unique_ptr<BinaryTree<T, std::unique_ptr>> MakeUniTree(T&& t) {
return std::make_unique<BinaryTree<T, std::unique_ptr>>(std::forward<T>(t));
}
/**
* \brief 构造二叉树内节点
* \tparam T 数据类型
* \param left 左子树
* \param right 右子树
* \param t 数据
* \return 构造完成的树
*/
template<typename T>
std::shared_ptr<BinaryTree<T, std::shared_ptr>> MakeSrdTree(std::shared_ptr<BinaryTree<T, std::shared_ptr>>&& left, std::shared_ptr<BinaryTree<T, std::shared_ptr>>&& right, T&& t) {
return std::make_shared<BinaryTree<T, std::shared_ptr>>(std::forward<std::shared_ptr<BinaryTree<T, std::shared_ptr>>>(left), std::forward<std::shared_ptr<BinaryTree<T, std::shared_ptr>>>(right), std::forward<T>(t));
}
/**
* \brief 构造二叉树叶子节点
* \tparam T 数据类型
* \param t 数据
* \return 构造完成的树
*/
template<typename T>
std::shared_ptr<BinaryTree<T, std::shared_ptr>> MakeSrdTree(T&& t) {
return std::make_shared<BinaryTree<T, std::shared_ptr>>(std::forward<T>(t));
}
#define BinaryTree_defined
#endif
#endif<|endoftext|> |
<commit_before>/*
* Copyright (c) 2001-2003 Stephen Williams (steve@icarus.com)
*
* This source code is free software; you can redistribute it
* and/or modify it in source code form 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#ifdef HAVE_CVS_IDENT
#ident "$Id: vpi_modules.cc,v 1.18 2004/10/04 01:10:59 steve Exp $"
#endif
# include "config.h"
# include "vpi_priv.h"
# include "ivl_dlfcn.h"
# include <stdio.h>
# include <string.h>
# include <sys/types.h>
# include <sys/stat.h>
typedef void (*vlog_startup_routines_t)(void);
const char* vpip_module_path[64] = {
#ifdef MODULE_DIR1
MODULE_DIR1,
#endif
#ifdef MODULE_DIR2
MODULE_DIR2,
#endif
0
};
unsigned vpip_module_path_cnt = 0
#ifdef MODULE_DIR1
+ 1
#endif
#ifdef MODULE_DIR2
+ 1
#endif
;
void vpip_load_module(const char*name)
{
struct stat sb;
int rc;
bool export_flag = false;
char buf[4096];
#ifdef __MINGW32__
const char sep = '\\';
#else
const char sep = '/';
#endif
ivl_dll_t dll = 0;
buf[0] = 0; /* terminate the string */
if (strchr(name, sep)) {
/* If the name has at least one directory character in
it, then assume it is a complete name, maybe including any
possible .vpi suffix. */
export_flag = false;
rc = stat(name, &sb);
if (rc != 0) { /* did we find a file? */
/* no, try with a .vpi suffix too */
export_flag = false;
sprintf(buf, "%s.vpi", name);
rc = stat(buf, &sb);
/* Try also with the .vpl suffix. */
if (rc != 0) {
export_flag = true;
sprintf(buf, "%s.vpl", name);
rc = stat(buf, &sb);
}
if (rc != 0) {
fprintf(stderr, "%s: Unable to find module file `%s' "
"or `%s.vpi'.\n", name,name,buf);
return;
}
} else {
strcpy(buf,name); /* yes copy the name into the buffer */
}
} else {
rc = -1;
for (unsigned idx = 0
; (rc != 0) && (idx < vpip_module_path_cnt)
; idx += 1) {
export_flag = false;
sprintf(buf, "%s%c%s.vpi", vpip_module_path[idx], sep, name);
rc = stat(buf,&sb);
if (rc != 0) {
export_flag = true;
sprintf(buf, "%s%c%s.vpl",
vpip_module_path[idx], sep, name);
rc = stat(buf,&sb);
}
}
if (rc != 0) {
fprintf(stderr, "%s: Unable to find a "
"`%s.vpi' module on the search path.\n",
name, name);
return;
}
}
/* must have found some file that could possibly be a vpi module
* try to open it as a shared object.
*/
dll = ivl_dlopen(buf, export_flag);
if(dll==0) {
/* hmm, this failed, let the user know what has really gone wrong */
fprintf(stderr,"%s:`%s' failed to open using dlopen() because:\n"
" %s.\n",name,buf,dlerror());
return;
}
void*table = ivl_dlsym(dll, LU "vlog_startup_routines" TU);
if (table == 0) {
fprintf(stderr, "%s: no vlog_startup_routines\n", name);
ivl_dlclose(dll);
return;
}
vpi_mode_flag = VPI_MODE_REGISTER;
vlog_startup_routines_t*routines = (vlog_startup_routines_t*)table;
for (unsigned tmp = 0 ; routines[tmp] ; tmp += 1)
(routines[tmp])();
vpi_mode_flag = VPI_MODE_NONE;
}
/*
* $Log: vpi_modules.cc,v $
* Revision 1.18 2004/10/04 01:10:59 steve
* Clean up spurious trailing white space.
*
* Revision 1.17 2003/10/08 23:09:09 steve
* Completely support vvp32 when enabled.
*
* Revision 1.16 2003/10/02 21:30:40 steve
* Configure control for the vpi subdirectory.
*
* Revision 1.15 2003/02/16 02:21:20 steve
* Support .vpl files as loadable LIBRARIES.
*
* Revision 1.14 2003/02/09 23:33:26 steve
* Spelling fixes.
*
* Revision 1.13 2003/01/10 03:06:32 steve
* Remove vpithunk, and move libvpi to vvp directory.
*
* Revision 1.12 2002/08/12 01:35:09 steve
* conditional ident string using autoconfig.
*
* Revision 1.11 2002/05/18 02:34:11 steve
* Add vpi support for named events.
*
* Add vpi_mode_flag to track the mode of the
* vpi engine. This is for error checking.
*
* Revision 1.10 2002/03/05 05:31:52 steve
* Better linker error messages.
*
* Revision 1.9 2001/10/14 18:42:46 steve
* Try appending .vpi to module names with directories.
*
* Revision 1.8 2001/07/30 02:44:05 steve
* Cleanup defines and types for mingw compile.
*
* Revision 1.7 2001/07/28 03:29:42 steve
* If module name has a /, skip the path search.
*
* Revision 1.6 2001/07/26 03:13:51 steve
* Make the -M flag add module search paths.
*/
<commit_msg>GetProcAddress expects no underscore (MinGW)<commit_after>/*
* Copyright (c) 2001-2008 Stephen Williams (steve@icarus.com)
*
* This source code is free software; you can redistribute it
* and/or modify it in source code form 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
# include "config.h"
# include "vpi_priv.h"
# include "ivl_dlfcn.h"
# include <stdio.h>
# include <string.h>
# include <sys/types.h>
# include <sys/stat.h>
typedef void (*vlog_startup_routines_t)(void);
const char* vpip_module_path[64] = {
#ifdef MODULE_DIR1
MODULE_DIR1,
#endif
#ifdef MODULE_DIR2
MODULE_DIR2,
#endif
0
};
unsigned vpip_module_path_cnt = 0
#ifdef MODULE_DIR1
+ 1
#endif
#ifdef MODULE_DIR2
+ 1
#endif
;
void vpip_load_module(const char*name)
{
struct stat sb;
int rc;
bool export_flag = false;
char buf[4096];
#ifdef __MINGW32__
const char sep = '\\';
#else
const char sep = '/';
#endif
ivl_dll_t dll = 0;
buf[0] = 0; /* terminate the string */
if (strchr(name, sep)) {
/* If the name has at least one directory character in
it, then assume it is a complete name, maybe including any
possible .vpi suffix. */
export_flag = false;
rc = stat(name, &sb);
if (rc != 0) { /* did we find a file? */
/* no, try with a .vpi suffix too */
export_flag = false;
sprintf(buf, "%s.vpi", name);
rc = stat(buf, &sb);
/* Try also with the .vpl suffix. */
if (rc != 0) {
export_flag = true;
sprintf(buf, "%s.vpl", name);
rc = stat(buf, &sb);
}
if (rc != 0) {
fprintf(stderr, "%s: Unable to find module file `%s' "
"or `%s.vpi'.\n", name,name,buf);
return;
}
} else {
strcpy(buf,name); /* yes copy the name into the buffer */
}
} else {
rc = -1;
for (unsigned idx = 0
; (rc != 0) && (idx < vpip_module_path_cnt)
; idx += 1) {
export_flag = false;
sprintf(buf, "%s%c%s.vpi", vpip_module_path[idx], sep, name);
rc = stat(buf,&sb);
if (rc != 0) {
export_flag = true;
sprintf(buf, "%s%c%s.vpl",
vpip_module_path[idx], sep, name);
rc = stat(buf,&sb);
}
}
if (rc != 0) {
fprintf(stderr, "%s: Unable to find a "
"`%s.vpi' module on the search path.\n",
name, name);
return;
}
}
/* must have found some file that could possibly be a vpi module
* try to open it as a shared object.
*/
dll = ivl_dlopen(buf, export_flag);
if(dll==0) {
/* hmm, this failed, let the user know what has really gone wrong */
fprintf(stderr,"%s:`%s' failed to open using dlopen() because:\n"
" %s.\n",name,buf,dlerror());
return;
}
#ifdef __MINGW32__
/* For this check MinGW does not want the leading underscore! */
void*table = ivl_dlsym(dll, "vlog_startup_routines");
#else
void*table = ivl_dlsym(dll, LU "vlog_startup_routines" TU);
#endif
if (table == 0) {
fprintf(stderr, "%s: no vlog_startup_routines\n", name);
ivl_dlclose(dll);
return;
}
vpi_mode_flag = VPI_MODE_REGISTER;
vlog_startup_routines_t*routines = (vlog_startup_routines_t*)table;
for (unsigned tmp = 0 ; routines[tmp] ; tmp += 1)
(routines[tmp])();
vpi_mode_flag = VPI_MODE_NONE;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2012, Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 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 <algorithm>
#include <cassert>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iterator>
#include <list>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include <unordered_map>
#ifdef _WIN32
#include <Windows.h>
#endif
#include <amx/amx.h>
#include <amx_profiler/call_graph_writer_gv.h>
#include <amx_profiler/debug_info.h>
#include <amx_profiler/profile_writer_html.h>
#include <amx_profiler/profile_writer_text.h>
#include <amx_profiler/profile_writer_xml.h>
#include <amx_profiler/profiler.h>
#include "amx_path.h"
#include "config_reader.h"
#include "hook.h"
#include "plugin.h"
#include "version.h"
using namespace amx_profiler;
typedef void (*logprintf_t)(const char *format, ...);
extern void *pAMXFunctions;
static logprintf_t logprintf;
// Profiler instances.
static std::unordered_map<AMX*, std::shared_ptr<Profiler>> profilers;
// List of loaded scripts, need this to fix AmxUnload bug on Windows.
static std::list<AMX*> loaded_scripts;
// Stores previously set debug hooks (if any).
static std::unordered_map<AMX*, AMX_DEBUG> old_debug_hooks;
// Plugin settings and their defauls.
namespace cfg {
bool profile_gamemode = false;
std::string profile_filterscripts = "";
std::string profile_format = "html";
bool call_graph = false;
std::string call_graph_format = "gv";
};
namespace hooks {
Hook amx_Exec_hook;
Hook amx_Callback_hook;
static int AMXAPI amx_Debug(AMX *amx) {
auto profiler = ::profilers[amx];
if (profiler) {
profiler->amx_Debug();
}
auto iterator = old_debug_hooks.find(amx);
if (iterator != old_debug_hooks.end()) {
if (iterator->second != 0) {
return (iterator->second)(amx);
}
}
return AMX_ERR_NONE;
}
static int AMXAPI amx_Callback(AMX *amx, cell index, cell *result, cell *params) {
Hook::ScopedRemove r(&amx_Callback_hook);
Hook::ScopedInstall i(&amx_Exec_hook);
auto profiler = ::profilers[amx];
if (profiler) {
return profiler->amx_Callback(index, result, params);
} else {
return ::amx_Callback(amx, index, result, params);
}
}
static int AMXAPI amx_Exec(AMX *amx, cell *retval, int index) {
Hook::ScopedRemove r(&amx_Exec_hook);
Hook::ScopedInstall i(&amx_Callback_hook);
auto profiler = ::profilers[amx];
if (profiler) {
return profiler->amx_Exec(retval, index);
} else {
return ::amx_Exec(amx, retval, index);
}
}
} // namespace hooks
static std::string ToUnixPath(const std::string &path) {
std::string fsPath = path;
std::replace(fsPath.begin(), fsPath.end(), '\\', '/');
return fsPath;
}
static bool IsGameMode(const std::string &amxName) {
return ToUnixPath(amxName).find("gamemodes/") != std::string::npos;
}
static bool IsFilterScript(const std::string &amxName) {
return ToUnixPath(amxName).find("filterscripts/") != std::string::npos;
}
static bool GetPublicVariable(AMX *amx, const char *name, cell &value) {
cell amx_addr;
if (amx_FindPubVar(amx, name, &amx_addr) == AMX_ERR_NONE) {
cell *phys_addr;
amx_GetAddr(amx, amx_addr, &phys_addr);
value = *phys_addr;
return true;
}
return false;
}
static bool WantsProfiler(const std::string &amxName) {
std::string goodAmxName = ToUnixPath(amxName);
if (IsGameMode(amxName)) {
if (cfg::profile_gamemode) {
return true;
}
} else if (IsFilterScript(amxName)) {
std::string fsList = cfg::profile_filterscripts;
std::stringstream fsStream(fsList);
do {
std::string fsName;
fsStream >> fsName;
if (goodAmxName == "filterscripts/" + fsName + ".amx"
|| goodAmxName == "filterscripts/" + fsName) {
return true;
}
} while (!fsStream.eof());
}
return false;
}
#ifdef _WIN32
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx);
static BOOL WINAPI ConsoleCtrlHandler(DWORD dwCtrlType) {
switch (dwCtrlType) {
case CTRL_CLOSE_EVENT:
case CTRL_BREAK_EVENT:
for (auto amx : loaded_scripts) {
AmxUnload(amx);
}
}
return FALSE;
}
#endif
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
static void *AMXAPI my_amx_Align(void *v) { return v; }
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align16] = (void*)my_amx_Align;
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align32] = (void*)my_amx_Align;
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align64] = (void*)my_amx_Align;
hooks::amx_Exec_hook.Install(
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec],
(void*)hooks::amx_Exec);
hooks::amx_Callback_hook.Install(
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Callback],
(void*)hooks::amx_Callback);
#ifdef _WIN32
SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
#endif
// Read plugin settings from server.cfg.
ConfigReader server_cfg("server.cfg");
cfg::profile_gamemode = server_cfg.GetOption("profile_gamemode", cfg::profile_gamemode);
cfg::profile_filterscripts = server_cfg.GetOption("profile_filterscripts", cfg::profile_filterscripts);
cfg::profile_format = server_cfg.GetOption("profile_format", cfg::profile_format);
cfg::call_graph = server_cfg.GetOption("call_graph", cfg::call_graph);
cfg::call_graph_format = server_cfg.GetOption("call_graph_format", cfg::call_graph_format);
logprintf(" Profiler v" PLUGIN_VERSION_STRING " is OK.");
return true;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
::loaded_scripts.push_back(amx);
std::string filename = GetAmxPath(amx);
if (filename.empty()) {
logprintf("[profiler] Can't find matching .amx file");
return AMX_ERR_NONE;
}
cell profiler_enabled = false;
if (GetPublicVariable(amx, "profiler_enabled", profiler_enabled)
&& !profiler_enabled) {
return AMX_ERR_NONE;
}
if (profiler_enabled || WantsProfiler(filename)) {
// Disable SYSREQ.D
amx->sysreq_d = 0;
// Store previous debug hook somewhere before setting a new one
::old_debug_hooks[amx] = amx->debug;
amx_SetDebugHook(amx, hooks::amx_Debug);
// Load debug stats if available
DebugInfo debug_info;
if (HasDebugInfo(amx)) {
debug_info.Load(filename);
if (debug_info.IsLoaded()) {
logprintf("[profiler] Loaded debug stats from '%s'", filename.c_str());
} else {
logprintf("[profiler] Error loading debug stats from '%s'", filename.c_str());
}
}
::profilers[amx] = std::shared_ptr<Profiler>(new Profiler(amx, debug_info, cfg::call_graph));
if (debug_info.IsLoaded()) {
logprintf("[profiler] Attached profiler to '%s'", filename.c_str());
} else {
logprintf("[profiler] Attached profiler to '%s' (no debug symbols)", filename.c_str());
}
}
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
auto profiler = ::profilers[amx];
if (profiler) {
std::string amx_path = GetAmxPath(amx);
std::string amx_name = std::string(amx_path, 0, amx_path.find_last_of("."));
// Convert profile_format to lower case.
std::transform(cfg::profile_format.begin(), cfg::profile_format.end(),
cfg::profile_format.begin(), ::tolower);
auto profile_name = amx_name + "-profile." + cfg::profile_format;
std::ofstream profile_stream(profile_name.c_str());
if (profile_stream.is_open()) {
ProfileWriter *writer = 0;
if (cfg::profile_format == "html") {
writer = new ProfileWriterHtml(&profile_stream, amx_path);
} else if (cfg::profile_format == "txt") {
writer = new ProfileWriterText(&profile_stream, amx_path);
} else if (cfg::profile_format == "xml") {
writer = new ProfileWriterXml(&profile_stream, amx_path);
} else {
logprintf("[profiler] Unknown output format '%s'", cfg::profile_format.c_str());
}
if (writer != 0) {
logprintf("[profiler] Writing '%s'", profile_name.c_str());
profiler->WriteProfile(writer);
delete writer;
}
profile_stream.close();
}
if (cfg::call_graph) {
// Save the call graph as a dot script.
auto call_graph_name = amx_name + "-calls.gv";
std::ofstream call_graph_stream(call_graph_name.c_str());
if (call_graph_stream.is_open()) {
CallGraphWriterGV *call_graph_writer = 0;
if (cfg::call_graph_format == "gv") {
call_graph_writer = new CallGraphWriterGV(&call_graph_stream, amx_path, "SA-MP Server");
} else {
logprintf("[profiler] Unknown call graph format '%s'", cfg::call_graph_format.c_str());
}
if (call_graph_writer != 0) {
logprintf("[profiler] Writing '%s'", call_graph_name.c_str());
profiler->call_graph()->Write(call_graph_writer);
delete call_graph_writer;
}
call_graph_stream.close();
}
}
profilers.erase(amx);
}
return AMX_ERR_NONE;
}
<commit_msg>Remove 'using namespace amx_profiler'<commit_after>// Copyright (c) 2011-2012, Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 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 <algorithm>
#include <cassert>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iterator>
#include <list>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include <unordered_map>
#ifdef _WIN32
#include <windows.h>
#endif
#include <amx/amx.h>
#include <amx_profiler/call_graph_writer_gv.h>
#include <amx_profiler/debug_info.h>
#include <amx_profiler/profile_writer_html.h>
#include <amx_profiler/profile_writer_text.h>
#include <amx_profiler/profile_writer_xml.h>
#include <amx_profiler/profiler.h>
#include "amx_path.h"
#include "config_reader.h"
#include "hook.h"
#include "plugin.h"
#include "version.h"
typedef void (*logprintf_t)(const char *format, ...);
extern void *pAMXFunctions;
static logprintf_t logprintf;
// Profiler instances.
static std::unordered_map<AMX*, std::shared_ptr<amx_profiler::Profiler>> profilers;
// List of loaded scripts, need this to fix AmxUnload bug on Windows.
static std::list<AMX*> loaded_scripts;
// Stores previously set debug hooks (if any).
static std::unordered_map<AMX*, AMX_DEBUG> old_debug_hooks;
// Plugin settings and their defauls.
namespace cfg {
bool profile_gamemode = false;
std::string profile_filterscripts = "";
std::string profile_format = "html";
bool call_graph = false;
std::string call_graph_format = "gv";
};
namespace hooks {
Hook amx_Exec_hook;
Hook amx_Callback_hook;
static int AMXAPI amx_Debug(AMX *amx) {
auto profiler = ::profilers[amx];
if (profiler) {
profiler->amx_Debug();
}
auto iterator = old_debug_hooks.find(amx);
if (iterator != old_debug_hooks.end()) {
if (iterator->second != 0) {
return (iterator->second)(amx);
}
}
return AMX_ERR_NONE;
}
static int AMXAPI amx_Callback(AMX *amx, cell index, cell *result, cell *params) {
Hook::ScopedRemove r(&amx_Callback_hook);
Hook::ScopedInstall i(&amx_Exec_hook);
auto profiler = ::profilers[amx];
if (profiler) {
return profiler->amx_Callback(index, result, params);
} else {
return ::amx_Callback(amx, index, result, params);
}
}
static int AMXAPI amx_Exec(AMX *amx, cell *retval, int index) {
Hook::ScopedRemove r(&amx_Exec_hook);
Hook::ScopedInstall i(&amx_Callback_hook);
auto profiler = ::profilers[amx];
if (profiler) {
return profiler->amx_Exec(retval, index);
} else {
return ::amx_Exec(amx, retval, index);
}
}
} // namespace hooks
static std::string ToUnixPath(const std::string &path) {
std::string fsPath = path;
std::replace(fsPath.begin(), fsPath.end(), '\\', '/');
return fsPath;
}
static bool IsGameMode(const std::string &amxName) {
return ToUnixPath(amxName).find("gamemodes/") != std::string::npos;
}
static bool IsFilterScript(const std::string &amxName) {
return ToUnixPath(amxName).find("filterscripts/") != std::string::npos;
}
static bool GetPublicVariable(AMX *amx, const char *name, cell &value) {
cell amx_addr;
if (amx_FindPubVar(amx, name, &amx_addr) == AMX_ERR_NONE) {
cell *phys_addr;
amx_GetAddr(amx, amx_addr, &phys_addr);
value = *phys_addr;
return true;
}
return false;
}
static bool WantsProfiler(const std::string &amxName) {
std::string goodAmxName = ToUnixPath(amxName);
if (IsGameMode(amxName)) {
if (cfg::profile_gamemode) {
return true;
}
} else if (IsFilterScript(amxName)) {
std::string fsList = cfg::profile_filterscripts;
std::stringstream fsStream(fsList);
do {
std::string fsName;
fsStream >> fsName;
if (goodAmxName == "filterscripts/" + fsName + ".amx"
|| goodAmxName == "filterscripts/" + fsName) {
return true;
}
} while (!fsStream.eof());
}
return false;
}
#ifdef _WIN32
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx);
static BOOL WINAPI ConsoleCtrlHandler(DWORD dwCtrlType) {
switch (dwCtrlType) {
case CTRL_CLOSE_EVENT:
case CTRL_BREAK_EVENT:
for (auto amx : loaded_scripts) {
AmxUnload(amx);
}
}
return FALSE;
}
#endif
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
static void *AMXAPI my_amx_Align(void *v) { return v; }
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align16] = (void*)my_amx_Align;
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align32] = (void*)my_amx_Align;
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align64] = (void*)my_amx_Align;
hooks::amx_Exec_hook.Install(
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec],
(void*)hooks::amx_Exec);
hooks::amx_Callback_hook.Install(
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Callback],
(void*)hooks::amx_Callback);
#ifdef _WIN32
SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
#endif
// Read plugin settings from server.cfg.
ConfigReader server_cfg("server.cfg");
cfg::profile_gamemode = server_cfg.GetOption("profile_gamemode", cfg::profile_gamemode);
cfg::profile_filterscripts = server_cfg.GetOption("profile_filterscripts", cfg::profile_filterscripts);
cfg::profile_format = server_cfg.GetOption("profile_format", cfg::profile_format);
cfg::call_graph = server_cfg.GetOption("call_graph", cfg::call_graph);
cfg::call_graph_format = server_cfg.GetOption("call_graph_format", cfg::call_graph_format);
logprintf(" Profiler v" PLUGIN_VERSION_STRING " is OK.");
return true;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
::loaded_scripts.push_back(amx);
std::string filename = GetAmxPath(amx);
if (filename.empty()) {
logprintf("[profiler] Can't find matching .amx file");
return AMX_ERR_NONE;
}
cell profiler_enabled = false;
if (GetPublicVariable(amx, "profiler_enabled", profiler_enabled)
&& !profiler_enabled) {
return AMX_ERR_NONE;
}
if (profiler_enabled || WantsProfiler(filename)) {
// Disable SYSREQ.D
amx->sysreq_d = 0;
// Store previous debug hook somewhere before setting a new one
::old_debug_hooks[amx] = amx->debug;
amx_SetDebugHook(amx, hooks::amx_Debug);
// Load debug stats if available
amx_profiler::DebugInfo debug_info;
if (amx_profiler::HasDebugInfo(amx)) {
debug_info.Load(filename);
if (debug_info.IsLoaded()) {
logprintf("[profiler] Loaded debug stats from '%s'", filename.c_str());
} else {
logprintf("[profiler] Error loading debug stats from '%s'", filename.c_str());
}
}
::profilers[amx] = std::shared_ptr<amx_profiler::Profiler>(new amx_profiler::Profiler(amx, debug_info, cfg::call_graph));
if (debug_info.IsLoaded()) {
logprintf("[profiler] Attached profiler to '%s'", filename.c_str());
} else {
logprintf("[profiler] Attached profiler to '%s' (no debug symbols)", filename.c_str());
}
}
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
auto profiler = ::profilers[amx];
if (profiler) {
std::string amx_path = GetAmxPath(amx);
std::string amx_name = std::string(amx_path, 0, amx_path.find_last_of("."));
// Convert profile_format to lower case.
std::transform(
cfg::profile_format.begin(),
cfg::profile_format.end(),
cfg::profile_format.begin(),
::tolower
);
auto profile_name = amx_name + "-profile." + cfg::profile_format;
std::ofstream profile_stream(profile_name.c_str());
if (profile_stream.is_open()) {
amx_profiler::ProfileWriter *writer = 0;
if (cfg::profile_format == "html") {
writer = new amx_profiler::ProfileWriterHtml(&profile_stream, amx_path);
} else if (cfg::profile_format == "txt") {
writer = new amx_profiler::ProfileWriterText(&profile_stream, amx_path);
} else if (cfg::profile_format == "xml") {
writer = new amx_profiler::ProfileWriterXml(&profile_stream, amx_path);
} else {
logprintf("[profiler] Unknown output format '%s'", cfg::profile_format.c_str());
}
if (writer != 0) {
logprintf("[profiler] Writing '%s'", profile_name.c_str());
profiler->WriteProfile(writer);
delete writer;
}
profile_stream.close();
}
if (cfg::call_graph) {
// Save the call graph as a dot script.
auto call_graph_name = amx_name + "-calls.gv";
std::ofstream call_graph_stream(call_graph_name.c_str());
if (call_graph_stream.is_open()) {
amx_profiler::CallGraphWriterGV *call_graph_writer = 0;
if (cfg::call_graph_format == "gv") {
call_graph_writer = new amx_profiler::CallGraphWriterGV(&call_graph_stream, amx_path, "SA-MP Server");
} else {
logprintf("[profiler] Unknown call graph format '%s'", cfg::call_graph_format.c_str());
}
if (call_graph_writer != 0) {
logprintf("[profiler] Writing '%s'", call_graph_name.c_str());
profiler->call_graph()->Write(call_graph_writer);
delete call_graph_writer;
}
call_graph_stream.close();
}
}
profilers.erase(amx);
}
return AMX_ERR_NONE;
}
<|endoftext|> |
<commit_before>#include <QSettings>
#include "QGCSettingsWidget.h"
#include "MainWindow.h"
#include "ui_QGCSettingsWidget.h"
#include "LinkManager.h"
#include "MAVLinkProtocol.h"
#include "MAVLinkSettingsWidget.h"
#include "GAudioOutput.h"
#include "ArduPilotMegaMAV.h"
#include <QFileDialog>
QGCSettingsWidget::QGCSettingsWidget(QWidget *parent, Qt::WindowFlags flags) :
QDialog(parent, flags),
ui(new Ui::QGCSettingsWidget)
{
m_init = false;
ui->setupUi(this);
// Add all protocols
/*QList<ProtocolInterface*> protocols = LinkManager::instance()->getProtocols();
foreach (ProtocolInterface* protocol, protocols) {
MAVLinkProtocol* mavlink = dynamic_cast<MAVLinkProtocol*>(protocol);
if (mavlink) {
MAVLinkSettingsWidget* msettings = new MAVLinkSettingsWidget(mavlink, this);
ui->tabWidget->addTab(msettings, "MAVLink");
}
}*/
this->window()->setWindowTitle(tr("APM Planner 2 Settings"));
}
void QGCSettingsWidget::showEvent(QShowEvent *evt)
{
if (!m_init)
{
m_init = true;
// Audio preferences
ui->audioMuteCheckBox->setChecked(GAudioOutput::instance()->isMuted());
connect(ui->audioMuteCheckBox, SIGNAL(toggled(bool)), GAudioOutput::instance(), SLOT(mute(bool)));
connect(GAudioOutput::instance(), SIGNAL(mutedChanged(bool)), ui->audioMuteCheckBox, SLOT(setChecked(bool)));
// Reconnect
ui->reconnectCheckBox->setChecked(MainWindow::instance()->autoReconnectEnabled());
connect(ui->reconnectCheckBox, SIGNAL(clicked(bool)), MainWindow::instance(), SLOT(enableAutoReconnect(bool)));
// Low power mode
ui->lowPowerCheckBox->setChecked(MainWindow::instance()->lowPowerModeEnabled());
connect(ui->lowPowerCheckBox, SIGNAL(clicked(bool)), MainWindow::instance(), SLOT(enableLowPowerMode(bool)));
//Dock widget title bars
ui->titleBarCheckBox->setChecked(MainWindow::instance()->dockWidgetTitleBarsEnabled());
connect(ui->titleBarCheckBox,SIGNAL(clicked(bool)),MainWindow::instance(),SLOT(enableDockWidgetTitleBars(bool)));
ui->heartbeatCheckBox->setChecked(MainWindow::instance()->heartbeatEnabled());
connect(ui->heartbeatCheckBox,SIGNAL(clicked(bool)),MainWindow::instance(),SLOT(enableHeartbeat(bool)));
ui->mavlinkLoggingCheckBox->setChecked(LinkManager::instance()->loggingEnabled());
connect(ui->mavlinkLoggingCheckBox,SIGNAL(clicked(bool)),LinkManager::instance(),SLOT(enableLogging(bool)));
ui->logDirEdit->setText(QGC::logDirectory());
ui->appDataDirEdit->setText((QGC::appDataDirectory()));
ui->paramDirEdit->setText(QGC::parameterDirectory());
ui->mavlinkLogDirEdit->setText((QGC::MAVLinkLogDirectory()));
ui->missionsDirEdit->setText((QGC::missionDirectory()));
connect(ui->logDirSetButton, SIGNAL(clicked()), this, SLOT(setLogDir()));
connect(ui->appDirSetButton, SIGNAL(clicked()), this, SLOT(setAppDataDir()));
connect(ui->paramDirSetButton, SIGNAL(clicked()), this, SLOT(setParamDir()));
connect(ui->mavlinkDirSetButton, SIGNAL(clicked()), this, SLOT(setMAVLinkLogDir()));
connect(ui->missionsSetButton, SIGNAL(clicked()), this, SLOT(setMissionsDir()));
// Style
MainWindow::QGC_MAINWINDOW_STYLE style = (MainWindow::QGC_MAINWINDOW_STYLE)MainWindow::instance()->getStyle();
switch (style) {
case MainWindow::QGC_MAINWINDOW_STYLE_NATIVE:
ui->nativeStyle->setChecked(true);
break;
case MainWindow::QGC_MAINWINDOW_STYLE_INDOOR:
ui->indoorStyle->setChecked(true);
break;
case MainWindow::QGC_MAINWINDOW_STYLE_OUTDOOR:
ui->outdoorStyle->setChecked(true);
break;
}
connect(ui->nativeStyle, SIGNAL(clicked()), MainWindow::instance(), SLOT(loadNativeStyle()));
connect(ui->indoorStyle, SIGNAL(clicked()), MainWindow::instance(), SLOT(loadIndoorStyle()));
connect(ui->outdoorStyle, SIGNAL(clicked()), MainWindow::instance(), SLOT(loadOutdoorStyle()));
connect(ui->extra1LineEdit, SIGNAL(editingFinished()), this, SLOT(ratesChanged()));
connect(ui->extra2LineEdit, SIGNAL(editingFinished()), this, SLOT(ratesChanged()));
connect(ui->extra3LineEdit, SIGNAL(editingFinished()), this, SLOT(ratesChanged()));
connect(ui->positionLineEdit, SIGNAL(editingFinished()), this, SLOT(ratesChanged()));
connect(ui->extStatusLineEdit, SIGNAL(editingFinished()), this, SLOT(ratesChanged()));
connect(ui->rcChannelDataLineEdit, SIGNAL(editingFinished()), this, SLOT(ratesChanged()));
connect(ui->rawSensorLineEdit, SIGNAL(editingFinished()), this, SLOT(ratesChanged()));
connect(UASManager::instance(),SIGNAL(activeUASSet(UASInterface*)),this,SLOT(setActiveUAS(UASInterface*)));
setActiveUAS(UASManager::instance()->getActiveUAS());
setDataRateLineEdits();
QSettings settings;
settings.beginGroup("AUTO_UPDATE");
if(!settings.value("RELEASE_TYPE", "stable").toString().contains("stable")){
ui->enableBetaReleaseCheckBox->setChecked(true);
}
settings.endGroup();
connect(ui->enableBetaReleaseCheckBox, SIGNAL(clicked(bool)), this, SLOT(setBetaRelease(bool)));
}
}
QGCSettingsWidget::~QGCSettingsWidget()
{
delete ui;
}
void QGCSettingsWidget::setLogDir()
{
QFileDialog dlg(this);
dlg.setFileMode(QFileDialog::Directory);
dlg.setDirectory(QGC::logDirectory());
if(dlg.exec() == QDialog::Accepted) {
QDir dir = dlg.directory();
QString name = dir.absolutePath();
QGC::setLogDirectory(name);
ui->logDirEdit->setText(name);
}
}
void QGCSettingsWidget::setMAVLinkLogDir()
{
QFileDialog dlg(this);
dlg.setFileMode(QFileDialog::Directory);
dlg.setDirectory(QGC::MAVLinkLogDirectory());
if(dlg.exec() == QDialog::Accepted) {
QDir dir = dlg.directory();
QString name = dir.absolutePath();
QGC::setMAVLinkLogDirectory(name);
ui->mavlinkLogDirEdit->setText(name);
}
}
void QGCSettingsWidget::setParamDir()
{
QFileDialog dlg(this);
dlg.setFileMode(QFileDialog::Directory);
dlg.setDirectory(QGC::parameterDirectory());
if(dlg.exec() == QDialog::Accepted) {
QDir dir = dlg.directory();
QString name = dir.absolutePath();
QGC::setParameterDirectory(name);
ui->paramDirEdit->setText(name);
}
}
void QGCSettingsWidget::setAppDataDir()
{
QFileDialog dlg(this);
dlg.setFileMode(QFileDialog::Directory);
dlg.setDirectory(QGC::appDataDirectory());
if(dlg.exec() == QDialog::Accepted) {
QDir dir = dlg.directory();
QString name = dir.absolutePath();
QGC::setAppDataDirectory(name);
ui->appDataDirEdit->setText(name);
}
}
void QGCSettingsWidget::setMissionsDir()
{
QFileDialog dlg(this);
dlg.setFileMode(QFileDialog::Directory);
dlg.setDirectory(QGC::missionDirectory());
if(dlg.exec() == QDialog::Accepted) {
QDir dir = dlg.directory();
QString name = dir.absolutePath();
QGC::setMissionDirectory(name);
ui->missionsDirEdit->setText(name);
}
}
void QGCSettingsWidget::setActiveUAS(UASInterface *uas)
{
if (m_uas){
m_uas = NULL;
}
if (uas != NULL){
m_uas = uas;
}
}
void QGCSettingsWidget::setDataRateLineEdits()
{
QSettings settings;
settings.beginGroup("DATA_RATES");
ui->extStatusLineEdit->setText(settings.value("EXT_SYS_STATUS",2).toString());
ui->positionLineEdit->setText(settings.value("POSITION",3).toString());
ui->extra1LineEdit->setText(settings.value("EXTRA1",10).toString());
ui->extra2LineEdit->setText(settings.value("EXTRA2",10).toString());
ui->extra3LineEdit->setText(settings.value("EXTRA3",2).toString());
ui->rawSensorLineEdit->setText(settings.value("RAW_SENSOR_DATA",2).toString());
ui->rcChannelDataLineEdit->setText(settings.value("RC_CHANNEL_DATA",2).toString());
settings.endGroup();
}
void QGCSettingsWidget::ratesChanged()
{
QSettings settings;
settings.beginGroup("DATA_RATES");
bool ok;
int conversion = ui->extStatusLineEdit->text().toInt(&ok);
if (ok){
settings.setValue("EXT_SYS_STATUS",conversion);
}
conversion = ui->positionLineEdit->text().toInt(&ok);
if (ok){
settings.setValue("POSITION",conversion);
}
conversion = ui->extra1LineEdit->text().toInt(&ok);
if (ok){
settings.setValue("EXTRA1", conversion);
}
conversion = ui->extra2LineEdit->text().toInt(&ok);
if (ok){
settings.setValue("EXTRA2", conversion);
}
conversion = ui->extra3LineEdit->text().toInt(&ok);
if (ok){
settings.setValue("EXTRA3", conversion);
}
conversion = ui->rawSensorLineEdit->text().toInt(&ok);
if (ok){
settings.setValue("RAW_SENSOR_DATA", conversion);
}
conversion = ui->rcChannelDataLineEdit->text().toInt(&ok);
if (ok){
settings.setValue("RC_CHANNEL_DATA", conversion);
}
settings.endGroup();
settings.sync();
setDataRateLineEdits();
if (m_uas) {
ArduPilotMegaMAV *mav = dynamic_cast<ArduPilotMegaMAV*>(m_uas);
if (mav != NULL){
mav->RequestAllDataStreams();
}
}
}
void QGCSettingsWidget::setBetaRelease(bool state)
{
QString type;
QSettings settings;
settings.beginGroup("AUTO_UPDATE");
if (state == true){
type = "beta";
} else {
type = "stable";
}
settings.setValue("RELEASE_TYPE", type);
settings.sync();
}
<commit_msg>Settings Widget: added window title for file location dialog<commit_after>#include <QSettings>
#include "QGCSettingsWidget.h"
#include "MainWindow.h"
#include "ui_QGCSettingsWidget.h"
#include "LinkManager.h"
#include "MAVLinkProtocol.h"
#include "MAVLinkSettingsWidget.h"
#include "GAudioOutput.h"
#include "ArduPilotMegaMAV.h"
#include <QFileDialog>
QGCSettingsWidget::QGCSettingsWidget(QWidget *parent, Qt::WindowFlags flags) :
QDialog(parent, flags),
ui(new Ui::QGCSettingsWidget)
{
m_init = false;
ui->setupUi(this);
// Add all protocols
/*QList<ProtocolInterface*> protocols = LinkManager::instance()->getProtocols();
foreach (ProtocolInterface* protocol, protocols) {
MAVLinkProtocol* mavlink = dynamic_cast<MAVLinkProtocol*>(protocol);
if (mavlink) {
MAVLinkSettingsWidget* msettings = new MAVLinkSettingsWidget(mavlink, this);
ui->tabWidget->addTab(msettings, "MAVLink");
}
}*/
this->window()->setWindowTitle(tr("APM Planner 2 Settings"));
}
void QGCSettingsWidget::showEvent(QShowEvent *evt)
{
if (!m_init)
{
m_init = true;
// Audio preferences
ui->audioMuteCheckBox->setChecked(GAudioOutput::instance()->isMuted());
connect(ui->audioMuteCheckBox, SIGNAL(toggled(bool)), GAudioOutput::instance(), SLOT(mute(bool)));
connect(GAudioOutput::instance(), SIGNAL(mutedChanged(bool)), ui->audioMuteCheckBox, SLOT(setChecked(bool)));
// Reconnect
ui->reconnectCheckBox->setChecked(MainWindow::instance()->autoReconnectEnabled());
connect(ui->reconnectCheckBox, SIGNAL(clicked(bool)), MainWindow::instance(), SLOT(enableAutoReconnect(bool)));
// Low power mode
ui->lowPowerCheckBox->setChecked(MainWindow::instance()->lowPowerModeEnabled());
connect(ui->lowPowerCheckBox, SIGNAL(clicked(bool)), MainWindow::instance(), SLOT(enableLowPowerMode(bool)));
//Dock widget title bars
ui->titleBarCheckBox->setChecked(MainWindow::instance()->dockWidgetTitleBarsEnabled());
connect(ui->titleBarCheckBox,SIGNAL(clicked(bool)),MainWindow::instance(),SLOT(enableDockWidgetTitleBars(bool)));
ui->heartbeatCheckBox->setChecked(MainWindow::instance()->heartbeatEnabled());
connect(ui->heartbeatCheckBox,SIGNAL(clicked(bool)),MainWindow::instance(),SLOT(enableHeartbeat(bool)));
ui->mavlinkLoggingCheckBox->setChecked(LinkManager::instance()->loggingEnabled());
connect(ui->mavlinkLoggingCheckBox,SIGNAL(clicked(bool)),LinkManager::instance(),SLOT(enableLogging(bool)));
ui->logDirEdit->setText(QGC::logDirectory());
ui->appDataDirEdit->setText((QGC::appDataDirectory()));
ui->paramDirEdit->setText(QGC::parameterDirectory());
ui->mavlinkLogDirEdit->setText((QGC::MAVLinkLogDirectory()));
ui->missionsDirEdit->setText((QGC::missionDirectory()));
connect(ui->logDirSetButton, SIGNAL(clicked()), this, SLOT(setLogDir()));
connect(ui->appDirSetButton, SIGNAL(clicked()), this, SLOT(setAppDataDir()));
connect(ui->paramDirSetButton, SIGNAL(clicked()), this, SLOT(setParamDir()));
connect(ui->mavlinkDirSetButton, SIGNAL(clicked()), this, SLOT(setMAVLinkLogDir()));
connect(ui->missionsSetButton, SIGNAL(clicked()), this, SLOT(setMissionsDir()));
// Style
MainWindow::QGC_MAINWINDOW_STYLE style = (MainWindow::QGC_MAINWINDOW_STYLE)MainWindow::instance()->getStyle();
switch (style) {
case MainWindow::QGC_MAINWINDOW_STYLE_NATIVE:
ui->nativeStyle->setChecked(true);
break;
case MainWindow::QGC_MAINWINDOW_STYLE_INDOOR:
ui->indoorStyle->setChecked(true);
break;
case MainWindow::QGC_MAINWINDOW_STYLE_OUTDOOR:
ui->outdoorStyle->setChecked(true);
break;
}
connect(ui->nativeStyle, SIGNAL(clicked()), MainWindow::instance(), SLOT(loadNativeStyle()));
connect(ui->indoorStyle, SIGNAL(clicked()), MainWindow::instance(), SLOT(loadIndoorStyle()));
connect(ui->outdoorStyle, SIGNAL(clicked()), MainWindow::instance(), SLOT(loadOutdoorStyle()));
connect(ui->extra1LineEdit, SIGNAL(editingFinished()), this, SLOT(ratesChanged()));
connect(ui->extra2LineEdit, SIGNAL(editingFinished()), this, SLOT(ratesChanged()));
connect(ui->extra3LineEdit, SIGNAL(editingFinished()), this, SLOT(ratesChanged()));
connect(ui->positionLineEdit, SIGNAL(editingFinished()), this, SLOT(ratesChanged()));
connect(ui->extStatusLineEdit, SIGNAL(editingFinished()), this, SLOT(ratesChanged()));
connect(ui->rcChannelDataLineEdit, SIGNAL(editingFinished()), this, SLOT(ratesChanged()));
connect(ui->rawSensorLineEdit, SIGNAL(editingFinished()), this, SLOT(ratesChanged()));
connect(UASManager::instance(),SIGNAL(activeUASSet(UASInterface*)),this,SLOT(setActiveUAS(UASInterface*)));
setActiveUAS(UASManager::instance()->getActiveUAS());
setDataRateLineEdits();
QSettings settings;
settings.beginGroup("AUTO_UPDATE");
if(!settings.value("RELEASE_TYPE", "stable").toString().contains("stable")){
ui->enableBetaReleaseCheckBox->setChecked(true);
}
settings.endGroup();
connect(ui->enableBetaReleaseCheckBox, SIGNAL(clicked(bool)), this, SLOT(setBetaRelease(bool)));
}
}
QGCSettingsWidget::~QGCSettingsWidget()
{
delete ui;
}
void QGCSettingsWidget::setLogDir()
{
QFileDialog dlg(this, "Set log output directory");
dlg.setFileMode(QFileDialog::Directory);
dlg.setDirectory(QGC::logDirectory());
if(dlg.exec() == QDialog::Accepted) {
QDir dir = dlg.directory();
QString name = dir.absolutePath();
QGC::setLogDirectory(name);
ui->logDirEdit->setText(name);
}
}
void QGCSettingsWidget::setMAVLinkLogDir()
{
QFileDialog dlg(this, "Set tlog output directory");
dlg.setFileMode(QFileDialog::Directory);
dlg.setDirectory(QGC::MAVLinkLogDirectory());
if(dlg.exec() == QDialog::Accepted) {
QDir dir = dlg.directory();
QString name = dir.absolutePath();
QGC::setMAVLinkLogDirectory(name);
ui->mavlinkLogDirEdit->setText(name);
}
}
void QGCSettingsWidget::setParamDir()
{
QFileDialog dlg(this, "Set parameters directory");
dlg.setFileMode(QFileDialog::Directory);
dlg.setDirectory(QGC::parameterDirectory());
if(dlg.exec() == QDialog::Accepted) {
QDir dir = dlg.directory();
QString name = dir.absolutePath();
QGC::setParameterDirectory(name);
ui->paramDirEdit->setText(name);
}
}
void QGCSettingsWidget::setAppDataDir()
{
QFileDialog dlg(this, "Set application data directory");
dlg.setFileMode(QFileDialog::Directory);
dlg.setDirectory(QGC::appDataDirectory());
if(dlg.exec() == QDialog::Accepted) {
QDir dir = dlg.directory();
QString name = dir.absolutePath();
QGC::setAppDataDirectory(name);
ui->appDataDirEdit->setText(name);
}
}
void QGCSettingsWidget::setMissionsDir()
{
QFileDialog dlg(this, "Set missions directory");
dlg.setFileMode(QFileDialog::Directory);
dlg.setDirectory(QGC::missionDirectory());
if(dlg.exec() == QDialog::Accepted) {
QDir dir = dlg.directory();
QString name = dir.absolutePath();
QGC::setMissionDirectory(name);
ui->missionsDirEdit->setText(name);
}
}
void QGCSettingsWidget::setActiveUAS(UASInterface *uas)
{
if (m_uas){
m_uas = NULL;
}
if (uas != NULL){
m_uas = uas;
}
}
void QGCSettingsWidget::setDataRateLineEdits()
{
QSettings settings;
settings.beginGroup("DATA_RATES");
ui->extStatusLineEdit->setText(settings.value("EXT_SYS_STATUS",2).toString());
ui->positionLineEdit->setText(settings.value("POSITION",3).toString());
ui->extra1LineEdit->setText(settings.value("EXTRA1",10).toString());
ui->extra2LineEdit->setText(settings.value("EXTRA2",10).toString());
ui->extra3LineEdit->setText(settings.value("EXTRA3",2).toString());
ui->rawSensorLineEdit->setText(settings.value("RAW_SENSOR_DATA",2).toString());
ui->rcChannelDataLineEdit->setText(settings.value("RC_CHANNEL_DATA",2).toString());
settings.endGroup();
}
void QGCSettingsWidget::ratesChanged()
{
QSettings settings;
settings.beginGroup("DATA_RATES");
bool ok;
int conversion = ui->extStatusLineEdit->text().toInt(&ok);
if (ok){
settings.setValue("EXT_SYS_STATUS",conversion);
}
conversion = ui->positionLineEdit->text().toInt(&ok);
if (ok){
settings.setValue("POSITION",conversion);
}
conversion = ui->extra1LineEdit->text().toInt(&ok);
if (ok){
settings.setValue("EXTRA1", conversion);
}
conversion = ui->extra2LineEdit->text().toInt(&ok);
if (ok){
settings.setValue("EXTRA2", conversion);
}
conversion = ui->extra3LineEdit->text().toInt(&ok);
if (ok){
settings.setValue("EXTRA3", conversion);
}
conversion = ui->rawSensorLineEdit->text().toInt(&ok);
if (ok){
settings.setValue("RAW_SENSOR_DATA", conversion);
}
conversion = ui->rcChannelDataLineEdit->text().toInt(&ok);
if (ok){
settings.setValue("RC_CHANNEL_DATA", conversion);
}
settings.endGroup();
settings.sync();
setDataRateLineEdits();
if (m_uas) {
ArduPilotMegaMAV *mav = dynamic_cast<ArduPilotMegaMAV*>(m_uas);
if (mav != NULL){
mav->RequestAllDataStreams();
}
}
}
void QGCSettingsWidget::setBetaRelease(bool state)
{
QString type;
QSettings settings;
settings.beginGroup("AUTO_UPDATE");
if (state == true){
type = "beta";
} else {
type = "stable";
}
settings.setValue("RELEASE_TYPE", type);
settings.sync();
}
<|endoftext|> |
<commit_before>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
* Copyright (c) 2010 Ruslan Kabatsayev <b7.10110111@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or(at your option ) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "oxygenscrolledwindowdata.h"
#include "../oxygengtkutils.h"
#include "../config.h"
#include "../oxygencairocontext.h"
#include "oxygenanimations.h"
#include "../oxygenstyle.h"
#include <cassert>
#include <iostream>
namespace Oxygen
{
gboolean ScrolledWindowData::targetExposeEvent( GtkWidget* widget, GdkEventExpose* event, gpointer )
{
GtkWidget* child=gtk_bin_get_child(GTK_BIN(widget));
GdkWindow* window=gtk_widget_get_window(child);
#if OXYGEN_DEBUG
std::cerr << "ScrolledWindowData::targetExposeEvent( " << G_OBJECT_TYPE_NAME(widget) << ",, ); child: " << G_OBJECT_TYPE_NAME(child) << "\n";
#endif
// don't do anything if the window isn't composited
if(!gdk_window_get_composited(window))
return FALSE;
Cairo::Context context(gtk_widget_get_window(widget));
// set up clipping independently of GTK version
GtkAllocation alloc;
gtk_widget_get_allocation(child,&alloc);
cairo_rectangle(context,alloc.x,alloc.y,alloc.width,alloc.height);
cairo_clip(context);
gdk_cairo_region(context,event->region);
cairo_clip(context);
// draw the child
gtk_widget_get_allocation(child,&alloc);
gdk_cairo_set_source_window(context,window,alloc.x,alloc.y);
cairo_paint(context);
// draw the shadow
StyleOptions options(widget,gtk_widget_get_state(widget));
options|=NoFill;
options &= ~(Hover|Focus);
if( Style::instance().animations().scrolledWindowEngine().focused( widget ) ) options |= Focus;
if( Style::instance().animations().scrolledWindowEngine().hovered( widget ) ) options |= Hover;
const AnimationData data( Style::instance().animations().widgetStateEngine().get( widget, options, AnimationHover|AnimationFocus, AnimationFocus ) );
const int basicOffset=2;
int offsetX=basicOffset+Style::Entry_SideMargin;
int offsetY=basicOffset;
Style::instance().renderHoleBackground( gtk_widget_get_window(widget), &alloc, alloc.x-offsetX, alloc.y-offsetY, alloc.width+offsetX*2, alloc.height+offsetY*2 );
offsetX-=Style::Entry_SideMargin;
Style::instance().renderHole( gtk_widget_get_window(widget), NULL, alloc.x-offsetX, alloc.y-offsetY, alloc.width+offsetX*2, alloc.height+offsetY*2, options, data );
// let the event propagate
return FALSE;
}
//_____________________________________________
void ScrolledWindowData::connect( GtkWidget* widget )
{
assert( GTK_IS_SCROLLED_WINDOW( widget ) );
assert( !_target );
// store target
_target = widget;
if(gdk_display_supports_composite(gdk_display_get_default()))
{
_compositeEnabled=true;
_exposeId.connect( G_OBJECT(_target), "expose-event", G_CALLBACK( targetExposeEvent ), this, true );
}
// register scrollbars
GtkScrolledWindow* scrolledWindow( GTK_SCROLLED_WINDOW( widget ) );
if( GtkWidget* hScrollBar = gtk_scrolled_window_get_hscrollbar( scrolledWindow ) )
{ registerChild( hScrollBar ); }
if( GtkWidget* vScrollBar = gtk_scrolled_window_get_vscrollbar( scrolledWindow ) )
{ registerChild( vScrollBar ); }
// check child
GtkWidget* child( gtk_bin_get_child( GTK_BIN( widget ) ) );
if( !child ) return;
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::ScrolledWindowData::connect -"
<< " child: " << child << " (" << G_OBJECT_TYPE_NAME( child ) << ")"
<< std::endl;
#endif
if( GTK_IS_TREE_VIEW( child ) || GTK_IS_TEXT_VIEW( child ) || GTK_IS_ICON_VIEW( child ) )
{
registerChild( child );
} else {
// list widget types for which scrolled window needs register
static const char* widgetTypes[] = { "ExoIconView", "FMIconContainer", 0L };
for( unsigned int i = 0; widgetTypes[i]; i++ )
{
if( Gtk::g_object_is_a( G_OBJECT( child ), widgetTypes[i] ) )
{
registerChild( child );
break;
}
}
}
}
//_____________________________________________
void ScrolledWindowData::disconnect( GtkWidget* widget )
{
_target = 0;
for( ChildDataMap::iterator iter = _childrenData.begin(); iter != _childrenData.end(); ++iter )
{ iter->second.disconnect( iter->first ); }
if(_compositeEnabled)
{
_exposeId.disconnect();
GdkWindow* window(0);
if(GTK_IS_WIDGET(_target))
{
window=gtk_widget_get_window(_target);
if(window)
gdk_window_set_composited(window, FALSE);
}
}
_childrenData.clear();
}
//________________________________________________________________________________
void ScrolledWindowData::setHovered( GtkWidget* widget, bool value )
{
bool oldHover( hovered() );
ChildDataMap::iterator iter( _childrenData.find( widget ) );
if( iter != _childrenData.end() ) iter->second._hovered = value;
else return;
// need to schedule repaint of the whole widget
if( oldHover != hovered() && _target ) gtk_widget_queue_draw( _target );
}
//________________________________________________________________________________
void ScrolledWindowData::setFocused( GtkWidget* widget, bool value )
{
bool oldFocus( focused() );
ChildDataMap::iterator iter( _childrenData.find( widget ) );
if( iter != _childrenData.end() ) iter->second._focused = value;
else return;
// need to schedule repaint of the whole widget
if( oldFocus != focused() && _target ) gtk_widget_queue_draw( _target );
}
//_____________________________________________
void ScrolledWindowData::registerChild( GtkWidget* widget )
{
// make sure widget is not already in map
if( _childrenData.find( widget ) == _childrenData.end() )
{
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::ScrolledWindowData::registerChild -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
// adjust event mask
gtk_widget_add_events( widget, GDK_ENTER_NOTIFY_MASK|GDK_LEAVE_NOTIFY_MASK|GDK_FOCUS_CHANGE_MASK );
// allocate new Hover data
ChildData data;
data._destroyId.connect( G_OBJECT(widget), "destroy", G_CALLBACK( childDestroyNotifyEvent ), this );
data._enterId.connect( G_OBJECT(widget), "enter-notify-event", G_CALLBACK( enterNotifyEvent ), this );
data._leaveId.connect( G_OBJECT(widget), "leave-notify-event", G_CALLBACK( leaveNotifyEvent ), this );
data._focusInId.connect( G_OBJECT(widget), "focus-in-event", G_CALLBACK( focusInNotifyEvent ), this );
data._focusOutId.connect( G_OBJECT(widget), "focus-out-event", G_CALLBACK( focusOutNotifyEvent ), this );
// and insert in map
_childrenData.insert( std::make_pair( widget, data ) );
// set initial focus
setFocused( widget, gtk_widget_has_focus( widget ) );
// set initial hover
const bool enabled( gtk_widget_get_state( widget ) != GTK_STATE_INSENSITIVE );
// on connection, needs to check whether mouse pointer is in widget or not
// to have the proper initial value of the hover flag
if( enabled && gtk_widget_get_window( widget ) )
{
gint xPointer,yPointer;
gdk_window_get_pointer( gtk_widget_get_window( widget ), &xPointer, &yPointer, 0L );
const GtkAllocation allocation( Gtk::gtk_widget_get_allocation( widget ) );
const GdkRectangle rect( Gtk::gdk_rectangle( 0, 0, allocation.width, allocation.height ) );
setHovered( widget, Gtk::gdk_rectangle_contains( &rect, xPointer, yPointer ) );
} else setHovered( widget, false );
}
}
//________________________________________________________________________________
void ScrolledWindowData::unregisterChild( GtkWidget* widget )
{
// loopup in hover map
ChildDataMap::iterator iter( _childrenData.find( widget ) );
if( iter == _childrenData.end() ) return;
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::ScrolledWindowData::unregisterChild -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
iter->second.disconnect( widget );
_childrenData.erase( iter );
}
//________________________________________________________________________________
#if OXYGEN_DEBUG
void ScrolledWindowData::ChildData::disconnect( GtkWidget* widget )
#else
void ScrolledWindowData::ChildData::disconnect( GtkWidget* )
#endif
{
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::ScrolledWindowData::ChildData::disconnect -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
_destroyId.disconnect();
_enterId.disconnect();
_leaveId.disconnect();
_focusInId.disconnect();
_focusOutId.disconnect();
_hovered = false;
_focused = false;
}
//____________________________________________________________________________________________
gboolean ScrolledWindowData::childDestroyNotifyEvent( GtkWidget* widget, gpointer data )
{
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::ScrolledWindowData::childDestroyNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<ScrolledWindowData*>(data)->unregisterChild( widget );
return FALSE;
}
//________________________________________________________________________________
gboolean ScrolledWindowData::enterNotifyEvent( GtkWidget* widget, GdkEventCrossing* event, gpointer data )
{
#if OXYGEN_DEBUG
std::cerr << "Oxygen::ScrolledWindowData::enterNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
if( !(event->state & (GDK_BUTTON1_MASK|GDK_BUTTON2_MASK) ) )
{ static_cast<ScrolledWindowData*>( data )->setHovered( widget, true ); }
return FALSE;
}
//________________________________________________________________________________
gboolean ScrolledWindowData::leaveNotifyEvent( GtkWidget* widget, GdkEventCrossing* event, gpointer data )
{
#if OXYGEN_DEBUG
std::cerr << "Oxygen::ScrolledWindowData::leaveNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
if( !(event->state & (GDK_BUTTON1_MASK|GDK_BUTTON2_MASK) ) )
{ static_cast<ScrolledWindowData*>( data )->setHovered( widget, false ); }
return FALSE;
}
//________________________________________________________________________________
gboolean ScrolledWindowData::focusInNotifyEvent( GtkWidget* widget, GdkEvent*, gpointer data )
{
#if OXYGEN_DEBUG
std::cerr << "Oxygen::ScrolledWindowData::focusInNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<ScrolledWindowData*>( data )->setFocused( widget, true );
return FALSE;
}
//________________________________________________________________________________
gboolean ScrolledWindowData::focusOutNotifyEvent( GtkWidget* widget, GdkEvent*, gpointer data )
{
#if OXYGEN_DEBUG
std::cerr << "Oxygen::ScrolledWindowData::focusOutNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<ScrolledWindowData*>( data )->setFocused( widget, false );
return FALSE;
}
}
<commit_msg>Indent "#ifs"<commit_after>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
* Copyright (c) 2010 Ruslan Kabatsayev <b7.10110111@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or(at your option ) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "oxygenscrolledwindowdata.h"
#include "../oxygengtkutils.h"
#include "../config.h"
#include "../oxygencairocontext.h"
#include "oxygenanimations.h"
#include "../oxygenstyle.h"
#include <cassert>
#include <iostream>
namespace Oxygen
{
gboolean ScrolledWindowData::targetExposeEvent( GtkWidget* widget, GdkEventExpose* event, gpointer )
{
GtkWidget* child=gtk_bin_get_child(GTK_BIN(widget));
GdkWindow* window=gtk_widget_get_window(child);
#if OXYGEN_DEBUG
std::cerr << "ScrolledWindowData::targetExposeEvent( " << G_OBJECT_TYPE_NAME(widget) << ",, ); child: " << G_OBJECT_TYPE_NAME(child) << "\n";
#endif
// don't do anything if the window isn't composited
if(!gdk_window_get_composited(window))
return FALSE;
Cairo::Context context(gtk_widget_get_window(widget));
// set up clipping independently of GTK version
GtkAllocation alloc;
gtk_widget_get_allocation(child,&alloc);
cairo_rectangle(context,alloc.x,alloc.y,alloc.width,alloc.height);
cairo_clip(context);
gdk_cairo_region(context,event->region);
cairo_clip(context);
// draw the child
gtk_widget_get_allocation(child,&alloc);
gdk_cairo_set_source_window(context,window,alloc.x,alloc.y);
cairo_paint(context);
// draw the shadow
StyleOptions options(widget,gtk_widget_get_state(widget));
options|=NoFill;
options &= ~(Hover|Focus);
if( Style::instance().animations().scrolledWindowEngine().focused( widget ) ) options |= Focus;
if( Style::instance().animations().scrolledWindowEngine().hovered( widget ) ) options |= Hover;
const AnimationData data( Style::instance().animations().widgetStateEngine().get( widget, options, AnimationHover|AnimationFocus, AnimationFocus ) );
const int basicOffset=2;
int offsetX=basicOffset+Style::Entry_SideMargin;
int offsetY=basicOffset;
Style::instance().renderHoleBackground( gtk_widget_get_window(widget), &alloc, alloc.x-offsetX, alloc.y-offsetY, alloc.width+offsetX*2, alloc.height+offsetY*2 );
offsetX-=Style::Entry_SideMargin;
Style::instance().renderHole( gtk_widget_get_window(widget), NULL, alloc.x-offsetX, alloc.y-offsetY, alloc.width+offsetX*2, alloc.height+offsetY*2, options, data );
// let the event propagate
return FALSE;
}
//_____________________________________________
void ScrolledWindowData::connect( GtkWidget* widget )
{
assert( GTK_IS_SCROLLED_WINDOW( widget ) );
assert( !_target );
// store target
_target = widget;
if(gdk_display_supports_composite(gdk_display_get_default()))
{
_compositeEnabled=true;
_exposeId.connect( G_OBJECT(_target), "expose-event", G_CALLBACK( targetExposeEvent ), this, true );
}
// register scrollbars
GtkScrolledWindow* scrolledWindow( GTK_SCROLLED_WINDOW( widget ) );
if( GtkWidget* hScrollBar = gtk_scrolled_window_get_hscrollbar( scrolledWindow ) )
{ registerChild( hScrollBar ); }
if( GtkWidget* vScrollBar = gtk_scrolled_window_get_vscrollbar( scrolledWindow ) )
{ registerChild( vScrollBar ); }
// check child
GtkWidget* child( gtk_bin_get_child( GTK_BIN( widget ) ) );
if( !child ) return;
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::ScrolledWindowData::connect -"
<< " child: " << child << " (" << G_OBJECT_TYPE_NAME( child ) << ")"
<< std::endl;
#endif
if( GTK_IS_TREE_VIEW( child ) || GTK_IS_TEXT_VIEW( child ) || GTK_IS_ICON_VIEW( child ) )
{
registerChild( child );
} else {
// list widget types for which scrolled window needs register
static const char* widgetTypes[] = { "ExoIconView", "FMIconContainer", 0L };
for( unsigned int i = 0; widgetTypes[i]; i++ )
{
if( Gtk::g_object_is_a( G_OBJECT( child ), widgetTypes[i] ) )
{
registerChild( child );
break;
}
}
}
}
//_____________________________________________
void ScrolledWindowData::disconnect( GtkWidget* widget )
{
_target = 0;
for( ChildDataMap::iterator iter = _childrenData.begin(); iter != _childrenData.end(); ++iter )
{ iter->second.disconnect( iter->first ); }
if(_compositeEnabled)
{
_exposeId.disconnect();
GdkWindow* window(0);
if(GTK_IS_WIDGET(_target))
{
window=gtk_widget_get_window(_target);
if(window)
gdk_window_set_composited(window, FALSE);
}
}
_childrenData.clear();
}
//________________________________________________________________________________
void ScrolledWindowData::setHovered( GtkWidget* widget, bool value )
{
bool oldHover( hovered() );
ChildDataMap::iterator iter( _childrenData.find( widget ) );
if( iter != _childrenData.end() ) iter->second._hovered = value;
else return;
// need to schedule repaint of the whole widget
if( oldHover != hovered() && _target ) gtk_widget_queue_draw( _target );
}
//________________________________________________________________________________
void ScrolledWindowData::setFocused( GtkWidget* widget, bool value )
{
bool oldFocus( focused() );
ChildDataMap::iterator iter( _childrenData.find( widget ) );
if( iter != _childrenData.end() ) iter->second._focused = value;
else return;
// need to schedule repaint of the whole widget
if( oldFocus != focused() && _target ) gtk_widget_queue_draw( _target );
}
//_____________________________________________
void ScrolledWindowData::registerChild( GtkWidget* widget )
{
// make sure widget is not already in map
if( _childrenData.find( widget ) == _childrenData.end() )
{
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::ScrolledWindowData::registerChild -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
// adjust event mask
gtk_widget_add_events( widget, GDK_ENTER_NOTIFY_MASK|GDK_LEAVE_NOTIFY_MASK|GDK_FOCUS_CHANGE_MASK );
// allocate new Hover data
ChildData data;
data._destroyId.connect( G_OBJECT(widget), "destroy", G_CALLBACK( childDestroyNotifyEvent ), this );
data._enterId.connect( G_OBJECT(widget), "enter-notify-event", G_CALLBACK( enterNotifyEvent ), this );
data._leaveId.connect( G_OBJECT(widget), "leave-notify-event", G_CALLBACK( leaveNotifyEvent ), this );
data._focusInId.connect( G_OBJECT(widget), "focus-in-event", G_CALLBACK( focusInNotifyEvent ), this );
data._focusOutId.connect( G_OBJECT(widget), "focus-out-event", G_CALLBACK( focusOutNotifyEvent ), this );
// and insert in map
_childrenData.insert( std::make_pair( widget, data ) );
// set initial focus
setFocused( widget, gtk_widget_has_focus( widget ) );
// set initial hover
const bool enabled( gtk_widget_get_state( widget ) != GTK_STATE_INSENSITIVE );
// on connection, needs to check whether mouse pointer is in widget or not
// to have the proper initial value of the hover flag
if( enabled && gtk_widget_get_window( widget ) )
{
gint xPointer,yPointer;
gdk_window_get_pointer( gtk_widget_get_window( widget ), &xPointer, &yPointer, 0L );
const GtkAllocation allocation( Gtk::gtk_widget_get_allocation( widget ) );
const GdkRectangle rect( Gtk::gdk_rectangle( 0, 0, allocation.width, allocation.height ) );
setHovered( widget, Gtk::gdk_rectangle_contains( &rect, xPointer, yPointer ) );
} else setHovered( widget, false );
}
}
//________________________________________________________________________________
void ScrolledWindowData::unregisterChild( GtkWidget* widget )
{
// loopup in hover map
ChildDataMap::iterator iter( _childrenData.find( widget ) );
if( iter == _childrenData.end() ) return;
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::ScrolledWindowData::unregisterChild -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
iter->second.disconnect( widget );
_childrenData.erase( iter );
}
//________________________________________________________________________________
#if OXYGEN_DEBUG
void ScrolledWindowData::ChildData::disconnect( GtkWidget* widget )
#else
void ScrolledWindowData::ChildData::disconnect( GtkWidget* )
#endif
{
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::ScrolledWindowData::ChildData::disconnect -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
_destroyId.disconnect();
_enterId.disconnect();
_leaveId.disconnect();
_focusInId.disconnect();
_focusOutId.disconnect();
_hovered = false;
_focused = false;
}
//____________________________________________________________________________________________
gboolean ScrolledWindowData::childDestroyNotifyEvent( GtkWidget* widget, gpointer data )
{
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::ScrolledWindowData::childDestroyNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<ScrolledWindowData*>(data)->unregisterChild( widget );
return FALSE;
}
//________________________________________________________________________________
gboolean ScrolledWindowData::enterNotifyEvent( GtkWidget* widget, GdkEventCrossing* event, gpointer data )
{
#if OXYGEN_DEBUG
std::cerr << "Oxygen::ScrolledWindowData::enterNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
if( !(event->state & (GDK_BUTTON1_MASK|GDK_BUTTON2_MASK) ) )
{ static_cast<ScrolledWindowData*>( data )->setHovered( widget, true ); }
return FALSE;
}
//________________________________________________________________________________
gboolean ScrolledWindowData::leaveNotifyEvent( GtkWidget* widget, GdkEventCrossing* event, gpointer data )
{
#if OXYGEN_DEBUG
std::cerr << "Oxygen::ScrolledWindowData::leaveNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
if( !(event->state & (GDK_BUTTON1_MASK|GDK_BUTTON2_MASK) ) )
{ static_cast<ScrolledWindowData*>( data )->setHovered( widget, false ); }
return FALSE;
}
//________________________________________________________________________________
gboolean ScrolledWindowData::focusInNotifyEvent( GtkWidget* widget, GdkEvent*, gpointer data )
{
#if OXYGEN_DEBUG
std::cerr << "Oxygen::ScrolledWindowData::focusInNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<ScrolledWindowData*>( data )->setFocused( widget, true );
return FALSE;
}
//________________________________________________________________________________
gboolean ScrolledWindowData::focusOutNotifyEvent( GtkWidget* widget, GdkEvent*, gpointer data )
{
#if OXYGEN_DEBUG
std::cerr << "Oxygen::ScrolledWindowData::focusOutNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<ScrolledWindowData*>( data )->setFocused( widget, false );
return FALSE;
}
}
<|endoftext|> |
<commit_before>#include "hibike_message.h"
#define IN_PIN 1
#define CONTROLLER_ID 0 // arbitrarily chosen for now
uint32_t data;
uint32_t subscriptionDelay = 0;
HibikeMessage* m;
void setup() {
Serial.begin(115200);
pinMode(IN_PIN, INPUT);
}
void loop() {
data = digitalRead(IN_PIN);
uint64_t currTime = millis();
// uncomment the line below for fun data spoofing
data = (uint32_t) (currTime) & 0xFFFFFFFF;
if (subscriptionDelay && (currTime > subscriptionDelay)) {
SensorUpdate(CONTROLLER_ID, SensorType::LineFollower, sizeof(data), (uint8_t*) &data).send();
}
m = receiveHibikeMessage();
if (m) {
switch (m->getMessageId()) {
case HibikeMessageType::SubscriptionRequest:
{
subscriptionDelay = ((SubscriptionRequest*) m)->getSubscriptionDelay();
SubscriptionResponse(CONTROLLER_ID).send();
break;
}
case HibikeMessageType::SubscriptionResponse:
case HibikeMessageType::SensorUpdate:
case HibikeMessageType::Error:
default:
// TODO: implement error handling and retries
// TODO: implement other message types
break;
}
delete m;
}
}
<commit_msg>More changes to subscription delay<commit_after>#include "hibike_message.h"
#define IN_PIN 1
#define CONTROLLER_ID 0 // arbitrarily chosen for now
uint32_t data;
// Interval between updates, in milliseconds
uint32_t subscriptionInterval = 0;
// Time at which to send the next subscription
uint32_t subscriptionTime = 0;
HibikeMessage* m;
void setup() {
Serial.begin(115200);
pinMode(IN_PIN, INPUT);
}
void loop() {
data = digitalRead(IN_PIN);
uint64_t currTime = millis();
// uncomment the line below for fun data spoofing
data = (uint32_t) (currTime) & 0xFFFFFFFF;
if (subscriptionInterval && (currTime > subscriptionDelay)) {
SensorUpdate(CONTROLLER_ID, SensorType::LineFollower, sizeof(data), (uint8_t*) &data).send();
}
m = receiveHibikeMessage();
if (m) {
switch (m->getMessageId()) {
case HibikeMessageType::SubscriptionRequest:
{
subscriptionInterval = ((SubscriptionRequest*) m)->getSubscriptionDelay();
subscriptionTime = currTime + subscriptionInterval;
SubscriptionResponse(CONTROLLER_ID).send();
break;
}
case HibikeMessageType::SubscriptionResponse:
case HibikeMessageType::SensorUpdate:
case HibikeMessageType::Error:
default:
// TODO: implement error handling and retries
// TODO: implement other message types
break;
}
delete m;
}
}
<|endoftext|> |
<commit_before>//===-- WindowsResource.cpp -------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the .res file class.
//
//===----------------------------------------------------------------------===//
#include "llvm/Object/WindowsResource.h"
#include "llvm/Object/Error.h"
#include <system_error>
namespace llvm {
namespace object {
static const char ResourceMagic[] = {
'\0', '\0', '\0', '\0', '\x20', '\0', '\0', '\0',
'\xff', '\xff', '\0', '\0', '\xff', '\xff', '\0', '\0'};
static const char NullEntry[16] = {'\0'};
#define RETURN_IF_ERROR(X) \
if (auto EC = X) \
return EC;
WindowsResource::WindowsResource(MemoryBufferRef Source)
: Binary(Binary::ID_WinRes, Source) {
size_t LeadingSize = sizeof(ResourceMagic) + sizeof(NullEntry);
BBS = BinaryByteStream(Data.getBuffer().drop_front(LeadingSize),
support::little);
}
WindowsResource::~WindowsResource() = default;
Expected<std::unique_ptr<WindowsResource>>
WindowsResource::createWindowsResource(MemoryBufferRef Source) {
if (Source.getBufferSize() < sizeof(ResourceMagic) + sizeof(NullEntry))
return make_error<GenericBinaryError>(
"File too small to be a resource file",
object_error::invalid_file_type);
std::unique_ptr<WindowsResource> Ret(new WindowsResource(Source));
return std::move(Ret);
}
Expected<ResourceEntryRef> WindowsResource::getHeadEntry() {
Error Err = Error::success();
auto Ref = ResourceEntryRef(BinaryStreamRef(BBS), this, Err);
if (Err)
return std::move(Err);
return Ref;
}
ResourceEntryRef::ResourceEntryRef(BinaryStreamRef Ref,
const WindowsResource *Owner, Error &Err)
: Reader(Ref), OwningRes(Owner) {
if (loadNext())
Err = make_error<GenericBinaryError>("Could not read first entry.",
object_error::unexpected_eof);
}
Error ResourceEntryRef::moveNext(bool &End) {
// Reached end of all the entries.
if (Reader.bytesRemaining() == 0) {
End = true;
return Error::success();
}
RETURN_IF_ERROR(loadNext());
return Error::success();
}
Error ResourceEntryRef::loadNext() {
uint32_t DataSize;
RETURN_IF_ERROR(Reader.readInteger(DataSize));
uint32_t HeaderSize;
RETURN_IF_ERROR(Reader.readInteger(HeaderSize));
// The data and header size ints are themselves part of the header, so we must
// subtract them from the size.
RETURN_IF_ERROR(
Reader.readStreamRef(HeaderBytes, HeaderSize - 2 * sizeof(uint32_t)));
RETURN_IF_ERROR(Reader.readStreamRef(DataBytes, DataSize));
RETURN_IF_ERROR(Reader.padToAlignment(sizeof(uint32_t)));
return Error::success();
}
} // namespace object
} // namespace llvm
<commit_msg>Fix -Wunneeded-internal-declaration by removing constant arrays only used in sizeof expressions, in favor of constants containing the size directly<commit_after>//===-- WindowsResource.cpp -------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the .res file class.
//
//===----------------------------------------------------------------------===//
#include "llvm/Object/WindowsResource.h"
#include "llvm/Object/Error.h"
#include <system_error>
namespace llvm {
namespace object {
static const size_t ResourceMagicSize = 16;
static const size_t NullEntrySize = 16;
#define RETURN_IF_ERROR(X) \
if (auto EC = X) \
return EC;
WindowsResource::WindowsResource(MemoryBufferRef Source)
: Binary(Binary::ID_WinRes, Source) {
size_t LeadingSize = ResourceMagicSize + NullEntrySize;
BBS = BinaryByteStream(Data.getBuffer().drop_front(LeadingSize),
support::little);
}
WindowsResource::~WindowsResource() = default;
Expected<std::unique_ptr<WindowsResource>>
WindowsResource::createWindowsResource(MemoryBufferRef Source) {
if (Source.getBufferSize() < ResourceMagicSize + NullEntrySize)
return make_error<GenericBinaryError>(
"File too small to be a resource file",
object_error::invalid_file_type);
std::unique_ptr<WindowsResource> Ret(new WindowsResource(Source));
return std::move(Ret);
}
Expected<ResourceEntryRef> WindowsResource::getHeadEntry() {
Error Err = Error::success();
auto Ref = ResourceEntryRef(BinaryStreamRef(BBS), this, Err);
if (Err)
return std::move(Err);
return Ref;
}
ResourceEntryRef::ResourceEntryRef(BinaryStreamRef Ref,
const WindowsResource *Owner, Error &Err)
: Reader(Ref), OwningRes(Owner) {
if (loadNext())
Err = make_error<GenericBinaryError>("Could not read first entry.",
object_error::unexpected_eof);
}
Error ResourceEntryRef::moveNext(bool &End) {
// Reached end of all the entries.
if (Reader.bytesRemaining() == 0) {
End = true;
return Error::success();
}
RETURN_IF_ERROR(loadNext());
return Error::success();
}
Error ResourceEntryRef::loadNext() {
uint32_t DataSize;
RETURN_IF_ERROR(Reader.readInteger(DataSize));
uint32_t HeaderSize;
RETURN_IF_ERROR(Reader.readInteger(HeaderSize));
// The data and header size ints are themselves part of the header, so we must
// subtract them from the size.
RETURN_IF_ERROR(
Reader.readStreamRef(HeaderBytes, HeaderSize - 2 * sizeof(uint32_t)));
RETURN_IF_ERROR(Reader.readStreamRef(DataBytes, DataSize));
RETURN_IF_ERROR(Reader.padToAlignment(sizeof(uint32_t)));
return Error::success();
}
} // namespace object
} // namespace llvm
<|endoftext|> |
<commit_before>// TasksFrame.cpp : implmentation of the CTasksFrame class
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "resource.h"
#include "AboutDlg.h"
#include "ConnectionDlg.h"
#include "TasksView.h"
#include "TasksFrame.h"
#include <jira/jira.hpp>
#include <jira/server.hpp>
#include <net/utf8.hpp>
#include <net/xhr.hpp>
#include <sstream>
#include <thread>
#include "AppSettings.h"
#include "wincrypt.h"
#pragma comment(lib, "crypt32.lib")
std::string contents(LPCWSTR path)
{
std::unique_ptr<FILE, decltype(&fclose)> f{ _wfopen(path, L"r"), fclose };
if (!f)
return std::string();
std::string out;
char buffer[8192];
int read = 0;
while ((read = fread(buffer, 1, sizeof(buffer), f.get())) > 0)
out.append(buffer, buffer + read);
return out;
}
void print(FILE* f, const std::string& s)
{
fwrite(s.c_str(), 1, s.length(), f);
}
void print(FILE* f, const char* s)
{
if (!s)
return;
fwrite(s, 1, strlen(s), f);
}
template <size_t length>
void print(FILE* f, const char(&s)[length])
{
if (!s)
return;
fwrite(s, 1, strlen(s), f);
}
BOOL CTasksFrame::PreTranslateMessage(MSG* pMsg)
{
if (CFameSuper::PreTranslateMessage(pMsg))
return TRUE;
return m_view.PreTranslateMessage(pMsg);
}
BOOL CTasksFrame::OnIdle()
{
UIUpdateToolBar();
return FALSE;
}
LRESULT CTasksFrame::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
// Check if Common Controls 6.0 are used. If yes, use 32-bit (alpha) images
// for the toolbar and command bar. If not, use the old, 4-bit images.
UINT uResID = IDR_MAINFRAME_OLD;
DWORD dwMajor = 0;
DWORD dwMinor = 0;
HRESULT hRet = AtlGetCommCtrlVersion(&dwMajor, &dwMinor);
if (SUCCEEDED(hRet) && dwMajor >= 6)
uResID = IDR_MAINFRAME;
CreateSimpleToolBar(uResID);
m_hWndClient = m_container.Create(m_hWnd, rcDefault, nullptr, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0);
m_view.m_model = m_model;
m_view.setScroller([&](size_t width, size_t height) {
m_container.SetScrollSize(width, height, FALSE, false);
});
m_view.Create(m_container, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0);
#if 0
m_font = AtlCreateControlFont();
#else
int fontSize = 14;
{
CWindowDC dc{ m_hWnd };
fontSize = dc.GetDeviceCaps(LOGPIXELSY) * fontSize / 96;
}
m_font.CreateFont(-fontSize, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY,
DEFAULT_PITCH | FF_SWISS, L"Arial");
#endif
m_view.SetFont(m_font);
m_container.SetClient(m_view, false);
// register object for message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->AddMessageFilter(this);
pLoop->AddIdleHandler(this);
m_taskIcon.Install(m_hWnd, 1, IDR_TASKBAR);
auto hwnd = m_hWnd;
m_model->startup();
return 0;
}
LRESULT CTasksFrame::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
// unregister message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->RemoveMessageFilter(this);
pLoop->RemoveIdleHandler(this);
bHandled = FALSE;
return 1;
}
LRESULT CTasksFrame::OnTaskIconClick(LPARAM /*uMsg*/, BOOL& /*bHandled*/)
{
return 0;
}
LRESULT CTasksFrame::OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
PostMessage(WM_CLOSE);
return 0;
}
LRESULT CTasksFrame::OnFileNew(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CConnectionDlg dlg;
if (dlg.DoModal() == IDOK) {
auto conn = std::make_shared<jira::server>(dlg.serverName, dlg.userName, dlg.userPassword, dlg.serverUrl, jira::search_def{});
m_model->add(conn);
};
return 0;
}
LRESULT CTasksFrame::OnTasksRefersh(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
auto local = m_model->servers();
auto document = m_model->document();
for (auto server : local) {
std::thread{ [server, document] {
server->loadFields();
server->refresh(document);
} }.detach();
}
return 0;
}
LRESULT CTasksFrame::OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CAboutDlg dlg;
dlg.DoModal();
return 0;
}
<commit_msg>[JIRDESK-11] Scrolling issues with out-of-sight parts of scrolled control<commit_after>// TasksFrame.cpp : implmentation of the CTasksFrame class
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "resource.h"
#include "AboutDlg.h"
#include "ConnectionDlg.h"
#include "TasksView.h"
#include "TasksFrame.h"
#include <jira/jira.hpp>
#include <jira/server.hpp>
#include <net/utf8.hpp>
#include <net/xhr.hpp>
#include <sstream>
#include <thread>
#include "AppSettings.h"
#include "wincrypt.h"
#pragma comment(lib, "crypt32.lib")
#undef max
#include <algorithm>
std::string contents(LPCWSTR path)
{
std::unique_ptr<FILE, decltype(&fclose)> f{ _wfopen(path, L"r"), fclose };
if (!f)
return std::string();
std::string out;
char buffer[8192];
int read = 0;
while ((read = fread(buffer, 1, sizeof(buffer), f.get())) > 0)
out.append(buffer, buffer + read);
return out;
}
void print(FILE* f, const std::string& s)
{
fwrite(s.c_str(), 1, s.length(), f);
}
void print(FILE* f, const char* s)
{
if (!s)
return;
fwrite(s, 1, strlen(s), f);
}
template <size_t length>
void print(FILE* f, const char(&s)[length])
{
if (!s)
return;
fwrite(s, 1, strlen(s), f);
}
BOOL CTasksFrame::PreTranslateMessage(MSG* pMsg)
{
if (CFameSuper::PreTranslateMessage(pMsg))
return TRUE;
return m_view.PreTranslateMessage(pMsg);
}
BOOL CTasksFrame::OnIdle()
{
UIUpdateToolBar();
return FALSE;
}
LRESULT CTasksFrame::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
// Check if Common Controls 6.0 are used. If yes, use 32-bit (alpha) images
// for the toolbar and command bar. If not, use the old, 4-bit images.
UINT uResID = IDR_MAINFRAME_OLD;
DWORD dwMajor = 0;
DWORD dwMinor = 0;
HRESULT hRet = AtlGetCommCtrlVersion(&dwMajor, &dwMinor);
if (SUCCEEDED(hRet) && dwMajor >= 6)
uResID = IDR_MAINFRAME;
CreateSimpleToolBar(uResID);
m_hWndClient = m_container.Create(m_hWnd, rcDefault, nullptr, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0);
m_view.m_model = m_model;
m_view.setScroller([&](size_t width, size_t height) {
m_container.SetScrollSize(width, height, TRUE, false);
RECT client;
m_container.GetClientRect(&client);
m_view.SetWindowPos(nullptr, 0, 0,
std::max(width, (size_t)client.right),
std::max(height, (size_t)client.bottom),
SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);
});
m_view.Create(m_container, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0);
#if 0
m_font = AtlCreateControlFont();
#else
int fontSize = 14;
{
CWindowDC dc{ m_hWnd };
fontSize = dc.GetDeviceCaps(LOGPIXELSY) * fontSize / 96;
}
m_font.CreateFont(-fontSize, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY,
DEFAULT_PITCH | FF_SWISS, L"Arial");
#endif
m_view.SetFont(m_font);
m_container.SetClient(m_view, false);
// register object for message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->AddMessageFilter(this);
pLoop->AddIdleHandler(this);
m_taskIcon.Install(m_hWnd, 1, IDR_TASKBAR);
auto hwnd = m_hWnd;
m_model->startup();
return 0;
}
LRESULT CTasksFrame::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
// unregister message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->RemoveMessageFilter(this);
pLoop->RemoveIdleHandler(this);
bHandled = FALSE;
return 1;
}
LRESULT CTasksFrame::OnTaskIconClick(LPARAM /*uMsg*/, BOOL& /*bHandled*/)
{
return 0;
}
LRESULT CTasksFrame::OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
PostMessage(WM_CLOSE);
return 0;
}
LRESULT CTasksFrame::OnFileNew(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CConnectionDlg dlg;
if (dlg.DoModal() == IDOK) {
auto conn = std::make_shared<jira::server>(dlg.serverName, dlg.userName, dlg.userPassword, dlg.serverUrl, jira::search_def{});
m_model->add(conn);
};
return 0;
}
LRESULT CTasksFrame::OnTasksRefersh(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
auto local = m_model->servers();
auto document = m_model->document();
for (auto server : local) {
std::thread{ [server, document] {
server->loadFields();
server->refresh(document);
} }.detach();
}
return 0;
}
LRESULT CTasksFrame::OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CAboutDlg dlg;
dlg.DoModal();
return 0;
}
<|endoftext|> |
<commit_before>#include "nanocv/tensor.h"
#include "nanocv/string.h"
#include "nanocv/tabulator.h"
#include "nanocv/measure.hpp"
#include "nanocv/math/conv2d.hpp"
#include <iostream>
using namespace ncv;
template
<
typename top,
typename tmatrix
>
static void test_cpu(tabulator_t::row_t& row, top op, const tmatrix& idata, const tmatrix& kdata, tmatrix& odata)
{
const size_t trials = 1024;
row << ncv::measure_robustly_usec([&] ()
{
odata.setZero();
op(idata, kdata, odata);
}, trials / kdata.rows());
}
void test_conv2d(tabulator_t::row_t& row, int isize, int ksize)
{
const int osize = isize - ksize + 1;
matrix_t idata(isize, isize);
matrix_t kdata(ksize, ksize);
matrix_t odata(osize, osize);
idata.setRandom();
kdata.setRandom();
odata.setRandom();
idata /= isize;
kdata /= ksize;
odata /= osize;
test_cpu(row, math::conv2d_eig_t(), idata, kdata, odata);
test_cpu(row, math::conv2d_cpp_t(), idata, kdata, odata);
test_cpu(row, math::conv2d_dot_t(), idata, kdata, odata);
test_cpu(row, math::conv2d_mad_t(), idata, kdata, odata);
test_cpu(row, math::conv2d_dyn_t(), idata, kdata, odata);
}
int main(int, char* [])
{
const int min_isize = 12;
const int max_isize = 48;
const int min_ksize = 3;
tabulator_t table("size\\method");
table.header() << "eig [us]"
<< "cpp [us]"
<< "dot [us]"
<< "mad [us]"
<< "dyn [us]"
<< "lin [us]"
<< "lin (buff) [us]";
for (int isize = min_isize; isize <= max_isize; isize += 4)
{
table.clear();
for (int ksize = min_ksize; ksize <= isize - min_ksize; ksize += 2)
{
const string_t header = "(" +
text::to_string(isize) + "x" + text::to_string(isize) + "@" +
text::to_string(ksize) + "x" + text::to_string(ksize) + ")";
tabulator_t::row_t& row = table.append(header);
test_conv2d(row, isize, ksize);
}
table.print(std::cout);
std::cout << std::endl;
}
return EXIT_SUCCESS;
}
<commit_msg>remove unused columns<commit_after>#include "nanocv/tensor.h"
#include "nanocv/string.h"
#include "nanocv/tabulator.h"
#include "nanocv/measure.hpp"
#include "nanocv/math/conv2d.hpp"
#include <iostream>
using namespace ncv;
template
<
typename top,
typename tmatrix
>
static void test_cpu(tabulator_t::row_t& row, top op, const tmatrix& idata, const tmatrix& kdata, tmatrix& odata)
{
const size_t trials = 1024;
row << ncv::measure_robustly_usec([&] ()
{
odata.setZero();
op(idata, kdata, odata);
}, trials / kdata.rows());
}
void test_conv2d(tabulator_t::row_t& row, int isize, int ksize)
{
const int osize = isize - ksize + 1;
matrix_t idata(isize, isize);
matrix_t kdata(ksize, ksize);
matrix_t odata(osize, osize);
idata.setRandom();
kdata.setRandom();
odata.setRandom();
idata /= isize;
kdata /= ksize;
odata /= osize;
test_cpu(row, math::conv2d_eig_t(), idata, kdata, odata);
test_cpu(row, math::conv2d_cpp_t(), idata, kdata, odata);
test_cpu(row, math::conv2d_dot_t(), idata, kdata, odata);
test_cpu(row, math::conv2d_mad_t(), idata, kdata, odata);
test_cpu(row, math::conv2d_dyn_t(), idata, kdata, odata);
}
int main(int, char* [])
{
const int min_isize = 12;
const int max_isize = 48;
const int min_ksize = 3;
tabulator_t table("size\\method");
table.header() << "eig [us]"
<< "cpp [us]"
<< "dot [us]"
<< "mad [us]"
<< "dyn [us]";
for (int isize = min_isize; isize <= max_isize; isize += 4)
{
table.clear();
for (int ksize = min_ksize; ksize <= isize - min_ksize; ksize += 2)
{
const string_t header = "(" +
text::to_string(isize) + "x" + text::to_string(isize) + "@" +
text::to_string(ksize) + "x" + text::to_string(ksize) + ")";
tabulator_t::row_t& row = table.append(header);
test_conv2d(row, isize, ksize);
}
table.print(std::cout);
std::cout << std::endl;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>//===-- GCSE.cpp - SSA based Global Common Subexpr Elimination ------------===//
//
// 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 pass is designed to be a very quick global transformation that
// eliminates global common subexpressions from a function. It does this by
// using an existing value numbering implementation to identify the common
// subexpressions, eliminating them when possible.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/iMemory.h"
#include "llvm/Type.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/ValueNumbering.h"
#include "llvm/Support/InstIterator.h"
#include "Support/Statistic.h"
#include <algorithm>
using namespace llvm;
namespace {
Statistic<> NumInstRemoved("gcse", "Number of instructions removed");
Statistic<> NumLoadRemoved("gcse", "Number of loads removed");
Statistic<> NumNonInsts ("gcse", "Number of instructions removed due "
"to non-instruction values");
class GCSE : public FunctionPass {
std::set<Instruction*> WorkList;
DominatorSet *DomSetInfo;
ValueNumbering *VN;
public:
virtual bool runOnFunction(Function &F);
private:
bool EliminateRedundancies(Instruction *I,std::vector<Value*> &EqualValues);
Instruction *EliminateCSE(Instruction *I, Instruction *Other);
void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
// This transformation requires dominator and immediate dominator info
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<DominatorSet>();
AU.addRequired<ImmediateDominators>();
AU.addRequired<ValueNumbering>();
}
};
RegisterOpt<GCSE> X("gcse", "Global Common Subexpression Elimination");
}
// createGCSEPass - The public interface to this file...
FunctionPass *llvm::createGCSEPass() { return new GCSE(); }
// GCSE::runOnFunction - This is the main transformation entry point for a
// function.
//
bool GCSE::runOnFunction(Function &F) {
bool Changed = false;
// Get pointers to the analysis results that we will be using...
DomSetInfo = &getAnalysis<DominatorSet>();
VN = &getAnalysis<ValueNumbering>();
// Step #1: Add all instructions in the function to the worklist for
// processing. All of the instructions are considered to be our
// subexpressions to eliminate if possible.
//
WorkList.insert(inst_begin(F), inst_end(F));
// Step #2: WorkList processing. Iterate through all of the instructions,
// checking to see if there are any additionally defined subexpressions in the
// program. If so, eliminate them!
//
while (!WorkList.empty()) {
Instruction &I = **WorkList.begin(); // Get an instruction from the worklist
WorkList.erase(WorkList.begin());
// If this instruction computes a value, try to fold together common
// instructions that compute it.
//
if (I.getType() != Type::VoidTy) {
std::vector<Value*> EqualValues;
VN->getEqualNumberNodes(&I, EqualValues);
if (!EqualValues.empty())
Changed |= EliminateRedundancies(&I, EqualValues);
}
}
// When the worklist is empty, return whether or not we changed anything...
return Changed;
}
bool GCSE::EliminateRedundancies(Instruction *I,
std::vector<Value*> &EqualValues) {
// If the EqualValues set contains any non-instruction values, then we know
// that all of the instructions can be replaced with the non-instruction value
// because it is guaranteed to dominate all of the instructions in the
// function. We only have to do hard work if all we have are instructions.
//
for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
if (!isa<Instruction>(EqualValues[i])) {
// Found a non-instruction. Replace all instructions with the
// non-instruction.
//
Value *Replacement = EqualValues[i];
// Make sure we get I as well...
EqualValues[i] = I;
// Replace all instructions with the Replacement value.
for (i = 0; i != e; ++i)
if (Instruction *I = dyn_cast<Instruction>(EqualValues[i])) {
// Change all users of I to use Replacement.
I->replaceAllUsesWith(Replacement);
if (isa<LoadInst>(I))
++NumLoadRemoved; // Keep track of loads eliminated
++NumInstRemoved; // Keep track of number of instructions eliminated
++NumNonInsts; // Keep track of number of insts repl with values
// Erase the instruction from the program.
I->getParent()->getInstList().erase(I);
WorkList.erase(I);
}
return true;
}
// Remove duplicate entries from EqualValues...
std::sort(EqualValues.begin(), EqualValues.end());
EqualValues.erase(std::unique(EqualValues.begin(), EqualValues.end()),
EqualValues.end());
// From this point on, EqualValues is logically a vector of instructions.
//
bool Changed = false;
EqualValues.push_back(I); // Make sure I is included...
while (EqualValues.size() > 1) {
// FIXME, this could be done better than simple iteration!
Instruction *Test = cast<Instruction>(EqualValues.back());
EqualValues.pop_back();
for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
if (Instruction *Ret = EliminateCSE(Test,
cast<Instruction>(EqualValues[i]))) {
if (Ret == Test) // Eliminated EqualValues[i]
EqualValues[i] = Test; // Make sure that we reprocess I at some point
Changed = true;
break;
}
}
return Changed;
}
// ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
// uses of the instruction use First now instead.
//
void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
Instruction &Second = *SI;
//cerr << "DEL " << (void*)Second << Second;
// Add the first instruction back to the worklist
WorkList.insert(First);
// Add all uses of the second instruction to the worklist
for (Value::use_iterator UI = Second.use_begin(), UE = Second.use_end();
UI != UE; ++UI)
WorkList.insert(cast<Instruction>(*UI));
// Make all users of 'Second' now use 'First'
Second.replaceAllUsesWith(First);
// Erase the second instruction from the program
Second.getParent()->getInstList().erase(SI);
}
// EliminateCSE - The two instruction I & Other have been found to be common
// subexpressions. This function is responsible for eliminating one of them,
// and for fixing the worklist to be correct. The instruction that is preserved
// is returned from the function if the other is eliminated, otherwise null is
// returned.
//
Instruction *GCSE::EliminateCSE(Instruction *I, Instruction *Other) {
assert(I != Other);
WorkList.erase(I);
WorkList.erase(Other); // Other may not actually be on the worklist anymore...
// Handle the easy case, where both instructions are in the same basic block
BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
Instruction *Ret = 0;
if (BB1 == BB2) {
// Eliminate the second occurring instruction. Add all uses of the second
// instruction to the worklist.
//
// Scan the basic block looking for the "first" instruction
BasicBlock::iterator BI = BB1->begin();
while (&*BI != I && &*BI != Other) {
++BI;
assert(BI != BB1->end() && "Instructions not found in parent BB!");
}
// Keep track of which instructions occurred first & second
Instruction *First = BI;
Instruction *Second = I != First ? I : Other; // Get iterator to second inst
BI = Second;
// Destroy Second, using First instead.
ReplaceInstWithInst(First, BI);
Ret = First;
// Otherwise, the two instructions are in different basic blocks. If one
// dominates the other instruction, we can simply use it
//
} else if (DomSetInfo->dominates(BB1, BB2)) { // I dom Other?
ReplaceInstWithInst(I, Other);
Ret = I;
} else if (DomSetInfo->dominates(BB2, BB1)) { // Other dom I?
ReplaceInstWithInst(Other, I);
Ret = Other;
} else {
// This code is disabled because it has several problems:
// One, the actual assumption is wrong, as shown by this code:
// int "test"(int %X, int %Y) {
// %Z = add int %X, %Y
// ret int %Z
// Unreachable:
// %Q = add int %X, %Y
// ret int %Q
// }
//
// Here there are no shared dominators. Additionally, this had the habit of
// moving computations where they were not always computed. For example, in
// a case like this:
// if (c) {
// if (d) ...
// else ... X+Y ...
// } else {
// ... X+Y ...
// }
//
// In this case, the expression would be hoisted to outside the 'if' stmt,
// causing the expression to be evaluated, even for the if (d) path, which
// could cause problems, if, for example, it caused a divide by zero. In
// general the problem this case is trying to solve is better addressed with
// PRE than GCSE.
//
return 0;
}
if (isa<LoadInst>(Ret))
++NumLoadRemoved; // Keep track of loads eliminated
++NumInstRemoved; // Keep track of number of instructions eliminated
// Add all users of Ret to the worklist...
for (Value::use_iterator I = Ret->use_begin(), E = Ret->use_end(); I != E;++I)
if (Instruction *Inst = dyn_cast<Instruction>(*I))
WorkList.insert(Inst);
return Ret;
}
<commit_msg>Add debug output<commit_after>//===-- GCSE.cpp - SSA based Global Common Subexpr Elimination ------------===//
//
// 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 pass is designed to be a very quick global transformation that
// eliminates global common subexpressions from a function. It does this by
// using an existing value numbering implementation to identify the common
// subexpressions, eliminating them when possible.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/iMemory.h"
#include "llvm/Type.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/ValueNumbering.h"
#include "llvm/Support/InstIterator.h"
#include "Support/Statistic.h"
#include "Support/Debug.h"
#include <algorithm>
using namespace llvm;
namespace {
Statistic<> NumInstRemoved("gcse", "Number of instructions removed");
Statistic<> NumLoadRemoved("gcse", "Number of loads removed");
Statistic<> NumNonInsts ("gcse", "Number of instructions removed due "
"to non-instruction values");
class GCSE : public FunctionPass {
std::set<Instruction*> WorkList;
DominatorSet *DomSetInfo;
ValueNumbering *VN;
public:
virtual bool runOnFunction(Function &F);
private:
bool EliminateRedundancies(Instruction *I,std::vector<Value*> &EqualValues);
Instruction *EliminateCSE(Instruction *I, Instruction *Other);
void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
// This transformation requires dominator and immediate dominator info
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<DominatorSet>();
AU.addRequired<ImmediateDominators>();
AU.addRequired<ValueNumbering>();
}
};
RegisterOpt<GCSE> X("gcse", "Global Common Subexpression Elimination");
}
// createGCSEPass - The public interface to this file...
FunctionPass *llvm::createGCSEPass() { return new GCSE(); }
// GCSE::runOnFunction - This is the main transformation entry point for a
// function.
//
bool GCSE::runOnFunction(Function &F) {
bool Changed = false;
// Get pointers to the analysis results that we will be using...
DomSetInfo = &getAnalysis<DominatorSet>();
VN = &getAnalysis<ValueNumbering>();
// Step #1: Add all instructions in the function to the worklist for
// processing. All of the instructions are considered to be our
// subexpressions to eliminate if possible.
//
WorkList.insert(inst_begin(F), inst_end(F));
// Step #2: WorkList processing. Iterate through all of the instructions,
// checking to see if there are any additionally defined subexpressions in the
// program. If so, eliminate them!
//
while (!WorkList.empty()) {
Instruction &I = **WorkList.begin(); // Get an instruction from the worklist
WorkList.erase(WorkList.begin());
// If this instruction computes a value, try to fold together common
// instructions that compute it.
//
if (I.getType() != Type::VoidTy) {
std::vector<Value*> EqualValues;
VN->getEqualNumberNodes(&I, EqualValues);
if (!EqualValues.empty())
Changed |= EliminateRedundancies(&I, EqualValues);
}
}
// When the worklist is empty, return whether or not we changed anything...
return Changed;
}
bool GCSE::EliminateRedundancies(Instruction *I,
std::vector<Value*> &EqualValues) {
// If the EqualValues set contains any non-instruction values, then we know
// that all of the instructions can be replaced with the non-instruction value
// because it is guaranteed to dominate all of the instructions in the
// function. We only have to do hard work if all we have are instructions.
//
for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
if (!isa<Instruction>(EqualValues[i])) {
// Found a non-instruction. Replace all instructions with the
// non-instruction.
//
Value *Replacement = EqualValues[i];
// Make sure we get I as well...
EqualValues[i] = I;
// Replace all instructions with the Replacement value.
for (i = 0; i != e; ++i)
if (Instruction *I = dyn_cast<Instruction>(EqualValues[i])) {
// Change all users of I to use Replacement.
I->replaceAllUsesWith(Replacement);
if (isa<LoadInst>(I))
++NumLoadRemoved; // Keep track of loads eliminated
++NumInstRemoved; // Keep track of number of instructions eliminated
++NumNonInsts; // Keep track of number of insts repl with values
// Erase the instruction from the program.
I->getParent()->getInstList().erase(I);
WorkList.erase(I);
}
return true;
}
// Remove duplicate entries from EqualValues...
std::sort(EqualValues.begin(), EqualValues.end());
EqualValues.erase(std::unique(EqualValues.begin(), EqualValues.end()),
EqualValues.end());
// From this point on, EqualValues is logically a vector of instructions.
//
bool Changed = false;
EqualValues.push_back(I); // Make sure I is included...
while (EqualValues.size() > 1) {
// FIXME, this could be done better than simple iteration!
Instruction *Test = cast<Instruction>(EqualValues.back());
EqualValues.pop_back();
for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
if (Instruction *Ret = EliminateCSE(Test,
cast<Instruction>(EqualValues[i]))) {
if (Ret == Test) // Eliminated EqualValues[i]
EqualValues[i] = Test; // Make sure that we reprocess I at some point
Changed = true;
break;
}
}
return Changed;
}
// ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
// uses of the instruction use First now instead.
//
void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
Instruction &Second = *SI;
DEBUG(std::cerr << "GCSE: Substituting %" << First->getName() << " for: "
<< Second);
//cerr << "DEL " << (void*)Second << Second;
// Add the first instruction back to the worklist
WorkList.insert(First);
// Add all uses of the second instruction to the worklist
for (Value::use_iterator UI = Second.use_begin(), UE = Second.use_end();
UI != UE; ++UI)
WorkList.insert(cast<Instruction>(*UI));
// Make all users of 'Second' now use 'First'
Second.replaceAllUsesWith(First);
// Erase the second instruction from the program
Second.getParent()->getInstList().erase(SI);
}
// EliminateCSE - The two instruction I & Other have been found to be common
// subexpressions. This function is responsible for eliminating one of them,
// and for fixing the worklist to be correct. The instruction that is preserved
// is returned from the function if the other is eliminated, otherwise null is
// returned.
//
Instruction *GCSE::EliminateCSE(Instruction *I, Instruction *Other) {
assert(I != Other);
WorkList.erase(I);
WorkList.erase(Other); // Other may not actually be on the worklist anymore...
// Handle the easy case, where both instructions are in the same basic block
BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
Instruction *Ret = 0;
if (BB1 == BB2) {
// Eliminate the second occurring instruction. Add all uses of the second
// instruction to the worklist.
//
// Scan the basic block looking for the "first" instruction
BasicBlock::iterator BI = BB1->begin();
while (&*BI != I && &*BI != Other) {
++BI;
assert(BI != BB1->end() && "Instructions not found in parent BB!");
}
// Keep track of which instructions occurred first & second
Instruction *First = BI;
Instruction *Second = I != First ? I : Other; // Get iterator to second inst
BI = Second;
// Destroy Second, using First instead.
ReplaceInstWithInst(First, BI);
Ret = First;
// Otherwise, the two instructions are in different basic blocks. If one
// dominates the other instruction, we can simply use it
//
} else if (DomSetInfo->dominates(BB1, BB2)) { // I dom Other?
ReplaceInstWithInst(I, Other);
Ret = I;
} else if (DomSetInfo->dominates(BB2, BB1)) { // Other dom I?
ReplaceInstWithInst(Other, I);
Ret = Other;
} else {
// This code is disabled because it has several problems:
// One, the actual assumption is wrong, as shown by this code:
// int "test"(int %X, int %Y) {
// %Z = add int %X, %Y
// ret int %Z
// Unreachable:
// %Q = add int %X, %Y
// ret int %Q
// }
//
// Here there are no shared dominators. Additionally, this had the habit of
// moving computations where they were not always computed. For example, in
// a case like this:
// if (c) {
// if (d) ...
// else ... X+Y ...
// } else {
// ... X+Y ...
// }
//
// In this case, the expression would be hoisted to outside the 'if' stmt,
// causing the expression to be evaluated, even for the if (d) path, which
// could cause problems, if, for example, it caused a divide by zero. In
// general the problem this case is trying to solve is better addressed with
// PRE than GCSE.
//
return 0;
}
if (isa<LoadInst>(Ret))
++NumLoadRemoved; // Keep track of loads eliminated
++NumInstRemoved; // Keep track of number of instructions eliminated
// Add all users of Ret to the worklist...
for (Value::use_iterator I = Ret->use_begin(), E = Ret->use_end(); I != E;++I)
if (Instruction *Inst = dyn_cast<Instruction>(*I))
WorkList.insert(Inst);
return Ret;
}
<|endoftext|> |
<commit_before>//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
//
// This pass is a simple loop invariant code motion pass.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/iOperators.h"
#include "llvm/iMemory.h"
#include "llvm/Support/InstVisitor.h"
#include "Support/STLExtras.h"
#include "Support/StatisticReporter.h"
#include <algorithm>
using std::string;
namespace {
Statistic<>NumHoisted("licm\t\t- Number of instructions hoisted out of loop");
Statistic<> NumHoistedLoads("licm\t\t- Number of load insts hoisted");
struct LICM : public FunctionPass, public InstVisitor<LICM> {
virtual bool runOnFunction(Function &F);
/// This transformation requires natural loop information & requires that
/// loop preheaders be inserted into the CFG...
///
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.preservesCFG();
AU.addRequiredID(LoopPreheadersID);
AU.addRequired<LoopInfo>();
AU.addRequired<AliasAnalysis>();
}
private:
Loop *CurLoop; // The current loop we are working on...
BasicBlock *Preheader; // The preheader block of the current loop...
bool Changed; // Set to true when we change anything.
AliasAnalysis *AA; // Currently AliasAnalysis information
/// visitLoop - Hoist expressions out of the specified loop...
///
void visitLoop(Loop *L);
/// inCurrentLoop - Little predicate that returns false if the specified
/// basic block is in a subloop of the current one, not the current one
/// itself.
///
bool inCurrentLoop(BasicBlock *BB) {
for (unsigned i = 0, e = CurLoop->getSubLoops().size(); i != e; ++i)
if (CurLoop->getSubLoops()[i]->contains(BB))
return false; // A subloop actually contains this block!
return true;
}
/// hoist - When an instruction is found to only use loop invariant operands
/// that is safe to hoist, this instruction is called to do the dirty work.
///
void hoist(Instruction &I);
/// pointerInvalidatedByLoop - Return true if the body of this loop may
/// store into the memory location pointed to by V.
///
bool pointerInvalidatedByLoop(Value *V);
/// isLoopInvariant - Return true if the specified value is loop invariant
///
inline bool isLoopInvariant(Value *V) {
if (Instruction *I = dyn_cast<Instruction>(V))
return !CurLoop->contains(I->getParent());
return true; // All non-instructions are loop invariant
}
/// Instruction visitation handlers... these basically control whether or
/// not the specified instruction types are hoisted.
///
friend class InstVisitor<LICM>;
void visitBinaryOperator(Instruction &I) {
if (isLoopInvariant(I.getOperand(0)) && isLoopInvariant(I.getOperand(1)))
hoist(I);
}
void visitCastInst(CastInst &CI) {
Instruction &I = (Instruction&)CI;
if (isLoopInvariant(I.getOperand(0))) hoist(I);
}
void visitShiftInst(ShiftInst &I) { visitBinaryOperator((Instruction&)I); }
void visitLoadInst(LoadInst &LI);
void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
Instruction &I = (Instruction&)GEPI;
for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
if (!isLoopInvariant(I.getOperand(i))) return;
hoist(I);
}
};
RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
}
Pass *createLICMPass() { return new LICM(); }
/// runOnFunction - For LICM, this simply traverses the loop structure of the
/// function, hoisting expressions out of loops if possible.
///
bool LICM::runOnFunction(Function &) {
// Get information about the top level loops in the function...
const std::vector<Loop*> &TopLevelLoops =
getAnalysis<LoopInfo>().getTopLevelLoops();
// Get our alias analysis information...
AA = &getAnalysis<AliasAnalysis>();
// Traverse loops in postorder, hoisting expressions out of the deepest loops
// first.
//
Changed = false;
std::for_each(TopLevelLoops.begin(), TopLevelLoops.end(),
bind_obj(this, &LICM::visitLoop));
return Changed;
}
/// visitLoop - Hoist expressions out of the specified loop...
///
void LICM::visitLoop(Loop *L) {
// Recurse through all subloops before we process this loop...
std::for_each(L->getSubLoops().begin(), L->getSubLoops().end(),
bind_obj(this, &LICM::visitLoop));
CurLoop = L;
// Get the preheader block to move instructions into...
Preheader = L->getLoopPreheader();
assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
// We want to visit all of the instructions in this loop... that are not parts
// of our subloops (they have already had their invariants hoisted out of
// their loop, into this loop, so there is no need to process the BODIES of
// the subloops).
//
for (std::vector<BasicBlock*>::const_iterator
I = L->getBlocks().begin(), E = L->getBlocks().end(); I != E; ++I)
if (inCurrentLoop(*I))
visit(**I);
// Clear out loops state information for the next iteration
CurLoop = 0;
Preheader = 0;
}
/// hoist - When an instruction is found to only use loop invariant operands
/// that is safe to hoist, this instruction is called to do the dirty work.
///
void LICM::hoist(Instruction &Inst) {
if (Inst.use_empty()) return; // Don't (re) hoist dead instructions!
//cerr << "Hoisting " << Inst;
BasicBlock *Header = CurLoop->getHeader();
// Remove the instruction from its current basic block... but don't delete the
// instruction.
Inst.getParent()->getInstList().remove(&Inst);
// Insert the new node in Preheader, before the terminator.
Preheader->getInstList().insert(Preheader->getTerminator(), &Inst);
++NumHoisted;
Changed = true;
}
void LICM::visitLoadInst(LoadInst &LI) {
if (isLoopInvariant(LI.getOperand(0)) &&
!pointerInvalidatedByLoop(LI.getOperand(0))) {
hoist(LI);
++NumHoistedLoads;
}
}
/// pointerInvalidatedByLoop - Return true if the body of this loop may store
/// into the memory location pointed to by V.
///
bool LICM::pointerInvalidatedByLoop(Value *V) {
// Check to see if any of the basic blocks in CurLoop invalidate V.
for (unsigned i = 0, e = CurLoop->getBlocks().size(); i != e; ++i)
if (AA->canBasicBlockModify(*CurLoop->getBlocks()[i], V))
return true;
return false;
}
<commit_msg>Hoist the contents of Loops in depth first order in the dominator tree, rather than in random order. This causes LICM to be DRAMATICALLY more effective. For example, on bzip2.c, it is able to hoist 302 loads and 2380 total instructions, as opposed to 44/338 before. This obviously makes other transformations much more powerful as well!<commit_after>//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
//
// This pass is a simple loop invariant code motion pass.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/iOperators.h"
#include "llvm/iMemory.h"
#include "llvm/Support/InstVisitor.h"
#include "Support/STLExtras.h"
#include "Support/StatisticReporter.h"
#include <algorithm>
using std::string;
namespace {
Statistic<>NumHoisted("licm\t\t- Number of instructions hoisted out of loop");
Statistic<> NumHoistedLoads("licm\t\t- Number of load insts hoisted");
struct LICM : public FunctionPass, public InstVisitor<LICM> {
virtual bool runOnFunction(Function &F);
/// This transformation requires natural loop information & requires that
/// loop preheaders be inserted into the CFG...
///
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.preservesCFG();
AU.addRequiredID(LoopPreheadersID);
AU.addRequired<LoopInfo>();
AU.addRequired<DominatorTree>();
AU.addRequired<AliasAnalysis>();
}
private:
Loop *CurLoop; // The current loop we are working on...
BasicBlock *Preheader; // The preheader block of the current loop...
bool Changed; // Set to true when we change anything.
AliasAnalysis *AA; // Currently AliasAnalysis information
/// visitLoop - Hoist expressions out of the specified loop...
///
void visitLoop(Loop *L);
/// HoistRegion - Walk the specified region of the CFG (defined by all
/// blocks dominated by the specified block, and that are in the current
/// loop) in depth first order w.r.t the DominatorTree. This allows us to
/// visit defintions before uses, allowing us to hoist a loop body in one
/// pass without iteration.
///
void HoistRegion(DominatorTree::Node *N);
/// inCurrentLoop - Little predicate that returns false if the specified
/// basic block is in a subloop of the current one, not the current one
/// itself.
///
bool inCurrentLoop(BasicBlock *BB) {
for (unsigned i = 0, e = CurLoop->getSubLoops().size(); i != e; ++i)
if (CurLoop->getSubLoops()[i]->contains(BB))
return false; // A subloop actually contains this block!
return true;
}
/// hoist - When an instruction is found to only use loop invariant operands
/// that is safe to hoist, this instruction is called to do the dirty work.
///
void hoist(Instruction &I);
/// pointerInvalidatedByLoop - Return true if the body of this loop may
/// store into the memory location pointed to by V.
///
bool pointerInvalidatedByLoop(Value *V);
/// isLoopInvariant - Return true if the specified value is loop invariant
///
inline bool isLoopInvariant(Value *V) {
if (Instruction *I = dyn_cast<Instruction>(V))
return !CurLoop->contains(I->getParent());
return true; // All non-instructions are loop invariant
}
/// Instruction visitation handlers... these basically control whether or
/// not the specified instruction types are hoisted.
///
friend class InstVisitor<LICM>;
void visitBinaryOperator(Instruction &I) {
if (isLoopInvariant(I.getOperand(0)) && isLoopInvariant(I.getOperand(1)))
hoist(I);
}
void visitCastInst(CastInst &CI) {
Instruction &I = (Instruction&)CI;
if (isLoopInvariant(I.getOperand(0))) hoist(I);
}
void visitShiftInst(ShiftInst &I) { visitBinaryOperator((Instruction&)I); }
void visitLoadInst(LoadInst &LI);
void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
Instruction &I = (Instruction&)GEPI;
for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
if (!isLoopInvariant(I.getOperand(i))) return;
hoist(I);
}
};
RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
}
Pass *createLICMPass() { return new LICM(); }
/// runOnFunction - For LICM, this simply traverses the loop structure of the
/// function, hoisting expressions out of loops if possible.
///
bool LICM::runOnFunction(Function &) {
// Get information about the top level loops in the function...
const std::vector<Loop*> &TopLevelLoops =
getAnalysis<LoopInfo>().getTopLevelLoops();
// Get our alias analysis information...
AA = &getAnalysis<AliasAnalysis>();
// Traverse loops in postorder, hoisting expressions out of the deepest loops
// first.
//
Changed = false;
std::for_each(TopLevelLoops.begin(), TopLevelLoops.end(),
bind_obj(this, &LICM::visitLoop));
return Changed;
}
/// visitLoop - Hoist expressions out of the specified loop...
///
void LICM::visitLoop(Loop *L) {
// Recurse through all subloops before we process this loop...
std::for_each(L->getSubLoops().begin(), L->getSubLoops().end(),
bind_obj(this, &LICM::visitLoop));
CurLoop = L;
// Get the preheader block to move instructions into...
Preheader = L->getLoopPreheader();
assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
// We want to visit all of the instructions in this loop... that are not parts
// of our subloops (they have already had their invariants hoisted out of
// their loop, into this loop, so there is no need to process the BODIES of
// the subloops).
//
// Traverse the body of the loop in depth first order on the dominator tree so
// that we are guaranteed to see definitions before we see uses. This allows
// us to perform the LICM transformation in one pass, without iteration.
//
HoistRegion(getAnalysis<DominatorTree>()[L->getHeader()]);
// Clear out loops state information for the next iteration
CurLoop = 0;
Preheader = 0;
}
/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
/// dominated by the specified block, and that are in the current loop) in depth
/// first order w.r.t the DominatorTree. This allows us to visit defintions
/// before uses, allowing us to hoist a loop body in one pass without iteration.
///
void LICM::HoistRegion(DominatorTree::Node *N) {
assert(N != 0 && "Null dominator tree node?");
// This subregion is not in the loop, it has already been already been hoisted
if (!inCurrentLoop(N->getNode()))
return;
visit(*N->getNode());
const std::vector<DominatorTree::Node*> &Children = N->getChildren();
for (unsigned i = 0, e = Children.size(); i != e; ++i)
HoistRegion(Children[i]);
}
/// hoist - When an instruction is found to only use loop invariant operands
/// that is safe to hoist, this instruction is called to do the dirty work.
///
void LICM::hoist(Instruction &Inst) {
DEBUG(std::cerr << "LICM hoisting: " << Inst);
BasicBlock *Header = CurLoop->getHeader();
// Remove the instruction from its current basic block... but don't delete the
// instruction.
Inst.getParent()->getInstList().remove(&Inst);
// Insert the new node in Preheader, before the terminator.
Preheader->getInstList().insert(Preheader->getTerminator(), &Inst);
++NumHoisted;
Changed = true;
}
void LICM::visitLoadInst(LoadInst &LI) {
if (isLoopInvariant(LI.getOperand(0)) &&
!pointerInvalidatedByLoop(LI.getOperand(0))) {
hoist(LI);
++NumHoistedLoads;
}
}
/// pointerInvalidatedByLoop - Return true if the body of this loop may store
/// into the memory location pointed to by V.
///
bool LICM::pointerInvalidatedByLoop(Value *V) {
// Check to see if any of the basic blocks in CurLoop invalidate V.
for (unsigned i = 0, e = CurLoop->getBlocks().size(); i != e; ++i)
if (AA->canBasicBlockModify(*CurLoop->getBlocks()[i], V))
return true;
return false;
}
<|endoftext|> |
<commit_before>//===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Owen Anderson and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass transforms loops by placing phi nodes at the end of the loops for
// all values that are live across the loop boundary. For example, it turns
// the left into the right code:
//
// for (...) for (...)
// if (c) if (c)
// X1 = ... X1 = ...
// else else
// X2 = ... X2 = ...
// X3 = phi(X1, X2) X3 = phi(X1, X2)
// ... = X3 + 4 X4 = phi(X3)
// ... = X4 + 4
//
// This is still valid LLVM; the extra phi nodes are purely redundant, and will
// be trivially eliminated by InstCombine. The major benefit of this
// transformation is that it makes many other loop optimizations, such as
// LoopUnswitching, simpler.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "lcssa"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Constants.h"
#include "llvm/Pass.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/Compiler.h"
#include <algorithm>
#include <map>
using namespace llvm;
STATISTIC(NumLCSSA, "Number of live out of a loop variables");
namespace {
struct VISIBILITY_HIDDEN LCSSA : public LoopPass {
static char ID; // Pass identification, replacement for typeid
LCSSA() : LoopPass((intptr_t)&ID) {}
// Cached analysis information for the current function.
LoopInfo *LI;
DominatorTree *DT;
std::vector<BasicBlock*> LoopBlocks;
virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
void ProcessInstruction(Instruction* Instr,
const std::vector<BasicBlock*>& exitBlocks);
/// This transformation requires natural loop information & requires that
/// loop preheaders be inserted into the CFG. It maintains both of these,
/// as well as the CFG. It also requires dominator information.
///
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequiredID(LoopSimplifyID);
AU.addPreservedID(LoopSimplifyID);
AU.addRequired<LoopInfo>();
AU.addPreserved<LoopInfo>();
AU.addRequired<DominatorTree>();
AU.addPreserved<ScalarEvolution>();
}
private:
void getLoopValuesUsedOutsideLoop(Loop *L,
SetVector<Instruction*> &AffectedValues);
Value *GetValueForBlock(DomTreeNode *BB, Instruction *OrigInst,
std::map<DomTreeNode*, Value*> &Phis);
/// inLoop - returns true if the given block is within the current loop
const bool inLoop(BasicBlock* B) {
return std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), B);
}
};
char LCSSA::ID = 0;
RegisterPass<LCSSA> X("lcssa", "Loop-Closed SSA Form Pass");
}
LoopPass *llvm::createLCSSAPass() { return new LCSSA(); }
const PassInfo *llvm::LCSSAID = X.getPassInfo();
/// runOnFunction - Process all loops in the function, inner-most out.
bool LCSSA::runOnLoop(Loop *L, LPPassManager &LPM) {
LI = &LPM.getAnalysis<LoopInfo>();
DT = &getAnalysis<DominatorTree>();
// Speed up queries by creating a sorted list of blocks
LoopBlocks.clear();
LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
std::sort(LoopBlocks.begin(), LoopBlocks.end());
SetVector<Instruction*> AffectedValues;
getLoopValuesUsedOutsideLoop(L, AffectedValues);
// If no values are affected, we can save a lot of work, since we know that
// nothing will be changed.
if (AffectedValues.empty())
return false;
std::vector<BasicBlock*> exitBlocks;
L->getExitBlocks(exitBlocks);
// Iterate over all affected values for this loop and insert Phi nodes
// for them in the appropriate exit blocks
for (SetVector<Instruction*>::iterator I = AffectedValues.begin(),
E = AffectedValues.end(); I != E; ++I)
ProcessInstruction(*I, exitBlocks);
assert(L->isLCSSAForm());
return true;
}
/// processInstruction - Given a live-out instruction, insert LCSSA Phi nodes,
/// eliminate all out-of-loop uses.
void LCSSA::ProcessInstruction(Instruction *Instr,
const std::vector<BasicBlock*>& exitBlocks) {
++NumLCSSA; // We are applying the transformation
// Keep track of the blocks that have the value available already.
std::map<DomTreeNode*, Value*> Phis;
DomTreeNode *InstrNode = DT->getNode(Instr->getParent());
// Insert the LCSSA phi's into the exit blocks (dominated by the value), and
// add them to the Phi's map.
for (std::vector<BasicBlock*>::const_iterator BBI = exitBlocks.begin(),
BBE = exitBlocks.end(); BBI != BBE; ++BBI) {
BasicBlock *BB = *BBI;
DomTreeNode *ExitBBNode = DT->getNode(BB);
Value *&Phi = Phis[ExitBBNode];
if (!Phi && DT->dominates(InstrNode, ExitBBNode)) {
PHINode *PN = new PHINode(Instr->getType(), Instr->getName()+".lcssa",
BB->begin());
PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
// Remember that this phi makes the value alive in this block.
Phi = PN;
// Add inputs from inside the loop for this PHI.
for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
PN->addIncoming(Instr, *PI);
}
}
// Record all uses of Instr outside the loop. We need to rewrite these. The
// LCSSA phis won't be included because they use the value in the loop.
for (Value::use_iterator UI = Instr->use_begin(), E = Instr->use_end();
UI != E;) {
BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
if (PHINode *P = dyn_cast<PHINode>(*UI)) {
unsigned OperandNo = UI.getOperandNo();
UserBB = P->getIncomingBlock(OperandNo/2);
}
// If the user is in the loop, don't rewrite it!
if (UserBB == Instr->getParent() || inLoop(UserBB)) {
++UI;
continue;
}
// Otherwise, patch up uses of the value with the appropriate LCSSA Phi,
// inserting PHI nodes into join points where needed.
Value *Val = GetValueForBlock(DT->getNode(UserBB), Instr, Phis);
// Preincrement the iterator to avoid invalidating it when we change the
// value.
Use &U = UI.getUse();
++UI;
U.set(Val);
}
}
/// getLoopValuesUsedOutsideLoop - Return any values defined in the loop that
/// are used by instructions outside of it.
void LCSSA::getLoopValuesUsedOutsideLoop(Loop *L,
SetVector<Instruction*> &AffectedValues) {
// FIXME: For large loops, we may be able to avoid a lot of use-scanning
// by using dominance information. In particular, if a block does not
// dominate any of the loop exits, then none of the values defined in the
// block could be used outside the loop.
for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
BB != E; ++BB) {
for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
++UI) {
BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
if (PHINode* p = dyn_cast<PHINode>(*UI)) {
unsigned OperandNo = UI.getOperandNo();
UserBB = p->getIncomingBlock(OperandNo/2);
}
if (*BB != UserBB && !inLoop(UserBB)) {
AffectedValues.insert(I);
break;
}
}
}
}
/// GetValueForBlock - Get the value to use within the specified basic block.
/// available values are in Phis.
Value *LCSSA::GetValueForBlock(DomTreeNode *BB, Instruction *OrigInst,
std::map<DomTreeNode*, Value*> &Phis) {
// If there is no dominator info for this BB, it is unreachable.
if (BB == 0)
return UndefValue::get(OrigInst->getType());
// If we have already computed this value, return the previously computed val.
Value *&V = Phis[BB];
if (V) return V;
DomTreeNode *IDom = BB->getIDom();
// Otherwise, there are two cases: we either have to insert a PHI node or we
// don't. We need to insert a PHI node if this block is not dominated by one
// of the exit nodes from the loop (the loop could have multiple exits, and
// though the value defined *inside* the loop dominated all its uses, each
// exit by itself may not dominate all the uses).
//
// The simplest way to check for this condition is by checking to see if the
// idom is in the loop. If so, we *know* that none of the exit blocks
// dominate this block. Note that we *know* that the block defining the
// original instruction is in the idom chain, because if it weren't, then the
// original value didn't dominate this use.
if (!inLoop(IDom->getBlock())) {
// Idom is not in the loop, we must still be "below" the exit block and must
// be fully dominated by the value live in the idom.
return V = GetValueForBlock(IDom, OrigInst, Phis);
}
BasicBlock *BBN = BB->getBlock();
// Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
// now, then get values to fill in the incoming values for the PHI.
PHINode *PN = new PHINode(OrigInst->getType(), OrigInst->getName()+".lcssa",
BBN->begin());
PN->reserveOperandSpace(std::distance(pred_begin(BBN), pred_end(BBN)));
V = PN;
// Fill in the incoming values for the block.
for (pred_iterator PI = pred_begin(BBN), E = pred_end(BBN); PI != E; ++PI)
PN->addIncoming(GetValueForBlock(DT->getNode(*PI), OrigInst, Phis), *PI);
return PN;
}
<commit_msg>Return Undef if the block has no dominator. This was required to allow llvm-gcc build to succeed. Without this change it fails in libstdc++ compilation. This causes no regressions in dejagnu tests. However, someone who knows this code better might want to review it.<commit_after>//===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Owen Anderson and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass transforms loops by placing phi nodes at the end of the loops for
// all values that are live across the loop boundary. For example, it turns
// the left into the right code:
//
// for (...) for (...)
// if (c) if (c)
// X1 = ... X1 = ...
// else else
// X2 = ... X2 = ...
// X3 = phi(X1, X2) X3 = phi(X1, X2)
// ... = X3 + 4 X4 = phi(X3)
// ... = X4 + 4
//
// This is still valid LLVM; the extra phi nodes are purely redundant, and will
// be trivially eliminated by InstCombine. The major benefit of this
// transformation is that it makes many other loop optimizations, such as
// LoopUnswitching, simpler.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "lcssa"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Constants.h"
#include "llvm/Pass.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/Compiler.h"
#include <algorithm>
#include <map>
using namespace llvm;
STATISTIC(NumLCSSA, "Number of live out of a loop variables");
namespace {
struct VISIBILITY_HIDDEN LCSSA : public LoopPass {
static char ID; // Pass identification, replacement for typeid
LCSSA() : LoopPass((intptr_t)&ID) {}
// Cached analysis information for the current function.
LoopInfo *LI;
DominatorTree *DT;
std::vector<BasicBlock*> LoopBlocks;
virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
void ProcessInstruction(Instruction* Instr,
const std::vector<BasicBlock*>& exitBlocks);
/// This transformation requires natural loop information & requires that
/// loop preheaders be inserted into the CFG. It maintains both of these,
/// as well as the CFG. It also requires dominator information.
///
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequiredID(LoopSimplifyID);
AU.addPreservedID(LoopSimplifyID);
AU.addRequired<LoopInfo>();
AU.addPreserved<LoopInfo>();
AU.addRequired<DominatorTree>();
AU.addPreserved<ScalarEvolution>();
}
private:
void getLoopValuesUsedOutsideLoop(Loop *L,
SetVector<Instruction*> &AffectedValues);
Value *GetValueForBlock(DomTreeNode *BB, Instruction *OrigInst,
std::map<DomTreeNode*, Value*> &Phis);
/// inLoop - returns true if the given block is within the current loop
const bool inLoop(BasicBlock* B) {
return std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), B);
}
};
char LCSSA::ID = 0;
RegisterPass<LCSSA> X("lcssa", "Loop-Closed SSA Form Pass");
}
LoopPass *llvm::createLCSSAPass() { return new LCSSA(); }
const PassInfo *llvm::LCSSAID = X.getPassInfo();
/// runOnFunction - Process all loops in the function, inner-most out.
bool LCSSA::runOnLoop(Loop *L, LPPassManager &LPM) {
LI = &LPM.getAnalysis<LoopInfo>();
DT = &getAnalysis<DominatorTree>();
// Speed up queries by creating a sorted list of blocks
LoopBlocks.clear();
LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
std::sort(LoopBlocks.begin(), LoopBlocks.end());
SetVector<Instruction*> AffectedValues;
getLoopValuesUsedOutsideLoop(L, AffectedValues);
// If no values are affected, we can save a lot of work, since we know that
// nothing will be changed.
if (AffectedValues.empty())
return false;
std::vector<BasicBlock*> exitBlocks;
L->getExitBlocks(exitBlocks);
// Iterate over all affected values for this loop and insert Phi nodes
// for them in the appropriate exit blocks
for (SetVector<Instruction*>::iterator I = AffectedValues.begin(),
E = AffectedValues.end(); I != E; ++I)
ProcessInstruction(*I, exitBlocks);
assert(L->isLCSSAForm());
return true;
}
/// processInstruction - Given a live-out instruction, insert LCSSA Phi nodes,
/// eliminate all out-of-loop uses.
void LCSSA::ProcessInstruction(Instruction *Instr,
const std::vector<BasicBlock*>& exitBlocks) {
++NumLCSSA; // We are applying the transformation
// Keep track of the blocks that have the value available already.
std::map<DomTreeNode*, Value*> Phis;
DomTreeNode *InstrNode = DT->getNode(Instr->getParent());
// Insert the LCSSA phi's into the exit blocks (dominated by the value), and
// add them to the Phi's map.
for (std::vector<BasicBlock*>::const_iterator BBI = exitBlocks.begin(),
BBE = exitBlocks.end(); BBI != BBE; ++BBI) {
BasicBlock *BB = *BBI;
DomTreeNode *ExitBBNode = DT->getNode(BB);
Value *&Phi = Phis[ExitBBNode];
if (!Phi && DT->dominates(InstrNode, ExitBBNode)) {
PHINode *PN = new PHINode(Instr->getType(), Instr->getName()+".lcssa",
BB->begin());
PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
// Remember that this phi makes the value alive in this block.
Phi = PN;
// Add inputs from inside the loop for this PHI.
for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
PN->addIncoming(Instr, *PI);
}
}
// Record all uses of Instr outside the loop. We need to rewrite these. The
// LCSSA phis won't be included because they use the value in the loop.
for (Value::use_iterator UI = Instr->use_begin(), E = Instr->use_end();
UI != E;) {
BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
if (PHINode *P = dyn_cast<PHINode>(*UI)) {
unsigned OperandNo = UI.getOperandNo();
UserBB = P->getIncomingBlock(OperandNo/2);
}
// If the user is in the loop, don't rewrite it!
if (UserBB == Instr->getParent() || inLoop(UserBB)) {
++UI;
continue;
}
// Otherwise, patch up uses of the value with the appropriate LCSSA Phi,
// inserting PHI nodes into join points where needed.
Value *Val = GetValueForBlock(DT->getNode(UserBB), Instr, Phis);
// Preincrement the iterator to avoid invalidating it when we change the
// value.
Use &U = UI.getUse();
++UI;
U.set(Val);
}
}
/// getLoopValuesUsedOutsideLoop - Return any values defined in the loop that
/// are used by instructions outside of it.
void LCSSA::getLoopValuesUsedOutsideLoop(Loop *L,
SetVector<Instruction*> &AffectedValues) {
// FIXME: For large loops, we may be able to avoid a lot of use-scanning
// by using dominance information. In particular, if a block does not
// dominate any of the loop exits, then none of the values defined in the
// block could be used outside the loop.
for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
BB != E; ++BB) {
for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
++UI) {
BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
if (PHINode* p = dyn_cast<PHINode>(*UI)) {
unsigned OperandNo = UI.getOperandNo();
UserBB = p->getIncomingBlock(OperandNo/2);
}
if (*BB != UserBB && !inLoop(UserBB)) {
AffectedValues.insert(I);
break;
}
}
}
}
/// GetValueForBlock - Get the value to use within the specified basic block.
/// available values are in Phis.
Value *LCSSA::GetValueForBlock(DomTreeNode *BB, Instruction *OrigInst,
std::map<DomTreeNode*, Value*> &Phis) {
// If there is no dominator info for this BB, it is unreachable.
if (BB == 0)
return UndefValue::get(OrigInst->getType());
// If we have already computed this value, return the previously computed val.
Value *&V = Phis[BB];
if (V) return V;
DomTreeNode *IDom = BB->getIDom();
// If the block has no dominator, bail
if (!IDom)
return V = UndefValue::get(OrigInst->getType());
// Otherwise, there are two cases: we either have to insert a PHI node or we
// don't. We need to insert a PHI node if this block is not dominated by one
// of the exit nodes from the loop (the loop could have multiple exits, and
// though the value defined *inside* the loop dominated all its uses, each
// exit by itself may not dominate all the uses).
//
// The simplest way to check for this condition is by checking to see if the
// idom is in the loop. If so, we *know* that none of the exit blocks
// dominate this block. Note that we *know* that the block defining the
// original instruction is in the idom chain, because if it weren't, then the
// original value didn't dominate this use.
if (!inLoop(IDom->getBlock())) {
// Idom is not in the loop, we must still be "below" the exit block and must
// be fully dominated by the value live in the idom.
return V = GetValueForBlock(IDom, OrigInst, Phis);
}
BasicBlock *BBN = BB->getBlock();
// Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
// now, then get values to fill in the incoming values for the PHI.
PHINode *PN = new PHINode(OrigInst->getType(), OrigInst->getName()+".lcssa",
BBN->begin());
PN->reserveOperandSpace(std::distance(pred_begin(BBN), pred_end(BBN)));
V = PN;
// Fill in the incoming values for the block.
for (pred_iterator PI = pred_begin(BBN), E = pred_end(BBN); PI != E; ++PI)
PN->addIncoming(GetValueForBlock(DT->getNode(*PI), OrigInst, Phis), *PI);
return PN;
}
<|endoftext|> |
<commit_before>//===--- VMCore/PrintModulePass.cpp - Module/Function Printer -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// PrintModulePass and PrintFunctionPass implementations.
//
//===----------------------------------------------------------------------===//
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Function.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
class VISIBILITY_HIDDEN PrintModulePass : public ModulePass {
raw_ostream *Out; // raw_ostream to print on
bool DeleteStream; // Delete the ostream in our dtor?
public:
static char ID;
PrintModulePass() : ModulePass(&ID), Out(&errs()),
DeleteStream(false) {}
PrintModulePass(raw_ostream *o, bool DS)
: ModulePass(&ID), Out(o), DeleteStream(DS) {}
~PrintModulePass() {
if (DeleteStream) delete Out;
}
bool runOnModule(Module &M) {
(*Out) << M;
Out->flush();
return false;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
};
class PrintFunctionPass : public FunctionPass {
std::string Banner; // String to print before each function
raw_ostream *Out; // raw_ostream to print on
bool DeleteStream; // Delete the ostream in our dtor?
public:
static char ID;
PrintFunctionPass() : FunctionPass(&ID), Banner(""), Out(&errs()),
DeleteStream(false) {}
PrintFunctionPass(const std::string &B, raw_ostream *o, bool DS)
: FunctionPass(&ID), Banner(B), Out(o), DeleteStream(DS) {}
inline ~PrintFunctionPass() {
if (DeleteStream) delete Out;
}
// runOnFunction - This pass just prints a banner followed by the
// function as it's processed.
//
bool runOnFunction(Function &F) {
(*Out) << Banner << static_cast<Value&>(F);
Out->flush();
return false;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
};
}
char PrintModulePass::ID = 0;
static RegisterPass<PrintModulePass>
X("print-module", "Print module to stderr");
char PrintFunctionPass::ID = 0;
static RegisterPass<PrintFunctionPass>
Y("print-function","Print function to stderr");
/// createPrintModulePass - Create and return a pass that writes the
/// module to the specified raw_ostream.
ModulePass *llvm::createPrintModulePass(llvm::raw_ostream *OS,
bool DeleteStream) {
return new PrintModulePass(OS, DeleteStream);
}
/// createPrintFunctionPass - Create and return a pass that prints
/// functions to the specified raw_ostream as they are processed.
FunctionPass *llvm::createPrintFunctionPass(const std::string &Banner,
llvm::raw_ostream *OS,
bool DeleteStream) {
return new PrintFunctionPass(Banner, OS, DeleteStream);
}
<commit_msg>It's not necessary for PrintModulePass to flush the output streams now that errs() is properly non-buffered.<commit_after>//===--- VMCore/PrintModulePass.cpp - Module/Function Printer -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// PrintModulePass and PrintFunctionPass implementations.
//
//===----------------------------------------------------------------------===//
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Function.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
class VISIBILITY_HIDDEN PrintModulePass : public ModulePass {
raw_ostream *Out; // raw_ostream to print on
bool DeleteStream; // Delete the ostream in our dtor?
public:
static char ID;
PrintModulePass() : ModulePass(&ID), Out(&errs()),
DeleteStream(false) {}
PrintModulePass(raw_ostream *o, bool DS)
: ModulePass(&ID), Out(o), DeleteStream(DS) {}
~PrintModulePass() {
if (DeleteStream) delete Out;
}
bool runOnModule(Module &M) {
(*Out) << M;
return false;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
};
class PrintFunctionPass : public FunctionPass {
std::string Banner; // String to print before each function
raw_ostream *Out; // raw_ostream to print on
bool DeleteStream; // Delete the ostream in our dtor?
public:
static char ID;
PrintFunctionPass() : FunctionPass(&ID), Banner(""), Out(&errs()),
DeleteStream(false) {}
PrintFunctionPass(const std::string &B, raw_ostream *o, bool DS)
: FunctionPass(&ID), Banner(B), Out(o), DeleteStream(DS) {}
inline ~PrintFunctionPass() {
if (DeleteStream) delete Out;
}
// runOnFunction - This pass just prints a banner followed by the
// function as it's processed.
//
bool runOnFunction(Function &F) {
(*Out) << Banner << static_cast<Value&>(F);
return false;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
};
}
char PrintModulePass::ID = 0;
static RegisterPass<PrintModulePass>
X("print-module", "Print module to stderr");
char PrintFunctionPass::ID = 0;
static RegisterPass<PrintFunctionPass>
Y("print-function","Print function to stderr");
/// createPrintModulePass - Create and return a pass that writes the
/// module to the specified raw_ostream.
ModulePass *llvm::createPrintModulePass(llvm::raw_ostream *OS,
bool DeleteStream) {
return new PrintModulePass(OS, DeleteStream);
}
/// createPrintFunctionPass - Create and return a pass that prints
/// functions to the specified raw_ostream as they are processed.
FunctionPass *llvm::createPrintFunctionPass(const std::string &Banner,
llvm::raw_ostream *OS,
bool DeleteStream) {
return new PrintFunctionPass(Banner, OS, DeleteStream);
}
<|endoftext|> |
<commit_before>//===-- TypeSymbolTable.cpp - Implement the TypeSymbolTable class ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the TypeSymbolTable class for the VMCore library.
//
//===----------------------------------------------------------------------===//
#include "llvm/TypeSymbolTable.h"
#include "llvm/DerivedTypes.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Streams.h"
#include <algorithm>
using namespace llvm;
#define DEBUG_SYMBOL_TABLE 0
#define DEBUG_ABSTYPE 0
TypeSymbolTable::~TypeSymbolTable() {
// Drop all abstract type references in the type plane...
for (iterator TI = tmap.begin(), TE = tmap.end(); TI != TE; ++TI) {
if (TI->second->isAbstract()) // If abstract, drop the reference...
cast<DerivedType>(TI->second)->removeAbstractTypeUser(this);
}
}
std::string TypeSymbolTable::getUniqueName(const std::string &BaseName) const {
std::string TryName = BaseName;
const_iterator End = tmap.end();
// See if the name exists
while (tmap.find(TryName) != End) // Loop until we find a free
TryName = BaseName + utostr(++LastUnique); // name in the symbol table
return TryName;
}
// lookup a type by name - returns null on failure
Type* TypeSymbolTable::lookup(const std::string& Name) const {
const_iterator TI = tmap.find(Name);
if (TI != tmap.end())
return const_cast<Type*>(TI->second);
return 0;
}
// remove - Remove a type from the symbol table...
Type* TypeSymbolTable::remove(iterator Entry) {
assert(Entry != tmap.end() && "Invalid entry to remove!");
const Type* Result = Entry->second;
#if DEBUG_SYMBOL_TABLE
dump();
cerr << " Removing Value: " << Result->getName() << "\n";
#endif
tmap.erase(Entry);
// If we are removing an abstract type, remove the symbol table from it's use
// list...
if (Result->isAbstract()) {
#if DEBUG_ABSTYPE
cerr << "Removing abstract type from symtab"
<< Result->getDescription()
<< "\n";
#endif
cast<DerivedType>(Result)->removeAbstractTypeUser(this);
}
return const_cast<Type*>(Result);
}
// insert - Insert a type into the symbol table with the specified name...
void TypeSymbolTable::insert(const std::string& Name, const Type* T) {
assert(T && "Can't insert null type into symbol table!");
if (tmap.insert(make_pair(Name, T)).second) {
// Type inserted fine with no conflict.
#if DEBUG_SYMBOL_TABLE
dump();
cerr << " Inserted type: " << Name << ": " << T->getDescription() << "\n";
#endif
} else {
// If there is a name conflict...
// Check to see if there is a naming conflict. If so, rename this type!
std::string UniqueName = Name;
if (lookup(Name))
UniqueName = getUniqueName(Name);
#if DEBUG_SYMBOL_TABLE
dump();
cerr << " Inserting type: " << UniqueName << ": "
<< T->getDescription() << "\n";
#endif
// Insert the tmap entry
tmap.insert(make_pair(UniqueName, T));
}
// If we are adding an abstract type, add the symbol table to it's use list.
if (T->isAbstract()) {
cast<DerivedType>(T)->addAbstractTypeUser(this);
#if DEBUG_ABSTYPE
cerr << "Added abstract type to ST: " << T->getDescription() << "\n";
#endif
}
}
// This function is called when one of the types in the type plane are refined
void TypeSymbolTable::refineAbstractType(const DerivedType *OldType,
const Type *NewType) {
// Loop over all of the types in the symbol table, replacing any references
// to OldType with references to NewType. Note that there may be multiple
// occurrences, and although we only need to remove one at a time, it's
// faster to remove them all in one pass.
//
for (iterator I = begin(), E = end(); I != E; ++I) {
if (I->second == (Type*)OldType) { // FIXME when Types aren't const.
#if DEBUG_ABSTYPE
cerr << "Removing type " << OldType->getDescription() << "\n";
#endif
OldType->removeAbstractTypeUser(this);
I->second = (Type*)NewType; // TODO FIXME when types aren't const
if (NewType->isAbstract()) {
#if DEBUG_ABSTYPE
cerr << "Added type " << NewType->getDescription() << "\n";
#endif
cast<DerivedType>(NewType)->addAbstractTypeUser(this);
}
}
}
}
// Handle situation where type becomes Concreate from Abstract
void TypeSymbolTable::typeBecameConcrete(const DerivedType *AbsTy) {
// Loop over all of the types in the symbol table, dropping any abstract
// type user entries for AbsTy which occur because there are names for the
// type.
for (iterator TI = begin(), TE = end(); TI != TE; ++TI)
if (TI->second == const_cast<Type*>(static_cast<const Type*>(AbsTy)))
AbsTy->removeAbstractTypeUser(this);
}
static void DumpTypes(const std::pair<const std::string, const Type*>& T ) {
cerr << " '" << T.first << "' = ";
T.second->dump();
cerr << "\n";
}
void TypeSymbolTable::dump() const {
cerr << "TypeSymbolPlane: ";
for_each(tmap.begin(), tmap.end(), DumpTypes);
}
// vim: sw=2 ai
<commit_msg>Type safety for TypeSymbolTable!<commit_after>//===-- TypeSymbolTable.cpp - Implement the TypeSymbolTable class ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the TypeSymbolTable class for the VMCore library.
//
//===----------------------------------------------------------------------===//
#include "llvm/TypeSymbolTable.h"
#include "llvm/DerivedTypes.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Streams.h"
#include "llvm/Support/Threading.h"
#include "llvm/System/RWMutex.h"
#include <algorithm>
using namespace llvm;
#define DEBUG_SYMBOL_TABLE 0
#define DEBUG_ABSTYPE 0
static ManagedStatic<sys::RWMutex> TypeSymbolTableLock;
TypeSymbolTable::~TypeSymbolTable() {
// Drop all abstract type references in the type plane...
for (iterator TI = tmap.begin(), TE = tmap.end(); TI != TE; ++TI) {
if (TI->second->isAbstract()) // If abstract, drop the reference...
cast<DerivedType>(TI->second)->removeAbstractTypeUser(this);
}
}
std::string TypeSymbolTable::getUniqueName(const std::string &BaseName) const {
std::string TryName = BaseName;
if (llvm_is_multithreaded()) TypeSymbolTableLock->reader_acquire();
const_iterator End = tmap.end();
// See if the name exists
while (tmap.find(TryName) != End) // Loop until we find a free
TryName = BaseName + utostr(++LastUnique); // name in the symbol table
if (llvm_is_multithreaded()) TypeSymbolTableLock->reader_release();
return TryName;
}
// lookup a type by name - returns null on failure
Type* TypeSymbolTable::lookup(const std::string& Name) const {
if (llvm_is_multithreaded()) TypeSymbolTableLock->reader_acquire();
const_iterator TI = tmap.find(Name);
Type* result = 0;
if (TI != tmap.end())
result = const_cast<Type*>(TI->second);
if (llvm_is_multithreaded()) TypeSymbolTableLock->reader_release();
return result;
}
// remove - Remove a type from the symbol table...
Type* TypeSymbolTable::remove(iterator Entry) {
if (llvm_is_multithreaded()) TypeSymbolTableLock->writer_acquire();
assert(Entry != tmap.end() && "Invalid entry to remove!");
const Type* Result = Entry->second;
#if DEBUG_SYMBOL_TABLE
dump();
cerr << " Removing Value: " << Result->getName() << "\n";
#endif
tmap.erase(Entry);
if (llvm_is_multithreaded()) TypeSymbolTableLock->writer_release();
// If we are removing an abstract type, remove the symbol table from it's use
// list...
if (Result->isAbstract()) {
#if DEBUG_ABSTYPE
cerr << "Removing abstract type from symtab"
<< Result->getDescription()
<< "\n";
#endif
cast<DerivedType>(Result)->removeAbstractTypeUser(this);
}
return const_cast<Type*>(Result);
}
// insert - Insert a type into the symbol table with the specified name...
void TypeSymbolTable::insert(const std::string& Name, const Type* T) {
assert(T && "Can't insert null type into symbol table!");
if (llvm_is_multithreaded()) TypeSymbolTableLock->writer_acquire();
if (tmap.insert(make_pair(Name, T)).second) {
// Type inserted fine with no conflict.
#if DEBUG_SYMBOL_TABLE
dump();
cerr << " Inserted type: " << Name << ": " << T->getDescription() << "\n";
#endif
} else {
// If there is a name conflict...
// Check to see if there is a naming conflict. If so, rename this type!
std::string UniqueName = Name;
if (lookup(Name))
UniqueName = getUniqueName(Name);
#if DEBUG_SYMBOL_TABLE
dump();
cerr << " Inserting type: " << UniqueName << ": "
<< T->getDescription() << "\n";
#endif
// Insert the tmap entry
tmap.insert(make_pair(UniqueName, T));
}
if (llvm_is_multithreaded()) TypeSymbolTableLock->writer_release();
// If we are adding an abstract type, add the symbol table to it's use list.
if (T->isAbstract()) {
cast<DerivedType>(T)->addAbstractTypeUser(this);
#if DEBUG_ABSTYPE
cerr << "Added abstract type to ST: " << T->getDescription() << "\n";
#endif
}
}
// This function is called when one of the types in the type plane are refined
void TypeSymbolTable::refineAbstractType(const DerivedType *OldType,
const Type *NewType) {
if (llvm_is_multithreaded()) TypeSymbolTableLock->reader_acquire();
// Loop over all of the types in the symbol table, replacing any references
// to OldType with references to NewType. Note that there may be multiple
// occurrences, and although we only need to remove one at a time, it's
// faster to remove them all in one pass.
//
for (iterator I = begin(), E = end(); I != E; ++I) {
if (I->second == (Type*)OldType) { // FIXME when Types aren't const.
#if DEBUG_ABSTYPE
cerr << "Removing type " << OldType->getDescription() << "\n";
#endif
OldType->removeAbstractTypeUser(this);
I->second = (Type*)NewType; // TODO FIXME when types aren't const
if (NewType->isAbstract()) {
#if DEBUG_ABSTYPE
cerr << "Added type " << NewType->getDescription() << "\n";
#endif
cast<DerivedType>(NewType)->addAbstractTypeUser(this);
}
}
}
if (llvm_is_multithreaded()) TypeSymbolTableLock->reader_release();
}
// Handle situation where type becomes Concreate from Abstract
void TypeSymbolTable::typeBecameConcrete(const DerivedType *AbsTy) {
// Loop over all of the types in the symbol table, dropping any abstract
// type user entries for AbsTy which occur because there are names for the
// type.
if (llvm_is_multithreaded()) TypeSymbolTableLock->reader_acquire();
for (iterator TI = begin(), TE = end(); TI != TE; ++TI)
if (TI->second == const_cast<Type*>(static_cast<const Type*>(AbsTy)))
AbsTy->removeAbstractTypeUser(this);
if (llvm_is_multithreaded()) TypeSymbolTableLock->reader_release();
}
static void DumpTypes(const std::pair<const std::string, const Type*>& T ) {
cerr << " '" << T.first << "' = ";
T.second->dump();
cerr << "\n";
}
void TypeSymbolTable::dump() const {
cerr << "TypeSymbolPlane: ";
if (llvm_is_multithreaded()) TypeSymbolTableLock->reader_acquire();
for_each(tmap.begin(), tmap.end(), DumpTypes);
if (llvm_is_multithreaded()) TypeSymbolTableLock->reader_release();
}
// vim: sw=2 ai
<|endoftext|> |
<commit_before>/* <x0/plugins/proxy.cpp>
*
* This file is part of the x0 web server project and is released under LGPL-3.
* http://www.xzero.ws/
*
* (c) 2009-2010 Christian Parpart <trapni@gentoo.org>
*/
#include <x0/http/HttpPlugin.h>
#include <x0/http/HttpServer.h>
#include <x0/http/HttpRequest.h>
#include <x0/io/BufferSource.h>
#include <x0/strutils.h>
#include <x0/Url.h>
#include <x0/Types.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <fcntl.h>
#include <netdb.h>
/* {{{ -- configuration proposal:
*
* handler setup {
* }
*
* handler main {
* proxy.reverse 'http://127.0.0.1:3000';
* }
*
* --------------------------------------------------------------------------
* possible tweaks:
* - bufsize (0 = unbuffered)
* - timeout.connect
* - timeout.write
* - timeout.read
* - ignore_clientabort
* };
*
*
*/ // }}}
#if 1
# define TRACE(msg...) DEBUG("proxy: " msg)
#else
# define TRACE(msg...) /*!*/
#endif
// {{{ ProxyConnection API
class ProxyConnection :
public x0::HttpMessageProcessor
{
private:
int refCount_;
x0::HttpRequest *request_; //!< client's request
x0::Socket* backend_; //!< connection to backend app
bool cloak_; //!< to cloak or not to cloak the "Server" response header
int connectTimeout_;
int readTimeout_;
int writeTimeout_;
x0::Buffer writeBuffer_;
size_t writeOffset_;
size_t writeProgress_;
x0::Buffer readBuffer_;
private:
void ref();
void unref();
inline void close();
inline void readSome();
inline void writeSome();
void onConnected(x0::Socket* s, int revents);
void io(x0::Socket* s, int revents);
void onRequestChunk(x0::BufferRef&& chunk);
static void onAbort(void *p);
// response (HttpMessageProcessor)
virtual void messageBegin(int version_major, int version_minor, int code, x0::BufferRef&& text);
virtual void messageHeader(x0::BufferRef&& name, x0::BufferRef&& value);
virtual bool messageContent(x0::BufferRef&& chunk);
virtual bool messageEnd();
public:
inline ProxyConnection();
~ProxyConnection();
void start(x0::HttpRequest* in, x0::Socket* backend, bool cloak);
};
// }}}
// {{{ ProxyConnection impl
ProxyConnection::ProxyConnection() :
x0::HttpMessageProcessor(x0::HttpMessageProcessor::RESPONSE),
refCount_(1),
request_(nullptr),
backend_(nullptr),
cloak_(false),
connectTimeout_(0),
readTimeout_(0),
writeTimeout_(0),
writeBuffer_(),
writeOffset_(0),
writeProgress_(0),
readBuffer_()
{
TRACE("ProxyConnection()");
}
ProxyConnection::~ProxyConnection()
{
TRACE("~ProxyConnection()");
if (backend_) {
backend_->close();
delete backend_;
}
if (request_) {
if (request_->status == x0::HttpError::Undefined)
request_->status = x0::HttpError::ServiceUnavailable;
request_->finish();
}
}
void ProxyConnection::ref()
{
++refCount_;
}
void ProxyConnection::unref()
{
assert(refCount_ > 0);
--refCount_;
if (refCount_ == 0) {
delete this;
}
}
void ProxyConnection::close()
{
unref(); // the one from the constructor
}
void ProxyConnection::onAbort(void *p)
{
ProxyConnection *self = reinterpret_cast<ProxyConnection *>(p);
self->close();
}
void ProxyConnection::start(x0::HttpRequest* in, x0::Socket* backend, bool cloak)
{
request_ = in;
request_->setAbortHandler(&ProxyConnection::onAbort, this);
backend_ = backend;
cloak_ = cloak_;
// request line
writeBuffer_.push_back(request_->method);
writeBuffer_.push_back(' ');
writeBuffer_.push_back(request_->uri);
writeBuffer_.push_back(" HTTP/1.1\r\n");
// request headers
for (auto i = request_->requestHeaders.begin(), e = request_->requestHeaders.end(); i != e; ++i) {
if (iequals(i->name, "Content-Transfer")
|| iequals(i->name, "Expect")
|| iequals(i->name, "Connection"))
continue;
TRACE("pass requestHeader(%s: %s)", i->name.str().c_str(), i->value.str().c_str());
writeBuffer_.push_back(i->name);
writeBuffer_.push_back(": ");
writeBuffer_.push_back(i->value);
writeBuffer_.push_back("\r\n");
}
// request headers terminator
writeBuffer_.push_back("\r\n");
if (request_->contentAvailable()) {
TRACE("start: request content available: reading.");
request_->read(std::bind(&ProxyConnection::onRequestChunk, this, std::placeholders::_1));
}
if (backend_->state() == x0::Socket::Connecting) {
TRACE("start: connect in progress");
backend_->setReadyCallback<ProxyConnection, &ProxyConnection::onConnected>(this);
} else { // connected
TRACE("start: flushing");
backend_->setReadyCallback<ProxyConnection, &ProxyConnection::io>(this);
backend_->setMode(x0::Socket::ReadWrite);
}
}
void ProxyConnection::onConnected(x0::Socket* s, int revents)
{
TRACE("onConnected: content? %d", request_->contentAvailable());
TRACE("onConnected.pending:\n%s\n", writeBuffer_.c_str());
if (backend_->state() == x0::Socket::Operational) {
backend_->setReadyCallback<ProxyConnection, &ProxyConnection::io>(this);
if (request_->contentAvailable()) {
TRACE("onConnected: request content available: reading.");
request_->read(std::bind(&ProxyConnection::onRequestChunk, this, std::placeholders::_1));
} else {
TRACE("onConnected: flushing");
backend_->setMode(x0::Socket::ReadWrite); // flush already serialized request
}
} else {
close();
}
}
/** transferres a request body chunk to the origin server. */
void ProxyConnection::onRequestChunk(x0::BufferRef&& chunk)
{
TRACE("onRequestChunk(nb:%ld)", chunk.size());
writeBuffer_.push_back(chunk);
if (backend_->state() == x0::Socket::Operational) {
backend_->setMode(x0::Socket::ReadWrite);
}
}
inline bool validateResponseHeader(const x0::BufferRef& name)
{
// XXX do not allow origin's connection-level response headers to be passed to the client.
if (iequals(name, "Connection"))
return false;
if (iequals(name, "Transfer-Encoding"))
return false;
return true;
}
/** callback, invoked when the origin server has passed us the response status line.
*
* We will use the status code only.
* However, we could pass the text field, too - once x0 core supports it.
*/
void ProxyConnection::messageBegin(int major, int minor, int code, x0::BufferRef&& text)
{
TRACE("ProxyConnection(%p).status(HTTP/%d.%d, %d, '%s')", (void*)this, major, minor, code, text.str().c_str());
request_->status = static_cast<x0::HttpError>(code);
TRACE("status: %d", (int)request_->status);
}
/** callback, invoked on every successfully parsed response header.
*
* We will pass this header directly to the client's response,
* if that is NOT a connection-level header.
*/
void ProxyConnection::messageHeader(x0::BufferRef&& name, x0::BufferRef&& value)
{
TRACE("ProxyConnection(%p).onHeader('%s', '%s')", (void*)this, name.str().c_str(), value.str().c_str());
if (!validateResponseHeader(name))
return;
if (cloak_ && iequals(name, "Server"))
return;
request_->responseHeaders.push_back(name.str(), value.str());
}
/** callback, invoked on a new response content chunk. */
bool ProxyConnection::messageContent(x0::BufferRef&& chunk)
{
TRACE("messageContent(nb:%lu) state:%s", chunk.size(), backend_->state_str());
// stop watching for more input
backend_->setMode(x0::Socket::None);
// transfer response-body chunk to client
request_->write<x0::BufferSource>(std::move(chunk));
// start listening on backend I/O when chunk has been fully transmitted
request_->writeCallback([&]() {
TRACE("chunk write complete: %s", state_str());
backend_->setMode(x0::Socket::Read);
});
return true;
}
bool ProxyConnection::messageEnd()
{
TRACE("messageEnd() state:%s", backend_->state_str());
return true;
}
void ProxyConnection::io(x0::Socket* s, int revents)
{
TRACE("io(0x%04x)", revents);
if (revents & x0::Socket::Read)
readSome();
if (revents & x0::Socket::Write)
writeSome();
}
void ProxyConnection::writeSome()
{
TRACE("writeSome() - %s (%d)", state_str(), request_->contentAvailable());
ssize_t rv = backend_->write(writeBuffer_.data() + writeOffset_, writeBuffer_.size() - writeOffset_);
if (rv > 0) {
TRACE("write request: %ld (of %ld) bytes", rv, writeBuffer_.size() - writeOffset_);
writeOffset_ += rv;
writeProgress_ += rv;
if (writeOffset_ == writeBuffer_.size()) {
TRACE("writeOffset == writeBuffser.size (%ld) p:%ld, ca: %d, clr:%ld", writeOffset_,
writeProgress_, request_->contentAvailable(), request_->connection.contentLength());
writeOffset_ = 0;
writeBuffer_.clear();
if (request_->contentAvailable()) {
TRACE("writeSome: request content available: reading.");
backend_->setMode(x0::Socket::Read);
request_->read(std::bind(&ProxyConnection::onRequestChunk, this, std::placeholders::_1));
} else {
// request fully transmitted, let's read response then.
backend_->setMode(x0::Socket::Read);
TRACE("writeSome: watching for 'read'");
}
}
} else {
TRACE("write request failed(%ld): %s", rv, strerror(errno));
close();
}
}
void ProxyConnection::readSome()
{
TRACE("readSome() - %s", state_str());
std::size_t lower_bound = readBuffer_.size();
if (lower_bound == readBuffer_.capacity())
readBuffer_.setCapacity(lower_bound + 4096);
ssize_t rv = backend_->read(readBuffer_);
if (rv > 0) {
TRACE("read response: %ld bytes", rv);
std::size_t np = 0;
std::error_code ec = process(readBuffer_.ref(lower_bound, rv), np);
TRACE("readSome(): process(): %s", ec.message().c_str());
if (ec == x0::HttpMessageError::Success) {
close();
} else if (ec == x0::HttpMessageError::Partial) {
TRACE("resume with io:%d, state:%s", backend_->mode(), backend_->state_str());
backend_->setMode(x0::Socket::Read);
} else {
close();
}
} else if (rv == 0) {
TRACE("http server connection closed");
close();
} else {
TRACE("read response failed(%ld): %s", rv, strerror(errno));
switch (errno) {
#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
case EWOULDBLOCK:
#endif
case EAGAIN:
case EINTR:
backend_->setMode(x0::Socket::Read);
break;
default:
close();
break;
}
}
}
// }}}
// {{{ plugin class
/**
* \ingroup plugins
* \brief proxy content generator plugin
*/
class proxy_plugin :
public x0::HttpPlugin
{
private:
bool cloak_;
public:
proxy_plugin(x0::HttpServer& srv, const std::string& name) :
x0::HttpPlugin(srv, name),
cloak_(true)
{
registerHandler<proxy_plugin, &proxy_plugin::proxy_reverse>("proxy.reverse");
registerSetupProperty<proxy_plugin, &proxy_plugin::proxy_cloak>("proxy.cloak", x0::FlowValue::BOOLEAN);
}
~proxy_plugin()
{
}
private:
void proxy_cloak(x0::FlowValue& result, const x0::Params& args)
{
if (args.count() && (args[0].isBool() || args[0].isNumber())) {
cloak_ = args[0].toBool();
printf("proxy cloak: %s\n", cloak_ ? "true" : "false");
}
result.set(cloak_);
}
bool proxy_reverse(x0::HttpRequest *in, const x0::Params& args)
{
// TODO: reuse already spawned proxy connections instead of recreating each time.
x0::BufferRef origin = args[0].toString();
x0::Socket* backend = new x0::Socket(in->connection.worker().loop());
if (origin.begins("unix:")) { // UNIX domain socket
backend->openUnix(origin.str());
} else { // TCP/IP
auto pos = origin.rfind(':');
if (pos != origin.npos) {
std::string hostname = origin.substr(0, pos);
int port = origin.ref(pos + 1).toInt();
backend->openTcp(hostname, port);
} else {
// default to port 80 (FIXME not really good?)
backend->openTcp(origin.str(), 80);
}
}
if (backend->isOpen()) {
TRACE("in.content? %d", in->contentAvailable());
if (ProxyConnection* pc = new ProxyConnection()) {
pc->start(in, backend, cloak_);
return true;
}
}
in->status = x0::HttpError::ServiceUnavailable;
in->finish();
return true;
}
};
// }}}
X0_EXPORT_PLUGIN(proxy)
<commit_msg>[plugins] proxy: fixes unix-socket use<commit_after>/* <x0/plugins/proxy.cpp>
*
* This file is part of the x0 web server project and is released under LGPL-3.
* http://www.xzero.ws/
*
* (c) 2009-2010 Christian Parpart <trapni@gentoo.org>
*/
#include <x0/http/HttpPlugin.h>
#include <x0/http/HttpServer.h>
#include <x0/http/HttpRequest.h>
#include <x0/io/BufferSource.h>
#include <x0/strutils.h>
#include <x0/Url.h>
#include <x0/Types.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <fcntl.h>
#include <netdb.h>
/* {{{ -- configuration proposal:
*
* handler setup {
* }
*
* handler main {
* proxy.reverse 'http://127.0.0.1:3000';
* }
*
* --------------------------------------------------------------------------
* possible tweaks:
* - bufsize (0 = unbuffered)
* - timeout.connect
* - timeout.write
* - timeout.read
* - ignore_clientabort
* };
*
*
*/ // }}}
#if 1
# define TRACE(msg...) DEBUG("proxy: " msg)
#else
# define TRACE(msg...) /*!*/
#endif
// {{{ ProxyConnection API
class ProxyConnection :
public x0::HttpMessageProcessor
{
private:
int refCount_;
x0::HttpRequest *request_; //!< client's request
x0::Socket* backend_; //!< connection to backend app
bool cloak_; //!< to cloak or not to cloak the "Server" response header
int connectTimeout_;
int readTimeout_;
int writeTimeout_;
x0::Buffer writeBuffer_;
size_t writeOffset_;
size_t writeProgress_;
x0::Buffer readBuffer_;
private:
void ref();
void unref();
inline void close();
inline void readSome();
inline void writeSome();
void onConnected(x0::Socket* s, int revents);
void io(x0::Socket* s, int revents);
void onRequestChunk(x0::BufferRef&& chunk);
static void onAbort(void *p);
// response (HttpMessageProcessor)
virtual void messageBegin(int version_major, int version_minor, int code, x0::BufferRef&& text);
virtual void messageHeader(x0::BufferRef&& name, x0::BufferRef&& value);
virtual bool messageContent(x0::BufferRef&& chunk);
virtual bool messageEnd();
public:
inline ProxyConnection();
~ProxyConnection();
void start(x0::HttpRequest* in, x0::Socket* backend, bool cloak);
};
// }}}
// {{{ ProxyConnection impl
ProxyConnection::ProxyConnection() :
x0::HttpMessageProcessor(x0::HttpMessageProcessor::RESPONSE),
refCount_(1),
request_(nullptr),
backend_(nullptr),
cloak_(false),
connectTimeout_(0),
readTimeout_(0),
writeTimeout_(0),
writeBuffer_(),
writeOffset_(0),
writeProgress_(0),
readBuffer_()
{
TRACE("ProxyConnection()");
}
ProxyConnection::~ProxyConnection()
{
TRACE("~ProxyConnection()");
if (backend_) {
backend_->close();
delete backend_;
}
if (request_) {
if (request_->status == x0::HttpError::Undefined)
request_->status = x0::HttpError::ServiceUnavailable;
request_->finish();
}
}
void ProxyConnection::ref()
{
++refCount_;
}
void ProxyConnection::unref()
{
assert(refCount_ > 0);
--refCount_;
if (refCount_ == 0) {
delete this;
}
}
void ProxyConnection::close()
{
unref(); // the one from the constructor
}
void ProxyConnection::onAbort(void *p)
{
ProxyConnection *self = reinterpret_cast<ProxyConnection *>(p);
self->close();
}
void ProxyConnection::start(x0::HttpRequest* in, x0::Socket* backend, bool cloak)
{
request_ = in;
request_->setAbortHandler(&ProxyConnection::onAbort, this);
backend_ = backend;
cloak_ = cloak_;
// request line
writeBuffer_.push_back(request_->method);
writeBuffer_.push_back(' ');
writeBuffer_.push_back(request_->uri);
writeBuffer_.push_back(" HTTP/1.1\r\n");
// request headers
for (auto i = request_->requestHeaders.begin(), e = request_->requestHeaders.end(); i != e; ++i) {
if (iequals(i->name, "Content-Transfer")
|| iequals(i->name, "Expect")
|| iequals(i->name, "Connection"))
continue;
TRACE("pass requestHeader(%s: %s)", i->name.str().c_str(), i->value.str().c_str());
writeBuffer_.push_back(i->name);
writeBuffer_.push_back(": ");
writeBuffer_.push_back(i->value);
writeBuffer_.push_back("\r\n");
}
// request headers terminator
writeBuffer_.push_back("\r\n");
if (request_->contentAvailable()) {
TRACE("start: request content available: reading.");
request_->read(std::bind(&ProxyConnection::onRequestChunk, this, std::placeholders::_1));
}
if (backend_->state() == x0::Socket::Connecting) {
TRACE("start: connect in progress");
backend_->setReadyCallback<ProxyConnection, &ProxyConnection::onConnected>(this);
} else { // connected
TRACE("start: flushing");
backend_->setReadyCallback<ProxyConnection, &ProxyConnection::io>(this);
backend_->setMode(x0::Socket::ReadWrite);
}
}
void ProxyConnection::onConnected(x0::Socket* s, int revents)
{
TRACE("onConnected: content? %d", request_->contentAvailable());
TRACE("onConnected.pending:\n%s\n", writeBuffer_.c_str());
if (backend_->state() == x0::Socket::Operational) {
backend_->setReadyCallback<ProxyConnection, &ProxyConnection::io>(this);
if (request_->contentAvailable()) {
TRACE("onConnected: request content available: reading.");
request_->read(std::bind(&ProxyConnection::onRequestChunk, this, std::placeholders::_1));
} else {
TRACE("onConnected: flushing");
backend_->setMode(x0::Socket::ReadWrite); // flush already serialized request
}
} else {
close();
}
}
/** transferres a request body chunk to the origin server. */
void ProxyConnection::onRequestChunk(x0::BufferRef&& chunk)
{
TRACE("onRequestChunk(nb:%ld)", chunk.size());
writeBuffer_.push_back(chunk);
if (backend_->state() == x0::Socket::Operational) {
backend_->setMode(x0::Socket::ReadWrite);
}
}
inline bool validateResponseHeader(const x0::BufferRef& name)
{
// XXX do not allow origin's connection-level response headers to be passed to the client.
if (iequals(name, "Connection"))
return false;
if (iequals(name, "Transfer-Encoding"))
return false;
return true;
}
/** callback, invoked when the origin server has passed us the response status line.
*
* We will use the status code only.
* However, we could pass the text field, too - once x0 core supports it.
*/
void ProxyConnection::messageBegin(int major, int minor, int code, x0::BufferRef&& text)
{
TRACE("ProxyConnection(%p).status(HTTP/%d.%d, %d, '%s')", (void*)this, major, minor, code, text.str().c_str());
request_->status = static_cast<x0::HttpError>(code);
TRACE("status: %d", (int)request_->status);
}
/** callback, invoked on every successfully parsed response header.
*
* We will pass this header directly to the client's response,
* if that is NOT a connection-level header.
*/
void ProxyConnection::messageHeader(x0::BufferRef&& name, x0::BufferRef&& value)
{
TRACE("ProxyConnection(%p).onHeader('%s', '%s')", (void*)this, name.str().c_str(), value.str().c_str());
if (!validateResponseHeader(name))
return;
if (cloak_ && iequals(name, "Server"))
return;
request_->responseHeaders.push_back(name.str(), value.str());
}
/** callback, invoked on a new response content chunk. */
bool ProxyConnection::messageContent(x0::BufferRef&& chunk)
{
TRACE("messageContent(nb:%lu) state:%s", chunk.size(), backend_->state_str());
// stop watching for more input
backend_->setMode(x0::Socket::None);
// transfer response-body chunk to client
request_->write<x0::BufferSource>(std::move(chunk));
// start listening on backend I/O when chunk has been fully transmitted
request_->writeCallback([&]() {
TRACE("chunk write complete: %s", state_str());
backend_->setMode(x0::Socket::Read);
});
return true;
}
bool ProxyConnection::messageEnd()
{
TRACE("messageEnd() state:%s", backend_->state_str());
return true;
}
void ProxyConnection::io(x0::Socket* s, int revents)
{
TRACE("io(0x%04x)", revents);
if (revents & x0::Socket::Read)
readSome();
if (revents & x0::Socket::Write)
writeSome();
}
void ProxyConnection::writeSome()
{
TRACE("writeSome() - %s (%d)", state_str(), request_->contentAvailable());
ssize_t rv = backend_->write(writeBuffer_.data() + writeOffset_, writeBuffer_.size() - writeOffset_);
if (rv > 0) {
TRACE("write request: %ld (of %ld) bytes", rv, writeBuffer_.size() - writeOffset_);
writeOffset_ += rv;
writeProgress_ += rv;
if (writeOffset_ == writeBuffer_.size()) {
TRACE("writeOffset == writeBuffser.size (%ld) p:%ld, ca: %d, clr:%ld", writeOffset_,
writeProgress_, request_->contentAvailable(), request_->connection.contentLength());
writeOffset_ = 0;
writeBuffer_.clear();
if (request_->contentAvailable()) {
TRACE("writeSome: request content available: reading.");
backend_->setMode(x0::Socket::Read);
request_->read(std::bind(&ProxyConnection::onRequestChunk, this, std::placeholders::_1));
} else {
// request fully transmitted, let's read response then.
backend_->setMode(x0::Socket::Read);
TRACE("writeSome: watching for 'read'");
}
}
} else {
TRACE("write request failed(%ld): %s", rv, strerror(errno));
close();
}
}
void ProxyConnection::readSome()
{
TRACE("readSome() - %s", state_str());
std::size_t lower_bound = readBuffer_.size();
if (lower_bound == readBuffer_.capacity())
readBuffer_.setCapacity(lower_bound + 4096);
ssize_t rv = backend_->read(readBuffer_);
if (rv > 0) {
TRACE("read response: %ld bytes", rv);
std::size_t np = 0;
std::error_code ec = process(readBuffer_.ref(lower_bound, rv), np);
TRACE("readSome(): process(): %s", ec.message().c_str());
if (ec == x0::HttpMessageError::Success) {
close();
} else if (ec == x0::HttpMessageError::Partial) {
TRACE("resume with io:%d, state:%s", backend_->mode(), backend_->state_str());
backend_->setMode(x0::Socket::Read);
} else {
close();
}
} else if (rv == 0) {
TRACE("http server connection closed");
close();
} else {
TRACE("read response failed(%ld): %s", rv, strerror(errno));
switch (errno) {
#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
case EWOULDBLOCK:
#endif
case EAGAIN:
case EINTR:
backend_->setMode(x0::Socket::Read);
break;
default:
close();
break;
}
}
}
// }}}
// {{{ plugin class
/**
* \ingroup plugins
* \brief proxy content generator plugin
*/
class proxy_plugin :
public x0::HttpPlugin
{
private:
bool cloak_;
public:
proxy_plugin(x0::HttpServer& srv, const std::string& name) :
x0::HttpPlugin(srv, name),
cloak_(true)
{
registerHandler<proxy_plugin, &proxy_plugin::proxy_reverse>("proxy.reverse");
registerSetupProperty<proxy_plugin, &proxy_plugin::proxy_cloak>("proxy.cloak", x0::FlowValue::BOOLEAN);
}
~proxy_plugin()
{
}
private:
void proxy_cloak(x0::FlowValue& result, const x0::Params& args)
{
if (args.count() && (args[0].isBool() || args[0].isNumber())) {
cloak_ = args[0].toBool();
printf("proxy cloak: %s\n", cloak_ ? "true" : "false");
}
result.set(cloak_);
}
bool proxy_reverse(x0::HttpRequest *in, const x0::Params& args)
{
// TODO: reuse already spawned proxy connections instead of recreating each time.
x0::BufferRef origin = args[0].toString();
x0::Socket* backend = new x0::Socket(in->connection.worker().loop());
if (origin.begins("unix:")) { // UNIX domain socket
backend->openUnix(origin.ref(5).str());
} else { // TCP/IP
auto pos = origin.rfind(':');
if (pos != origin.npos) {
std::string hostname = origin.substr(0, pos);
int port = origin.ref(pos + 1).toInt();
backend->openTcp(hostname, port);
} else {
// default to port 80 (FIXME not really good?)
backend->openTcp(origin.str(), 80);
}
}
if (backend->isOpen()) {
TRACE("in.content? %d", in->contentAvailable());
if (ProxyConnection* pc = new ProxyConnection()) {
pc->start(in, backend, cloak_);
return true;
}
}
in->status = x0::HttpError::ServiceUnavailable;
in->finish();
return true;
}
};
// }}}
X0_EXPORT_PLUGIN(proxy)
<|endoftext|> |
<commit_before>// Copyright 2005-2016 The Mumble Developers. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file at the root of the
// Mumble source tree or at <https://www.mumble.info/LICENSE>.
#include "../mumble_plugin_win32_x86.h"
static int fetch(float *avatar_pos, float *avatar_front, float *avatar_top, float *camera_pos, float *camera_front, float *camera_top, std::string &context, std::wstring &identity) {
for (int i=0;i<3;i++)
avatar_pos[i]=avatar_front[i]=avatar_top[i]=camera_pos[i]=camera_front[i]=camera_top[i]=0.0f;
// Boolean value to check if game addresses retrieval is successful
bool ok;
// Avatar pointers
procptr32_t avatar_base = peekProc<procptr32_t>(pModule + 0x0170B5A4);
if (!avatar_base) return false;
procptr32_t avatar_offset_0 = peekProc<procptr32_t>(avatar_base + 0x448);
if (!avatar_offset_0) return false;
procptr32_t avatar_offset_1 = peekProc<procptr32_t>(avatar_offset_0 + 0x440);
if (!avatar_offset_1) return false;
procptr32_t avatar_offset_2 = peekProc<procptr32_t>(avatar_offset_1 + 0x0);
if (!avatar_offset_2) return false;
procptr32_t avatar_offset = peekProc<procptr32_t>(avatar_offset_2 + 0x1C);
if (!avatar_offset) return false;
// Peekproc and assign game addresses to our containers, so we can retrieve positional data
ok = peekProc(avatar_offset + 0x0, avatar_pos, 12) && // Avatar Position values (X, Y and -Z).
peekProc(pModule + 0x0170B7E0, camera_pos, 12) && // Camera Position values (X, Y and -Z).
peekProc(avatar_offset + 0xC, avatar_front, 12) && // Avatar Front values (X, Y and -Z).
peekProc(pModule + 0x0170B7C8, camera_front, 12) && // Camera Front Vector values (X, Y and -Z).
peekProc(pModule + 0x0170B7D4, camera_top, 12); // Camera Top Vector values (X, Y and -Z).
// This prevents the plugin from linking to the game in case something goes wrong during values retrieval from memory addresses.
if (! ok)
return false;
avatar_top[2] = -1; // This tells Mumble to automatically calculate top vector using front vector.
// Scale from centimeters to meters
for (int i=0;i<3;i++) {
avatar_pos[i]/=100.0f;
camera_pos[i]/=100.0f;
}
return true;
}
static int trylock(const std::multimap<std::wstring, unsigned long long int> &pids) {
if (! initialize(pids, L"RocketLeague.exe")) // Link the game executable
return false;
// Check if we can get meaningful data from it
float apos[3], afront[3], atop[3], cpos[3], cfront[3], ctop[3];
std::wstring sidentity;
std::string scontext;
if (fetch(apos, afront, atop, cpos, cfront, ctop, scontext, sidentity)) {
return true;
} else {
generic_unlock();
return false;
}
}
static const std::wstring longdesc() {
return std::wstring(L"Supports Rocket League version 1.19 without context or identity support yet."); // Plugin long description
}
static std::wstring description(L"Rocket League (v1.19)"); // Plugin short description
static std::wstring shortname(L"Rocket League"); // Plugin short name
static int trylock1() {
return trylock(std::multimap<std::wstring, unsigned long long int>());
}
static MumblePlugin rlplug = {
MUMBLE_PLUGIN_MAGIC,
description,
shortname,
NULL,
NULL,
trylock1,
generic_unlock,
longdesc,
fetch
};
static MumblePlugin2 rlplug2 = {
MUMBLE_PLUGIN_MAGIC_2,
MUMBLE_PLUGIN_VERSION,
trylock
};
extern "C" __declspec(dllexport) MumblePlugin *getMumblePlugin() {
return &rlplug;
}
extern "C" __declspec(dllexport) MumblePlugin2 *getMumblePlugin2() {
return &rlplug2;
}
<commit_msg>plugins/rl: Plugin update for game's latest version<commit_after>// Copyright 2005-2016 The Mumble Developers. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file at the root of the
// Mumble source tree or at <https://www.mumble.info/LICENSE>.
#include "../mumble_plugin_win32_x86.h"
static int fetch(float *avatar_pos, float *avatar_front, float *avatar_top, float *camera_pos, float *camera_front, float *camera_top, std::string &context, std::wstring &identity) {
for (int i=0;i<3;i++)
avatar_pos[i]=avatar_front[i]=avatar_top[i]=camera_pos[i]=camera_front[i]=camera_top[i]=0.0f;
// Boolean value to check if game addresses retrieval is successful
bool ok;
// Avatar pointers
procptr32_t avatar_base = peekProc<procptr32_t>(pModule + 0x017085A4);
if (!avatar_base) return false;
procptr32_t avatar_offset_0 = peekProc<procptr32_t>(avatar_base + 0x448);
if (!avatar_offset_0) return false;
procptr32_t avatar_offset_1 = peekProc<procptr32_t>(avatar_offset_0 + 0x440);
if (!avatar_offset_1) return false;
procptr32_t avatar_offset_2 = peekProc<procptr32_t>(avatar_offset_1 + 0x0);
if (!avatar_offset_2) return false;
procptr32_t avatar_offset = peekProc<procptr32_t>(avatar_offset_2 + 0x1C);
if (!avatar_offset) return false;
// Peekproc and assign game addresses to our containers, so we can retrieve positional data
ok = peekProc(avatar_offset + 0x0, avatar_pos, 12) && // Avatar Position values (X, Y and -Z).
peekProc(pModule + 0x017087E0, camera_pos, 12) && // Camera Position values (X, Y and -Z).
peekProc(avatar_offset + 0xC, avatar_front, 12) && // Avatar Front values (X, Y and -Z).
peekProc(pModule + 0x017087C8, camera_front, 12) && // Camera Front Vector values (X, Y and -Z).
peekProc(pModule + 0x017087D4, camera_top, 12); // Camera Top Vector values (X, Y and -Z).
// This prevents the plugin from linking to the game in case something goes wrong during values retrieval from memory addresses.
if (! ok)
return false;
avatar_top[2] = -1; // This tells Mumble to automatically calculate top vector using front vector.
// Scale from centimeters to meters
for (int i=0;i<3;i++) {
avatar_pos[i]/=100.0f;
camera_pos[i]/=100.0f;
}
return true;
}
static int trylock(const std::multimap<std::wstring, unsigned long long int> &pids) {
if (! initialize(pids, L"RocketLeague.exe")) // Link the game executable
return false;
// Check if we can get meaningful data from it
float apos[3], afront[3], atop[3], cpos[3], cfront[3], ctop[3];
std::wstring sidentity;
std::string scontext;
if (fetch(apos, afront, atop, cpos, cfront, ctop, scontext, sidentity)) {
return true;
} else {
generic_unlock();
return false;
}
}
static const std::wstring longdesc() {
return std::wstring(L"Supports Rocket League version 1.20 without context or identity support yet."); // Plugin long description
}
static std::wstring description(L"Rocket League (v1.20)"); // Plugin short description
static std::wstring shortname(L"Rocket League"); // Plugin short name
static int trylock1() {
return trylock(std::multimap<std::wstring, unsigned long long int>());
}
static MumblePlugin rlplug = {
MUMBLE_PLUGIN_MAGIC,
description,
shortname,
NULL,
NULL,
trylock1,
generic_unlock,
longdesc,
fetch
};
static MumblePlugin2 rlplug2 = {
MUMBLE_PLUGIN_MAGIC_2,
MUMBLE_PLUGIN_VERSION,
trylock
};
extern "C" __declspec(dllexport) MumblePlugin *getMumblePlugin() {
return &rlplug;
}
extern "C" __declspec(dllexport) MumblePlugin2 *getMumblePlugin2() {
return &rlplug2;
}
<|endoftext|> |
<commit_before>/* <x0/plugins/vhost.cpp>
*
* This file is part of the x0 web server project and is released under LGPL-3.
* http://www.xzero.ws/
*
* (c) 2011 Christian Parpart <trapni@gentoo.org>
*
* --------------------------------------------------------------------------
*
* plugin type: hostname resolver
*
* description:
* Maps the request hostname:port to a dedicated handler.
*
* setup API:
* void vhost.mapping(FQDN => handler_ref, ...);
*
* request processing API:
* handler vhost.map();
*/
#include <x0/http/HttpPlugin.h>
#include <x0/http/HttpServer.h>
#include <x0/http/HttpRequest.h>
#include <x0/http/HttpHeader.h>
#include <x0/Types.h>
#include <unordered_map>
/**
* \ingroup plugins
* \brief virtual host mapping plugin
*/
class vhost_plugin :
public x0::HttpPlugin
{
private:
typedef std::map<std::string, x0::FlowValue::Function> NamedHostMap;
NamedHostMap qualifiedHosts_;
NamedHostMap unqualifiedHosts_;
public:
vhost_plugin(x0::HttpServer& srv, const std::string& name) :
x0::HttpPlugin(srv, name)
{
registerSetupFunction<vhost_plugin, &vhost_plugin::addHost>("vhost.mapping", x0::FlowValue::VOID);
registerHandler<vhost_plugin, &vhost_plugin::mapRequest>("vhost.map");
}
~vhost_plugin()
{
}
private:
// vhost.add fqdn => proc, ...
void addHost(x0::FlowValue& result, const x0::Params& args)
{
for (auto& arg: args)
registerHost(arg);
}
void registerHost(const x0::FlowValue& arg)
{
if (arg.type() == x0::FlowValue::ARRAY) {
const x0::FlowArray* args = arg.toArray();
if (args->size() != 2)
return;
const x0::FlowValue& fqdn = args[0];
const x0::FlowValue& proc = args[1];
if (!fqdn.isString())
return;
if (!proc.isFunction())
return;
registerHost(fqdn.toString(), proc.toFunction());
}
}
void registerHost(const char *fqdn, x0::FlowValue::Function handler)
{
if (strchr(fqdn, ':'))
qualifiedHosts_[fqdn] = handler;
else
unqualifiedHosts_[fqdn] = handler;
}
bool mapRequest(x0::HttpRequest *r, const x0::Params& args)
{
auto i = qualifiedHosts_.find(r->hostid());
if (i != qualifiedHosts_.end())
return i->second(r);
auto k = unqualifiedHosts_.find(r->hostname.str());
if (k != unqualifiedHosts_.end())
return k->second(r);
return false;
}
};
X0_EXPORT_PLUGIN(vhost)
<commit_msg>[plugins] vhost: fixes adaptions to flow api changes<commit_after>/* <x0/plugins/vhost.cpp>
*
* This file is part of the x0 web server project and is released under LGPL-3.
* http://www.xzero.ws/
*
* (c) 2011 Christian Parpart <trapni@gentoo.org>
*
* --------------------------------------------------------------------------
*
* plugin type: hostname resolver
*
* description:
* Maps the request hostname:port to a dedicated handler.
*
* setup API:
* void vhost.mapping(FQDN => handler_ref, ...);
*
* request processing API:
* handler vhost.map();
*/
#include <x0/http/HttpPlugin.h>
#include <x0/http/HttpServer.h>
#include <x0/http/HttpRequest.h>
#include <x0/http/HttpHeader.h>
#include <x0/Types.h>
#include <unordered_map>
/**
* \ingroup plugins
* \brief virtual host mapping plugin
*/
class vhost_plugin :
public x0::HttpPlugin
{
private:
typedef std::map<std::string, x0::FlowValue::Function> NamedHostMap;
NamedHostMap qualifiedHosts_;
NamedHostMap unqualifiedHosts_;
public:
vhost_plugin(x0::HttpServer& srv, const std::string& name) :
x0::HttpPlugin(srv, name)
{
registerSetupFunction<vhost_plugin, &vhost_plugin::addHost>("vhost.mapping", x0::FlowValue::VOID);
registerHandler<vhost_plugin, &vhost_plugin::mapRequest>("vhost.map");
}
~vhost_plugin()
{
}
private:
// vhost.add fqdn => proc, ...
void addHost(x0::FlowValue& result, const x0::Params& args)
{
for (auto& arg: args)
registerHost(arg);
}
void registerHost(const x0::FlowValue& arg)
{
if (arg.type() == x0::FlowValue::ARRAY) {
const x0::FlowArray& args = *arg.toArray();
if (args.size() != 2)
return;
const x0::FlowValue& fqdn = args[0];
const x0::FlowValue& proc = args[1];
if (!fqdn.isString())
return;
if (!proc.isFunction())
return;
registerHost(fqdn.toString(), proc.toFunction());
}
}
void registerHost(const char *fqdn, x0::FlowValue::Function handler)
{
if (strchr(fqdn, ':'))
qualifiedHosts_[fqdn] = handler;
else
unqualifiedHosts_[fqdn] = handler;
}
bool mapRequest(x0::HttpRequest *r, const x0::Params& args)
{
auto i = qualifiedHosts_.find(r->hostid());
if (i != qualifiedHosts_.end())
return i->second(r);
auto k = unqualifiedHosts_.find(r->hostname.str());
if (k != unqualifiedHosts_.end())
return k->second(r);
return false;
}
};
X0_EXPORT_PLUGIN(vhost)
<|endoftext|> |
<commit_before>/**
* \file RMF/paths.cpp
* \brief Handle read/write of Model data from/to files.
*
* Copyright 2007-2012 IMP Inventors. All rights reserved.
*
*/
#include "avro_schemas.h"
#include "MultipleAvroFileWriter.h"
#include <RMF/internal/paths.h>
#include <RMF/decorators.h>
#include <avro/Compiler.hh>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <cstdio>
#include <stdexcept>
namespace RMF {
namespace internal {
void MultipleAvroFileWriter::set_current_frame(int frame) {
if (frame == get_current_frame()) return;
RMF_USAGE_CHECK(frame == ALL_FRAMES
|| frame == get_frames().size()-2,
"Bad frame set");
MultipleAvroFileBase::set_current_frame(frame);
}
MultipleAvroFileWriter::MultipleAvroFileWriter(std::string path,
bool create, bool read_only):
MultipleAvroFileBase(path){
RMF_INTERNAL_CHECK(create, "Can only create files");
RMF_INTERNAL_CHECK(!read_only, "Can only create files");
boost::filesystem::remove_all(path);
boost::filesystem::create_directory(path);
file_.version=1;
file_dirty_=true;
frames_dirty_=true;
nodes_dirty_=true;
}
MultipleAvroFileWriter::~MultipleAvroFileWriter() {
commit();
}
#if BOOST_VERSION < 104400
// boost::rename is broken
#define RMF_COMMIT(UCName, lcname) \
if (lcname##_dirty_) { \
std::string path=get_##lcname##_file_path().c_str(); \
std::string temppath=path+".new"; \
avro::DataFileWriter<UCName> \
wr(temppath.c_str(), get_##UCName##_schema()); \
wr.write(lcname##_); \
wr.flush(); \
std::rename(temppath.c_str(), path.c_str()); \
}
#else
#define RMF_COMMIT(UCName, lcname) \
if (lcname##_dirty_) { \
std::string path=get_##lcname##_file_path().c_str(); \
std::string temppath=path+".new"; \
avro::DataFileWriter<UCName> \
wr(temppath.c_str(), get_##UCName##_schema()); \
wr.write(lcname##_); \
wr.flush(); \
boost::filesystem::rename(temppath, path); \
}
#endif
void MultipleAvroFileWriter::commit() {
for (unsigned int i=0; i< categories_.size(); ++i) {
if (categories_[i].dirty) {
if (!categories_[i].writer) {
std::string name= get_category_dynamic_file_path(Category(i));
categories_[i].writer
.reset(new avro::DataFileWriter<RMF_internal::Data>(name.c_str(),
get_Data_schema()));
}
/*std::cout << "Writing data for " << get_category_name(Category(i))
<< " at frame " << categories_[i].data.frame << std::endl;*/
//show(categories_[i].data);
RMF_INTERNAL_CHECK(categories_[i].data.frame==get_frames().size()-2,
"Trying to write category that is at wrong frame.");
categories_[i].writer->write(categories_[i].data);
categories_[i].writer->flush();
categories_[i].data=RMF_internal::Data();
// go to next frame
categories_[i].data.frame=get_frames().size()-1;
}
}
for (unsigned int i=0; i< static_categories_.size(); ++i) {
if (static_categories_dirty_[i]) {
std::string name= get_category_static_file_path(Category(i));
avro::DataFileWriter<RMF_internal::Data> writer(name.c_str(),
get_Data_schema());
writer.write(static_categories_[i]);
writer.flush();
//std::cout << "Writing data for " << get_category_name(Category(i)) << std::endl;
//show(static_categories_[i]);
static_categories_dirty_[i]=false;
}
}
RMF_COMMIT(File, file);
RMF_COMMIT(Nodes, nodes);
RMF_COMMIT(Nodes, frames);
}
} // namespace internal
} /* namespace RMF */
<commit_msg>make sure to set frame index on all frames, not just written ones<commit_after>/**
* \file RMF/paths.cpp
* \brief Handle read/write of Model data from/to files.
*
* Copyright 2007-2012 IMP Inventors. All rights reserved.
*
*/
#include "avro_schemas.h"
#include "MultipleAvroFileWriter.h"
#include <RMF/internal/paths.h>
#include <RMF/decorators.h>
#include <avro/Compiler.hh>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <cstdio>
#include <stdexcept>
namespace RMF {
namespace internal {
void MultipleAvroFileWriter::set_current_frame(int frame) {
if (frame == get_current_frame()) return;
RMF_USAGE_CHECK(frame == ALL_FRAMES
|| frame == get_frames().size()-2,
"Bad frame set");
MultipleAvroFileBase::set_current_frame(frame);
}
MultipleAvroFileWriter::MultipleAvroFileWriter(std::string path,
bool create, bool read_only):
MultipleAvroFileBase(path){
RMF_INTERNAL_CHECK(create, "Can only create files");
RMF_INTERNAL_CHECK(!read_only, "Can only create files");
boost::filesystem::remove_all(path);
boost::filesystem::create_directory(path);
file_.version=1;
file_dirty_=true;
frames_dirty_=true;
nodes_dirty_=true;
}
MultipleAvroFileWriter::~MultipleAvroFileWriter() {
commit();
}
#if BOOST_VERSION < 104400
// boost::rename is broken
#define RMF_COMMIT(UCName, lcname) \
if (lcname##_dirty_) { \
std::string path=get_##lcname##_file_path().c_str(); \
std::string temppath=path+".new"; \
avro::DataFileWriter<UCName> \
wr(temppath.c_str(), get_##UCName##_schema()); \
wr.write(lcname##_); \
wr.flush(); \
std::rename(temppath.c_str(), path.c_str()); \
}
#else
#define RMF_COMMIT(UCName, lcname) \
if (lcname##_dirty_) { \
std::string path=get_##lcname##_file_path().c_str(); \
std::string temppath=path+".new"; \
avro::DataFileWriter<UCName> \
wr(temppath.c_str(), get_##UCName##_schema()); \
wr.write(lcname##_); \
wr.flush(); \
boost::filesystem::rename(temppath, path); \
}
#endif
void MultipleAvroFileWriter::commit() {
for (unsigned int i=0; i< categories_.size(); ++i) {
if (categories_[i].dirty) {
if (!categories_[i].writer) {
std::string name= get_category_dynamic_file_path(Category(i));
categories_[i].writer
.reset(new avro::DataFileWriter<RMF_internal::Data>(name.c_str(),
get_Data_schema()));
}
/*std::cout << "Writing data for " << get_category_name(Category(i))
<< " at frame " << categories_[i].data.frame << std::endl;*/
//show(categories_[i].data);
RMF_INTERNAL_CHECK(categories_[i].data.frame==get_frames().size()-2,
"Trying to write category that is at wrong frame.");
categories_[i].writer->write(categories_[i].data);
categories_[i].writer->flush();
}
categories_[i].data=RMF_internal::Data();
// go to the about to be added frame
categories_[i].data.frame=get_frames().size()-1;
}
for (unsigned int i=0; i< static_categories_.size(); ++i) {
if (static_categories_dirty_[i]) {
std::string name= get_category_static_file_path(Category(i));
avro::DataFileWriter<RMF_internal::Data> writer(name.c_str(),
get_Data_schema());
writer.write(static_categories_[i]);
writer.flush();
//std::cout << "Writing data for " << get_category_name(Category(i)) << std::endl;
//show(static_categories_[i]);
static_categories_dirty_[i]=false;
}
}
RMF_COMMIT(File, file);
RMF_COMMIT(Nodes, nodes);
RMF_COMMIT(Nodes, frames);
}
} // namespace internal
} /* namespace RMF */
<|endoftext|> |
<commit_before>
#include "backend/bridge/dml/expr/pg_func_map.h"
namespace peloton {
namespace bridge {
/**
* @brief Mapping PG Function Id to Peloton Function Meta Info.
*/
std::unordered_map<Oid, const PltFuncMetaInfo> kPgFuncMap({
//====--------------------------------
// Relational comparison
//====--------------------------------
{63, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{65, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{67, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{158, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{159, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{287, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{293, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{84, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{144, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{145, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{157, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{164, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{165, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{288, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{294, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{56, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{64, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{66, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{160, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{161, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{1246, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{289, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{295, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{57, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{73, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{146, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{147, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{162, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{163, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{291, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{297, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{74, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{150, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{151, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{168, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{169, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{1692, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{292, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{298, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{72, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{148, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{149, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{166, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{167, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{1691, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{290, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{296, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
//====--------------------------------
// Basic arithmetics
//====--------------------------------
{176, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{177, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{178, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{179, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{204, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{218, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{180, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{181, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{182, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{183, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{205, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{219, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{141, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{152, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{170, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{171, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{202, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{216, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{153, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{154, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{172, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{173, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{203, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{217, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
//====--------------------------------
// Cast
//====--------------------------------
{480, { EXPRESSION_TYPE_CAST, 1 } }, // int8 -> int4
{481, { EXPRESSION_TYPE_CAST, 1 } }, // int4 -> int8
{668, { EXPRESSION_TYPE_CAST, 3 } }, // bpchar -> bpchar
{669, { EXPRESSION_TYPE_CAST, 3 } }, // varchar -> varchar
{1703, { EXPRESSION_TYPE_CAST, 2 } }, // numeric -> numeric
{1740, { EXPRESSION_TYPE_CAST, 3 } }, // int8 -> numeric
{1742, { EXPRESSION_TYPE_CAST, 3 } }, // float4 -> numeric
{1743, { EXPRESSION_TYPE_CAST, 3 } }, // float8 -> numeric
{1744, { EXPRESSION_TYPE_CAST, 1 } }, // numeric -> int4
{1745, { EXPRESSION_TYPE_CAST, 1 } }, // numeric -> float4
{1746, { EXPRESSION_TYPE_CAST, 1 } }, // numeric -> float8
{1781, { EXPRESSION_TYPE_CAST, 1 } }, // int8 -> numeric
{1782, { EXPRESSION_TYPE_CAST, 1 } }, // int2 -> numeric
});
/**
* @brief Mapping PG transit function to Aggregate types.
* We have to separate it from kPgFuncMap,
* because the two maps may have overlapping functions that have
* different meaning in Peloton.
* For example, PG Function Id 218 (float8pl) means an PLUS in
* 'ordinary' expressions,
* but means a SUM(float) in an aggregation.
*/
std::unordered_map<Oid, const PltFuncMetaInfo> kPgTransitFuncMap({
//====--------------------------------
// "Transit function" of Aggregates
//====--------------------------------
{ 768, { EXPRESSION_TYPE_AGGREGATE_MAX, 1} },
{ 770, { EXPRESSION_TYPE_AGGREGATE_MAX, 1} },
{ 223, { EXPRESSION_TYPE_AGGREGATE_MAX, 1} },
{ 769, { EXPRESSION_TYPE_AGGREGATE_MIN, 1} },
{ 771, { EXPRESSION_TYPE_AGGREGATE_MIN, 1} },
{ 224, { EXPRESSION_TYPE_AGGREGATE_MIN, 1} },
{ 1840, { EXPRESSION_TYPE_AGGREGATE_SUM, 1} },
{ 1841, { EXPRESSION_TYPE_AGGREGATE_SUM, 1} },
{ 1842, { EXPRESSION_TYPE_AGGREGATE_SUM, 1} },
{ 218, { EXPRESSION_TYPE_AGGREGATE_SUM, 1} },
{ 222, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1834, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1835, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1836, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1833, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1962, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1963, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{1219, {EXPRESSION_TYPE_AGGREGATE_COUNT, 1} },
{2804, {EXPRESSION_TYPE_AGGREGATE_COUNT, 1} }
});
}
}
<commit_msg>add support for decimal comparison in mapping op expr<commit_after>
#include "backend/bridge/dml/expr/pg_func_map.h"
namespace peloton {
namespace bridge {
/**
* @brief Mapping PG Function Id to Peloton Function Meta Info.
*/
std::unordered_map<Oid, const PltFuncMetaInfo> kPgFuncMap({
//====--------------------------------
// Relational comparison
//====--------------------------------
{63, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{65, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{67, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{158, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{159, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{287, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{293, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{1718, { EXPRESSION_TYPE_COMPARE_EQ, 2 } },
{84, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{144, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{145, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{157, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{164, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{165, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{288, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{294, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{1719, { EXPRESSION_TYPE_COMPARE_NE, 2 } },
{56, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{64, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{66, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{160, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{161, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{1246, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{289, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{295, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{1722, { EXPRESSION_TYPE_COMPARE_LT, 2 } },
{57, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{73, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{146, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{147, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{162, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{163, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{291, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{297, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{1720, { EXPRESSION_TYPE_COMPARE_GT, 2 } },
{74, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{150, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{151, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{168, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{169, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{1692, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{292, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{298, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{1721, { EXPRESSION_TYPE_COMPARE_GTE, 2 } },
{72, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{148, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{149, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{166, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{167, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{1691, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{290, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{296, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
{1723, { EXPRESSION_TYPE_COMPARE_LTE, 2 } },
//====--------------------------------
// Basic arithmetics
//====--------------------------------
{176, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{177, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{178, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{179, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{204, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{218, { EXPRESSION_TYPE_OPERATOR_PLUS, 2 } },
{180, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{181, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{182, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{183, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{205, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{219, { EXPRESSION_TYPE_OPERATOR_MINUS, 2 } },
{141, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{152, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{170, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{171, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{202, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{216, { EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2 } },
{153, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{154, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{172, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{173, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{203, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
{217, { EXPRESSION_TYPE_OPERATOR_DIVIDE, 2 } },
//====--------------------------------
// Cast
//====--------------------------------
{480, { EXPRESSION_TYPE_CAST, 1 } }, // int8 -> int4
{481, { EXPRESSION_TYPE_CAST, 1 } }, // int4 -> int8
{668, { EXPRESSION_TYPE_CAST, 3 } }, // bpchar -> bpchar
{669, { EXPRESSION_TYPE_CAST, 3 } }, // varchar -> varchar
{1703, { EXPRESSION_TYPE_CAST, 2 } }, // numeric -> numeric
{1740, { EXPRESSION_TYPE_CAST, 3 } }, // int8 -> numeric
{1742, { EXPRESSION_TYPE_CAST, 3 } }, // float4 -> numeric
{1743, { EXPRESSION_TYPE_CAST, 3 } }, // float8 -> numeric
{1744, { EXPRESSION_TYPE_CAST, 1 } }, // numeric -> int4
{1745, { EXPRESSION_TYPE_CAST, 1 } }, // numeric -> float4
{1746, { EXPRESSION_TYPE_CAST, 1 } }, // numeric -> float8
{1781, { EXPRESSION_TYPE_CAST, 1 } }, // int8 -> numeric
{1782, { EXPRESSION_TYPE_CAST, 1 } }, // int2 -> numeric
});
/**
* @brief Mapping PG transit function to Aggregate types.
* We have to separate it from kPgFuncMap,
* because the two maps may have overlapping functions that have
* different meaning in Peloton.
* For example, PG Function Id 218 (float8pl) means an PLUS in
* 'ordinary' expressions,
* but means a SUM(float) in an aggregation.
*/
std::unordered_map<Oid, const PltFuncMetaInfo> kPgTransitFuncMap({
//====--------------------------------
// "Transit function" of Aggregates
//====--------------------------------
{ 768, { EXPRESSION_TYPE_AGGREGATE_MAX, 1} },
{ 770, { EXPRESSION_TYPE_AGGREGATE_MAX, 1} },
{ 223, { EXPRESSION_TYPE_AGGREGATE_MAX, 1} },
{ 769, { EXPRESSION_TYPE_AGGREGATE_MIN, 1} },
{ 771, { EXPRESSION_TYPE_AGGREGATE_MIN, 1} },
{ 224, { EXPRESSION_TYPE_AGGREGATE_MIN, 1} },
{ 1840, { EXPRESSION_TYPE_AGGREGATE_SUM, 1} },
{ 1841, { EXPRESSION_TYPE_AGGREGATE_SUM, 1} },
{ 1842, { EXPRESSION_TYPE_AGGREGATE_SUM, 1} },
{ 218, { EXPRESSION_TYPE_AGGREGATE_SUM, 1} },
{ 222, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1834, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1835, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1836, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1833, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1962, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{ 1963, {EXPRESSION_TYPE_AGGREGATE_AVG, 1} },
{1219, {EXPRESSION_TYPE_AGGREGATE_COUNT, 1} },
{2804, {EXPRESSION_TYPE_AGGREGATE_COUNT, 1} }
});
}
}
<|endoftext|> |
<commit_before>#include <widget/OpenGlWidget.hpp>
#include <app.hpp>
namespace rack {
namespace widget {
void OpenGlWidget::step() {
// Render every frame
dirty = true;
}
void OpenGlWidget::drawFramebuffer() {
glViewport(0.0, 0.0, fbSize.x, fbSize.y);
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, fbSize.x, 0.0, fbSize.y, -1.0, 1.0);
glBegin(GL_TRIANGLES);
glColor3f(1, 0, 0);
glVertex3f(0, 0, 0);
glColor3f(0, 1, 0);
glVertex3f(fbSize.x, 0, 0);
glColor3f(0, 0, 1);
glVertex3f(0, fbSize.y, 0);
glEnd();
}
} // namespace widget
} // namespace rack
<commit_msg>Fix OpenGlWidget by calling superclass step().<commit_after>#include <widget/OpenGlWidget.hpp>
#include <app.hpp>
namespace rack {
namespace widget {
void OpenGlWidget::step() {
// Render every frame
dirty = true;
FramebufferWidget::step();
}
void OpenGlWidget::drawFramebuffer() {
glViewport(0.0, 0.0, fbSize.x, fbSize.y);
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, fbSize.x, 0.0, fbSize.y, -1.0, 1.0);
glBegin(GL_TRIANGLES);
glColor3f(1, 0, 0);
glVertex3f(0, 0, 0);
glColor3f(0, 1, 0);
glVertex3f(fbSize.x, 0, 0);
glColor3f(0, 0, 1);
glVertex3f(0, fbSize.y, 0);
glEnd();
}
} // namespace widget
} // namespace rack
<|endoftext|> |
<commit_before>//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//
// File: ObjectNative.cpp
//
//
// Purpose: Native methods on System.Object
//
//
#include "common.h"
#include "objectnative.h"
#include "excep.h"
#include "vars.hpp"
#include "field.h"
#include "object.h"
#include "comsynchronizable.h"
#ifdef FEATURE_REMOTING
#include "remoting.h"
#endif
#include "eeconfig.h"
#ifdef FEATURE_REMOTING
#include "objectclone.h"
#endif
#include "mdaassistants.h"
/********************************************************************/
/* gets an object's 'value'. For normal classes, with reference
based semantics, this means the object's pointer. For boxed
primitive types, it also means just returning the pointer (because
they are immutable), for other value class, it means returning
a boxed copy. */
FCIMPL1(Object*, ObjectNative::GetObjectValue, Object* obj)
{
CONTRACTL
{
FCALL_CHECK;
INJECT_FAULT(FCThrow(kOutOfMemoryException););
}
CONTRACTL_END;
VALIDATEOBJECT(obj);
if (obj == 0)
return(obj);
MethodTable* pMT = obj->GetMethodTable();
// optimize for primitive types since GetVerifierCorElementType is slow.
if (pMT->IsTruePrimitive() || TypeHandle(pMT).GetVerifierCorElementType() != ELEMENT_TYPE_VALUETYPE) {
return(obj);
}
Object* retVal = NULL;
OBJECTREF objRef(obj);
HELPER_METHOD_FRAME_BEGIN_RET_1(objRef); // Set up a frame
// Technically we could return boxed DateTimes and Decimals without
// copying them here, but VB realized that this would be a breaking change
// for their customers. So copy them.
//
// MethodTable::Box is a cleaner way to copy value class, but it is slower than following code.
//
retVal = OBJECTREFToObject(AllocateObject(pMT));
CopyValueClass(retVal->GetData(), objRef->GetData(), pMT, retVal->GetAppDomain());
HELPER_METHOD_FRAME_END();
return(retVal);
}
FCIMPLEND
NOINLINE static INT32 GetHashCodeHelper(OBJECTREF objRef)
{
DWORD idx = 0;
FC_INNER_PROLOG(ObjectNative::GetHashCode);
HELPER_METHOD_FRAME_BEGIN_RET_ATTRIB_1(Frame::FRAME_ATTR_EXACT_DEPTH|Frame::FRAME_ATTR_CAPTURE_DEPTH_2, objRef);
#ifdef MDA_SUPPORTED
MdaModuloObjectHashcode* pProbe = MDA_GET_ASSISTANT(ModuloObjectHashcode);
#endif
idx = objRef->GetHashCodeEx();
#ifdef MDA_SUPPORTED
if (pProbe)
idx = idx % pProbe->GetModulo();
#endif
HELPER_METHOD_FRAME_END();
FC_INNER_EPILOG();
return idx;
}
// Note that we obtain a sync block index without actually building a sync block.
// That's because a lot of objects are hashed, without requiring support for
FCIMPL1(INT32, ObjectNative::GetHashCode, Object* obj) {
CONTRACTL
{
FCALL_CHECK;
INJECT_FAULT(FCThrow(kOutOfMemoryException););
}
CONTRACTL_END;
VALIDATEOBJECT(obj);
if (obj == 0)
return 0;
OBJECTREF objRef(obj);
#ifdef MDA_SUPPORTED
if (!MDA_GET_ASSISTANT(ModuloObjectHashcode))
#endif
{
DWORD bits = objRef->GetHeader()->GetBits();
if (bits & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX)
{
if (bits & BIT_SBLK_IS_HASHCODE)
{
// Common case: the object already has a hash code
return bits & MASK_HASHCODE;
}
else
{
// We have a sync block index. This means if we already have a hash code,
// it is in the sync block, otherwise we generate a new one and store it there
SyncBlock *psb = objRef->PassiveGetSyncBlock();
if (psb != NULL)
{
DWORD hashCode = psb->GetHashCode();
if (hashCode != 0)
return hashCode;
}
}
}
}
FC_INNER_RETURN(INT32, GetHashCodeHelper(objRef));
}
FCIMPLEND
//
// Compare by ref for normal classes, by value for value types.
//
// <TODO>@todo: it would be nice to customize this method based on the
// defining class rather than doing a runtime check whether it is
// a value type.</TODO>
//
FCIMPL2(FC_BOOL_RET, ObjectNative::Equals, Object *pThisRef, Object *pCompareRef)
{
CONTRACTL
{
FCALL_CHECK;
INJECT_FAULT(FCThrow(kOutOfMemoryException););
}
CONTRACTL_END;
if (pThisRef == pCompareRef)
FC_RETURN_BOOL(TRUE);
// Since we are in FCALL, we must handle NULL specially.
if (pThisRef == NULL || pCompareRef == NULL)
FC_RETURN_BOOL(FALSE);
MethodTable *pThisMT = pThisRef->GetMethodTable();
// If it's not a value class, don't compare by value
if (!pThisMT->IsValueType())
FC_RETURN_BOOL(FALSE);
// Make sure they are the same type.
if (pThisMT != pCompareRef->GetMethodTable())
FC_RETURN_BOOL(FALSE);
// Compare the contents (size - vtable - sink block index).
DWORD dwBaseSize = pThisRef->GetMethodTable()->GetBaseSize();
if(pThisRef->GetMethodTable() == g_pStringClass)
dwBaseSize -= sizeof(WCHAR);
BOOL ret = memcmp(
(void *) (pThisRef+1),
(void *) (pCompareRef+1),
dwBaseSize - sizeof(Object) - sizeof(int)) == 0;
FC_GC_POLL_RET();
FC_RETURN_BOOL(ret);
}
FCIMPLEND
NOINLINE static Object* GetClassHelper(OBJECTREF objRef)
{
FC_INNER_PROLOG(ObjectNative::GetClass);
_ASSERTE(objRef != NULL);
TypeHandle typeHandle = objRef->GetTypeHandle();
OBJECTREF refType = NULL;
// Arrays go down this slow path, at least don't do the full HelperMethodFrame setup
// if we are fetching the cached entry.
refType = typeHandle.GetManagedClassObjectFast();
if (refType != NULL)
return OBJECTREFToObject(refType);
HELPER_METHOD_FRAME_BEGIN_RET_ATTRIB_1(Frame::FRAME_ATTR_EXACT_DEPTH|Frame::FRAME_ATTR_CAPTURE_DEPTH_2, refType);
#ifdef FEATURE_REMOTING
if (objRef->IsTransparentProxy())
refType = CRemotingServices::GetClass(objRef);
else
#endif
refType = typeHandle.GetManagedClassObject();
HELPER_METHOD_FRAME_END();
FC_INNER_EPILOG();
return OBJECTREFToObject(refType);
}
// This routine is called by the Object.GetType() routine. It is a major way to get the Sytem.Type
FCIMPL1(Object*, ObjectNative::GetClass, Object* pThis)
{
CONTRACTL
{
FCALL_CHECK;
INJECT_FAULT(FCThrow(kOutOfMemoryException););
}
CONTRACTL_END;
OBJECTREF objRef = ObjectToOBJECTREF(pThis);
if (objRef != NULL)
{
MethodTable* pMT = objRef->GetMethodTable();
OBJECTREF typePtr = pMT->GetManagedClassObjectIfExists();
if (typePtr != NULL)
{
return OBJECTREFToObject(typePtr);
}
}
else
FCThrow(kNullReferenceException);
FC_INNER_RETURN(Object*, GetClassHelper(objRef));
}
FCIMPLEND
FCIMPL1(Object*, ObjectNative::Clone, Object* pThisUNSAFE)
{
FCALL_CONTRACT;
OBJECTREF refClone = NULL;
OBJECTREF refThis = ObjectToOBJECTREF(pThisUNSAFE);
if (refThis == NULL)
FCThrow(kNullReferenceException);
HELPER_METHOD_FRAME_BEGIN_RET_2(refClone, refThis);
// ObjectNative::Clone() ensures that the source and destination are always in
// the same context.
MethodTable* pMT = refThis->GetMethodTable();
// assert that String has overloaded the Clone() method
_ASSERTE(pMT != g_pStringClass);
if (pMT->IsArray()) {
refClone = DupArrayForCloning((BASEARRAYREF)refThis);
} else {
// We don't need to call the <cinit> because we know
// that it has been called....(It was called before this was created)
refClone = AllocateObject(pMT);
}
SIZE_T cb = refThis->GetSize() - sizeof(ObjHeader);
// copy contents of "this" to the clone
if (pMT->ContainsPointers())
{
memmoveGCRefs(OBJECTREFToObject(refClone), OBJECTREFToObject(refThis), cb);
}
else
{
memcpyNoGCRefs(OBJECTREFToObject(refClone), OBJECTREFToObject(refThis), cb);
}
HELPER_METHOD_FRAME_END();
return OBJECTREFToObject(refClone);
}
FCIMPLEND
FCIMPL3(FC_BOOL_RET, ObjectNative::WaitTimeout, CLR_BOOL exitContext, INT32 Timeout, Object* pThisUNSAFE)
{
FCALL_CONTRACT;
BOOL retVal = FALSE;
OBJECTREF pThis = (OBJECTREF) pThisUNSAFE;
HELPER_METHOD_FRAME_BEGIN_RET_1(pThis);
if (pThis == NULL)
COMPlusThrow(kNullReferenceException, W("NullReference_This"));
if ((Timeout < 0) && (Timeout != INFINITE_TIMEOUT))
COMPlusThrowArgumentOutOfRange(W("millisecondsTimeout"), W("ArgumentOutOfRange_NeedNonNegNum"));
retVal = pThis->Wait(Timeout, exitContext);
HELPER_METHOD_FRAME_END();
FC_RETURN_BOOL(retVal);
}
FCIMPLEND
FCIMPL1(void, ObjectNative::Pulse, Object* pThisUNSAFE)
{
FCALL_CONTRACT;
OBJECTREF pThis = (OBJECTREF) pThisUNSAFE;
HELPER_METHOD_FRAME_BEGIN_1(pThis);
if (pThis == NULL)
COMPlusThrow(kNullReferenceException, W("NullReference_This"));
pThis->Pulse();
HELPER_METHOD_FRAME_END();
}
FCIMPLEND
FCIMPL1(void, ObjectNative::PulseAll, Object* pThisUNSAFE)
{
FCALL_CONTRACT;
OBJECTREF pThis = (OBJECTREF) pThisUNSAFE;
HELPER_METHOD_FRAME_BEGIN_1(pThis);
if (pThis == NULL)
COMPlusThrow(kNullReferenceException, W("NullReference_This"));
pThis->PulseAll();
HELPER_METHOD_FRAME_END();
}
FCIMPLEND
FCIMPL1(FC_BOOL_RET, ObjectNative::IsLockHeld, Object* pThisUNSAFE)
{
FCALL_CONTRACT;
BOOL retVal;
DWORD owningThreadId;
DWORD acquisitionCount;
//
// If the lock is held, check if it's held by the current thread.
//
retVal = pThisUNSAFE->GetThreadOwningMonitorLock(&owningThreadId, &acquisitionCount);
if (retVal)
retVal = GetThread()->GetThreadId() == owningThreadId;
FC_RETURN_BOOL(retVal);
}
FCIMPLEND
<commit_msg>fixed typo in objectnative.cpp comments<commit_after>//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//
// File: ObjectNative.cpp
//
//
// Purpose: Native methods on System.Object
//
//
#include "common.h"
#include "objectnative.h"
#include "excep.h"
#include "vars.hpp"
#include "field.h"
#include "object.h"
#include "comsynchronizable.h"
#ifdef FEATURE_REMOTING
#include "remoting.h"
#endif
#include "eeconfig.h"
#ifdef FEATURE_REMOTING
#include "objectclone.h"
#endif
#include "mdaassistants.h"
/********************************************************************/
/* gets an object's 'value'. For normal classes, with reference
based semantics, this means the object's pointer. For boxed
primitive types, it also means just returning the pointer (because
they are immutable), for other value class, it means returning
a boxed copy. */
FCIMPL1(Object*, ObjectNative::GetObjectValue, Object* obj)
{
CONTRACTL
{
FCALL_CHECK;
INJECT_FAULT(FCThrow(kOutOfMemoryException););
}
CONTRACTL_END;
VALIDATEOBJECT(obj);
if (obj == 0)
return(obj);
MethodTable* pMT = obj->GetMethodTable();
// optimize for primitive types since GetVerifierCorElementType is slow.
if (pMT->IsTruePrimitive() || TypeHandle(pMT).GetVerifierCorElementType() != ELEMENT_TYPE_VALUETYPE) {
return(obj);
}
Object* retVal = NULL;
OBJECTREF objRef(obj);
HELPER_METHOD_FRAME_BEGIN_RET_1(objRef); // Set up a frame
// Technically we could return boxed DateTimes and Decimals without
// copying them here, but VB realized that this would be a breaking change
// for their customers. So copy them.
//
// MethodTable::Box is a cleaner way to copy value class, but it is slower than following code.
//
retVal = OBJECTREFToObject(AllocateObject(pMT));
CopyValueClass(retVal->GetData(), objRef->GetData(), pMT, retVal->GetAppDomain());
HELPER_METHOD_FRAME_END();
return(retVal);
}
FCIMPLEND
NOINLINE static INT32 GetHashCodeHelper(OBJECTREF objRef)
{
DWORD idx = 0;
FC_INNER_PROLOG(ObjectNative::GetHashCode);
HELPER_METHOD_FRAME_BEGIN_RET_ATTRIB_1(Frame::FRAME_ATTR_EXACT_DEPTH|Frame::FRAME_ATTR_CAPTURE_DEPTH_2, objRef);
#ifdef MDA_SUPPORTED
MdaModuloObjectHashcode* pProbe = MDA_GET_ASSISTANT(ModuloObjectHashcode);
#endif
idx = objRef->GetHashCodeEx();
#ifdef MDA_SUPPORTED
if (pProbe)
idx = idx % pProbe->GetModulo();
#endif
HELPER_METHOD_FRAME_END();
FC_INNER_EPILOG();
return idx;
}
// Note that we obtain a sync block index without actually building a sync block.
// That's because a lot of objects are hashed, without requiring support for
FCIMPL1(INT32, ObjectNative::GetHashCode, Object* obj) {
CONTRACTL
{
FCALL_CHECK;
INJECT_FAULT(FCThrow(kOutOfMemoryException););
}
CONTRACTL_END;
VALIDATEOBJECT(obj);
if (obj == 0)
return 0;
OBJECTREF objRef(obj);
#ifdef MDA_SUPPORTED
if (!MDA_GET_ASSISTANT(ModuloObjectHashcode))
#endif
{
DWORD bits = objRef->GetHeader()->GetBits();
if (bits & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX)
{
if (bits & BIT_SBLK_IS_HASHCODE)
{
// Common case: the object already has a hash code
return bits & MASK_HASHCODE;
}
else
{
// We have a sync block index. This means if we already have a hash code,
// it is in the sync block, otherwise we generate a new one and store it there
SyncBlock *psb = objRef->PassiveGetSyncBlock();
if (psb != NULL)
{
DWORD hashCode = psb->GetHashCode();
if (hashCode != 0)
return hashCode;
}
}
}
}
FC_INNER_RETURN(INT32, GetHashCodeHelper(objRef));
}
FCIMPLEND
//
// Compare by ref for normal classes, by value for value types.
//
// <TODO>@todo: it would be nice to customize this method based on the
// defining class rather than doing a runtime check whether it is
// a value type.</TODO>
//
FCIMPL2(FC_BOOL_RET, ObjectNative::Equals, Object *pThisRef, Object *pCompareRef)
{
CONTRACTL
{
FCALL_CHECK;
INJECT_FAULT(FCThrow(kOutOfMemoryException););
}
CONTRACTL_END;
if (pThisRef == pCompareRef)
FC_RETURN_BOOL(TRUE);
// Since we are in FCALL, we must handle NULL specially.
if (pThisRef == NULL || pCompareRef == NULL)
FC_RETURN_BOOL(FALSE);
MethodTable *pThisMT = pThisRef->GetMethodTable();
// If it's not a value class, don't compare by value
if (!pThisMT->IsValueType())
FC_RETURN_BOOL(FALSE);
// Make sure they are the same type.
if (pThisMT != pCompareRef->GetMethodTable())
FC_RETURN_BOOL(FALSE);
// Compare the contents (size - vtable - sync block index).
DWORD dwBaseSize = pThisRef->GetMethodTable()->GetBaseSize();
if(pThisRef->GetMethodTable() == g_pStringClass)
dwBaseSize -= sizeof(WCHAR);
BOOL ret = memcmp(
(void *) (pThisRef+1),
(void *) (pCompareRef+1),
dwBaseSize - sizeof(Object) - sizeof(int)) == 0;
FC_GC_POLL_RET();
FC_RETURN_BOOL(ret);
}
FCIMPLEND
NOINLINE static Object* GetClassHelper(OBJECTREF objRef)
{
FC_INNER_PROLOG(ObjectNative::GetClass);
_ASSERTE(objRef != NULL);
TypeHandle typeHandle = objRef->GetTypeHandle();
OBJECTREF refType = NULL;
// Arrays go down this slow path, at least don't do the full HelperMethodFrame setup
// if we are fetching the cached entry.
refType = typeHandle.GetManagedClassObjectFast();
if (refType != NULL)
return OBJECTREFToObject(refType);
HELPER_METHOD_FRAME_BEGIN_RET_ATTRIB_1(Frame::FRAME_ATTR_EXACT_DEPTH|Frame::FRAME_ATTR_CAPTURE_DEPTH_2, refType);
#ifdef FEATURE_REMOTING
if (objRef->IsTransparentProxy())
refType = CRemotingServices::GetClass(objRef);
else
#endif
refType = typeHandle.GetManagedClassObject();
HELPER_METHOD_FRAME_END();
FC_INNER_EPILOG();
return OBJECTREFToObject(refType);
}
// This routine is called by the Object.GetType() routine. It is a major way to get the Sytem.Type
FCIMPL1(Object*, ObjectNative::GetClass, Object* pThis)
{
CONTRACTL
{
FCALL_CHECK;
INJECT_FAULT(FCThrow(kOutOfMemoryException););
}
CONTRACTL_END;
OBJECTREF objRef = ObjectToOBJECTREF(pThis);
if (objRef != NULL)
{
MethodTable* pMT = objRef->GetMethodTable();
OBJECTREF typePtr = pMT->GetManagedClassObjectIfExists();
if (typePtr != NULL)
{
return OBJECTREFToObject(typePtr);
}
}
else
FCThrow(kNullReferenceException);
FC_INNER_RETURN(Object*, GetClassHelper(objRef));
}
FCIMPLEND
FCIMPL1(Object*, ObjectNative::Clone, Object* pThisUNSAFE)
{
FCALL_CONTRACT;
OBJECTREF refClone = NULL;
OBJECTREF refThis = ObjectToOBJECTREF(pThisUNSAFE);
if (refThis == NULL)
FCThrow(kNullReferenceException);
HELPER_METHOD_FRAME_BEGIN_RET_2(refClone, refThis);
// ObjectNative::Clone() ensures that the source and destination are always in
// the same context.
MethodTable* pMT = refThis->GetMethodTable();
// assert that String has overloaded the Clone() method
_ASSERTE(pMT != g_pStringClass);
if (pMT->IsArray()) {
refClone = DupArrayForCloning((BASEARRAYREF)refThis);
} else {
// We don't need to call the <cinit> because we know
// that it has been called....(It was called before this was created)
refClone = AllocateObject(pMT);
}
SIZE_T cb = refThis->GetSize() - sizeof(ObjHeader);
// copy contents of "this" to the clone
if (pMT->ContainsPointers())
{
memmoveGCRefs(OBJECTREFToObject(refClone), OBJECTREFToObject(refThis), cb);
}
else
{
memcpyNoGCRefs(OBJECTREFToObject(refClone), OBJECTREFToObject(refThis), cb);
}
HELPER_METHOD_FRAME_END();
return OBJECTREFToObject(refClone);
}
FCIMPLEND
FCIMPL3(FC_BOOL_RET, ObjectNative::WaitTimeout, CLR_BOOL exitContext, INT32 Timeout, Object* pThisUNSAFE)
{
FCALL_CONTRACT;
BOOL retVal = FALSE;
OBJECTREF pThis = (OBJECTREF) pThisUNSAFE;
HELPER_METHOD_FRAME_BEGIN_RET_1(pThis);
if (pThis == NULL)
COMPlusThrow(kNullReferenceException, W("NullReference_This"));
if ((Timeout < 0) && (Timeout != INFINITE_TIMEOUT))
COMPlusThrowArgumentOutOfRange(W("millisecondsTimeout"), W("ArgumentOutOfRange_NeedNonNegNum"));
retVal = pThis->Wait(Timeout, exitContext);
HELPER_METHOD_FRAME_END();
FC_RETURN_BOOL(retVal);
}
FCIMPLEND
FCIMPL1(void, ObjectNative::Pulse, Object* pThisUNSAFE)
{
FCALL_CONTRACT;
OBJECTREF pThis = (OBJECTREF) pThisUNSAFE;
HELPER_METHOD_FRAME_BEGIN_1(pThis);
if (pThis == NULL)
COMPlusThrow(kNullReferenceException, W("NullReference_This"));
pThis->Pulse();
HELPER_METHOD_FRAME_END();
}
FCIMPLEND
FCIMPL1(void, ObjectNative::PulseAll, Object* pThisUNSAFE)
{
FCALL_CONTRACT;
OBJECTREF pThis = (OBJECTREF) pThisUNSAFE;
HELPER_METHOD_FRAME_BEGIN_1(pThis);
if (pThis == NULL)
COMPlusThrow(kNullReferenceException, W("NullReference_This"));
pThis->PulseAll();
HELPER_METHOD_FRAME_END();
}
FCIMPLEND
FCIMPL1(FC_BOOL_RET, ObjectNative::IsLockHeld, Object* pThisUNSAFE)
{
FCALL_CONTRACT;
BOOL retVal;
DWORD owningThreadId;
DWORD acquisitionCount;
//
// If the lock is held, check if it's held by the current thread.
//
retVal = pThisUNSAFE->GetThreadOwningMonitorLock(&owningThreadId, &acquisitionCount);
if (retVal)
retVal = GetThread()->GetThreadId() == owningThreadId;
FC_RETURN_BOOL(retVal);
}
FCIMPLEND
<|endoftext|> |
<commit_before>/*
* LoadHandler.cpp
*
* Created on: 29.05.2017
* Author: Alexander
*/
#include "persistence/base/LoadHandler.hpp"
#ifdef NDEBUG
#define MSG_DEBUG(a) /**/
#else
#define MSG_DEBUG(a) std::cout << "| DEBUG | " << a << std::endl
#endif
#define MSG_WARNING(a) std::cout << "| WARNING | "<< a << std::endl
#define MSG_ERROR(a) std::cout << "| ERROR | " << a << std::endl
#define MSG_FLF __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << "() "
#include <iostream>
#include <sstream> // used for getLevel()
#include <cassert>
#include "abstractDataTypes/Bag.hpp"
#include "abstractDataTypes/Union.hpp"
#include "ecore/EClass.hpp"
#include "ecore/EClassifier.hpp"
#include "ecore/EObject.hpp"
#include "ecore/EPackage.hpp"
#include "ecore/EStructuralFeature.hpp"
#include "uml/Class.hpp"
#include "uml/NamedElement.hpp"
#include "uml/Package.hpp"
#include "persistence/base/HandlerHelper.hpp"
#include "pluginFramework/MDE4CPPPlugin.hpp"
#include "pluginFramework/PluginFramework.hpp"
#include "pluginFramework/EcoreModelPlugin.hpp"
#include "pluginFramework/UMLModelPlugin.hpp"
#include "abstractDataTypes/SubsetUnion.hpp"
using namespace persistence::base;
LoadHandler::LoadHandler()
{
m_rootObject = nullptr;
m_level = -1;
m_isXSIMode = true;
}
LoadHandler::~LoadHandler()
{
}
std::shared_ptr<ecore::EObject> LoadHandler::getObjectByRef(std::string ref)
{
std::shared_ptr<ecore::EObject> tmp;
if (!ref.empty())
{
if (m_refToObject_map.find(ref) != m_refToObject_map.end())
{
// found
tmp = m_refToObject_map.at(ref);
//return std::dynamic_pointer_cast<ecore::EObject>( tmp );
}
else
{
size_t double_dot = ref.find("#//", 0);
std::string _ref_prefix = "";
std::string _ref_name = "";
if (double_dot != std::string::npos)
{
std::string _ref_prefix = ref.substr(0, double_dot); // TODO '_ref_prefix' is not used in this case
std::string _ref_name = ref.substr(double_dot);
}
if (m_refToObject_map.find(_ref_name) != m_refToObject_map.end())
{
// found
tmp = m_refToObject_map.at(_ref_name);
//return std::dynamic_pointer_cast<ecore::EObject>( tmp );
}
else
{
MSG_WARNING("Given Reference-Name '" << ref << "' or '" << _ref_name << "' are not in stored map.");
return nullptr;
}
}
}
return tmp;
}
void LoadHandler::addToMap(std::shared_ptr<ecore::EObject> object)
{
addToMap(object, true, "");
}
void LoadHandler::addToMap(std::shared_ptr<ecore::EObject> object, bool useCurrentObjects, const std::string& uri)
{
std::string ref = "";
if (useCurrentObjects)
{
ref = getCurrentXMIID();
if (ref.empty())
{
ref = persistence::base::HandlerHelper::extractReference(object, m_rootObject, m_rootPrefix, m_currentObjects, uri);
}
}
else
{
ref = persistence::base::HandlerHelper::extractReference(object, m_rootObject, m_rootPrefix, uri);
}
if (!ref.empty())
{
if (m_refToObject_map.find(ref) == m_refToObject_map.end())
{
// ref not found in map, so insert
m_refToObject_map.insert(std::pair<std::string, std::shared_ptr<ecore::EObject>>(ref, object));
MSG_DEBUG("Add to map: '" << ref << "' eClass: '" << object->eClass()->getName() << "'");
}
}
}
/**/
std::string LoadHandler::getPrefix()
{
return m_rootPrefix;
}
std::string LoadHandler::getRootName()
{
return m_rootName;
}
std::string LoadHandler::getLevel()
{
std::stringstream ss;
for (int ii = 0; ii < m_level; ii++)
{
ss << " ";
}
return ss.str();
}
void LoadHandler::handleRoot(std::shared_ptr<ecore::EObject> object)
{
if (object == nullptr)
{
return;
}
m_level++;
m_currentObjects.push_back(object);
m_rootObject = object;
getNextNodeName();
if (!m_isXSIMode)
{
m_refToObject_map.insert(std::pair<std::string, std::shared_ptr<ecore::EObject>>(getCurrentXMIID(), m_rootObject));
}
object->load(m_thisPtr);
}
void LoadHandler::handleChild(std::shared_ptr<ecore::EObject> object)
{
if (object == nullptr)
{
return;
}
m_level++;
m_currentObjects.push_back(object);
if (!m_isXSIMode)
{
addToMap(object); // add 'object' to loadHandler's internal Map, that is used for resolving references.
}
object->load(m_thisPtr); // call recursively 'object.load().
if (m_isXSIMode)
{
addToMap(object); // add 'object' to loadHandler's internal Map, that is used for resolving references.
}
release(); // report loadHandler to set 'this' as new current Object.
}
std::shared_ptr<ecore::EObject> LoadHandler::getCurrentObject()
{
std::shared_ptr<ecore::EObject> tmp_obj = m_currentObjects.back();
assert(tmp_obj);
return tmp_obj;
}
/*
* This API is adapted to API in Project emf4cpp.
*
* LINK to source: https://github.com/catedrasaes-umu/emf4cpp/tree/master/emf4cpp/ecorecpp/serializer/serializer-xerces.cpp
* ::ecorecpp::mapping::type_traits::string_t serializer::get_type(EObject_ptr obj) const
*
*/
std::string LoadHandler::extractType(std::shared_ptr<ecore::EObject> obj) const
{
return persistence::base::HandlerHelper::extractType(obj, m_rootPrefix);
}
void LoadHandler::release()
{
std::shared_ptr<ecore::EObject> tmp_obj = m_currentObjects.back();
if (tmp_obj == nullptr)
{
MSG_ERROR("You can't call " << __PRETTY_FUNCTION__ << " while current Object is nullptr.");
}
else
{
// set current (container) object as new current object (decrease depth)
m_currentObjects.pop_back();
m_level--;
}
}
void LoadHandler::addUnresolvedReference(const std::string &name, std::shared_ptr<ecore::EObject> object, std::shared_ptr<ecore::EStructuralFeature> esf)
{
if (object != nullptr)
{
if (esf != nullptr)
{
m_unresolvedReferences.push_back(persistence::base::UnresolvedReference(name, object, esf));
}
else
{
MSG_ERROR(MSG_FLF << " esf is a nullptr");
}
}
else
{
MSG_ERROR(MSG_FLF << " object is a nullptr");
}
}
void LoadHandler::resolveReferences()
{
while (!m_unresolvedReferences.empty())
{
persistence::base::UnresolvedReference uref = m_unresolvedReferences.back();
m_unresolvedReferences.pop_back();
std::string name = uref.refName;
std::shared_ptr<ecore::EObject> object = uref.eObject;
std::shared_ptr<ecore::EStructuralFeature> esf = uref.eStructuralFeature;
std::list<std::shared_ptr<ecore::EObject>> references;
try
{
if (esf->getUpperBound() == 1)
{
// EStructuralFeature is a single object
solve(name, references, object, esf);
}
else
{
// EStructuralFeature is a list of objects
std::list<std::string> _strs;
std::string _tmpStr;
size_t pos = name.find(" ");
size_t initPos = 0;
while( pos != std::string::npos )
{
_strs.push_back( name.substr( initPos, pos - initPos ) );
initPos = pos + 1;
pos = name.find( " ", initPos );
}
while (_strs.size() > 0)
{
_tmpStr = _strs.front();
if (std::string::npos != _tmpStr.find("#//") || !m_isXSIMode)
{
solve(_tmpStr, references, object, esf);
}
_strs.pop_front();
}
// Call resolveReferences() of corresponding 'object'
object->resolveReferences(esf->getFeatureID(), references);
}
}
catch (std::exception& e)
{
MSG_ERROR(MSG_FLF << " Exception: " << e.what());
}
}
}
void LoadHandler::setThisPtr(std::shared_ptr<LoadHandler> thisPtr)
{
m_thisPtr = thisPtr;
}
void LoadHandler::solve(const std::string& name, std::list<std::shared_ptr<ecore::EObject>> references, std::shared_ptr<ecore::EObject> object, std::shared_ptr<ecore::EStructuralFeature> esf)
{
bool found = false;
bool libraryLoaded = false;
while (!found)
{
std::shared_ptr<ecore::EObject> resolved_object = this->getObjectByRef(name);
if (resolved_object)
{
references.push_back(resolved_object);
// Call resolveReferences() of corresponding 'object'
object->resolveReferences(esf->getFeatureID(), references);
found = true;
}
else
{
std::string adr= std::to_string ((long)(&(*object)));
std::string adrName="#//";
adrName=adrName+ object->eClass()->getName() + "_" +adr;
std::shared_ptr<ecore::EObject> resolved_object = this->getObjectByRef(adrName);
if (resolved_object)
{
references.push_back(resolved_object);
// Call resolveReferences() of corresponding 'object'
object->resolveReferences(esf->getFeatureID(), references);
found = true;
}
else
{
if (libraryLoaded)
{
return;
}
loadTypes(name);
libraryLoaded = true;
}
}
}
}
void LoadHandler::loadTypes(const std::string& name)
{
unsigned int indexStartUri = name.find(" ");
unsigned int indexEndUri = name.find("#");
if (indexStartUri != std::string::npos)
{
std::string nsURI = name.substr(indexStartUri+1, indexEndUri-indexStartUri-1);
unsigned int index = nsURI.find("file:/");
if (index == 0)
{
loadTypesFromFile(nsURI);
}
else
{
std::shared_ptr<MDE4CPPPlugin> plugin = PluginFramework::eInstance()->findPluginByUri(nsURI);
if (plugin)
{
std::shared_ptr<EcoreModelPlugin> ecorePlugin = std::dynamic_pointer_cast<EcoreModelPlugin>(plugin);
if (ecorePlugin)
{
loadTypes(ecorePlugin->getEPackage(), nsURI);
return;
}
std::shared_ptr<UMLModelPlugin> umlPlugin = std::dynamic_pointer_cast<UMLModelPlugin>(plugin);
if (umlPlugin)
{
loadTypes(umlPlugin->getPackage(), nsURI);
}
}
}
}
}
void LoadHandler::loadTypes(std::shared_ptr<ecore::EPackage> package, const std::string& uri)
{
std::shared_ptr<Subset<ecore::EClassifier, ecore::EObject>> eClassifiers = package->getEClassifiers();
for (std::shared_ptr<ecore::EClassifier> eClassifier : *eClassifiers)
{
// Filter only EDataType objects and add to handler's internal map
std::shared_ptr<ecore::EClass> _metaClass = eClassifier->eClass();
addToMap(eClassifier, false, uri); // TODO add default parameter force=true to addToMap()
}
}
void LoadHandler::loadTypes(std::shared_ptr<uml::Package> package, const std::string& uri)
{
std::shared_ptr<Bag<uml::NamedElement>> memberList = package->getMember();
for (std::shared_ptr<uml::NamedElement> member : *memberList)
{
// Filter only EDataType objects and add to handler's internal map
std::string metaClassName = "";
std::shared_ptr<ecore::EClass> ecoreMetaClass = member->eClass();
if (ecoreMetaClass)
{
auto x = ecoreMetaClass->getEPackage().lock();
if (x)
{
metaClassName = x->getName() + ":" + ecoreMetaClass->getName();
}
else
{
metaClassName = ecoreMetaClass->getName();
}
}
else
{
std::shared_ptr<uml::Class> metaClass = member->getMetaClass();
if (metaClass == nullptr)
{
metaClassName = metaClass->getName();
}
}
std::string ref = metaClassName + " " + uri + "#" + member->getName();
m_refToObject_map.insert(std::pair<std::string, std::shared_ptr<ecore::EObject>>(ref, member));
MSG_DEBUG("Add to map: '" << ref << "'");
}
}
std::map<std::string, std::shared_ptr<ecore::EObject>> LoadHandler::getTypesMap()
{
return m_refToObject_map;
}
<commit_msg>Bugfix: load References<commit_after>/*
* LoadHandler.cpp
*
* Created on: 29.05.2017
* Author: Alexander
*/
#include "persistence/base/LoadHandler.hpp"
#include "PersistenceDefine.hpp"
#include <iostream>
#include <sstream> // used for getLevel()
#include <cassert>
#include "abstractDataTypes/Bag.hpp"
#include "abstractDataTypes/Union.hpp"
#include "ecore/EClass.hpp"
#include "ecore/EClassifier.hpp"
#include "ecore/EObject.hpp"
#include "ecore/EPackage.hpp"
#include "ecore/EStructuralFeature.hpp"
#include "uml/Class.hpp"
#include "uml/NamedElement.hpp"
#include "uml/Package.hpp"
#include "persistence/base/HandlerHelper.hpp"
#include "pluginFramework/MDE4CPPPlugin.hpp"
#include "pluginFramework/PluginFramework.hpp"
#include "pluginFramework/EcoreModelPlugin.hpp"
#include "pluginFramework/UMLModelPlugin.hpp"
#include "abstractDataTypes/SubsetUnion.hpp"
using namespace persistence::base;
LoadHandler::LoadHandler()
{
m_rootObject = nullptr;
m_level = -1;
m_isXSIMode = true;
}
LoadHandler::~LoadHandler()
{
}
std::shared_ptr<ecore::EObject> LoadHandler::getObjectByRef(std::string ref)
{
std::shared_ptr<ecore::EObject> tmp;
if (!ref.empty())
{
if (m_refToObject_map.find(ref) != m_refToObject_map.end())
{
// found
tmp = m_refToObject_map.at(ref);
//return std::dynamic_pointer_cast<ecore::EObject>( tmp );
}
else
{
size_t double_dot = ref.find("#//", 0);
std::string _ref_prefix = "";
std::string _ref_name = "";
if (double_dot != std::string::npos)
{
std::string _ref_prefix = ref.substr(0, double_dot); // TODO '_ref_prefix' is not used in this case
std::string _ref_name = ref.substr(double_dot);
}
if (m_refToObject_map.find(_ref_name) != m_refToObject_map.end())
{
// found
tmp = m_refToObject_map.at(_ref_name);
//return std::dynamic_pointer_cast<ecore::EObject>( tmp );
}
else
{
MSG_WARNING("Given Reference-Name '" << ref << "' or '" << _ref_name << "' are not in stored map.");
return nullptr;
}
}
}
return tmp;
}
void LoadHandler::addToMap(std::shared_ptr<ecore::EObject> object)
{
addToMap(object, true, "");
}
void LoadHandler::addToMap(std::shared_ptr<ecore::EObject> object, bool useCurrentObjects, const std::string& uri)
{
std::string ref = "";
if (useCurrentObjects)
{
ref = getCurrentXMIID();
if (ref.empty())
{
ref = persistence::base::HandlerHelper::extractReference(object, m_rootObject, m_rootPrefix, m_currentObjects, uri);
}
}
else
{
ref = persistence::base::HandlerHelper::extractReference(object, m_rootObject, m_rootPrefix, uri);
}
if (!ref.empty())
{
if (m_refToObject_map.find(ref) == m_refToObject_map.end())
{
// ref not found in map, so insert
m_refToObject_map.insert(std::pair<std::string, std::shared_ptr<ecore::EObject>>(ref, object));
MSG_DEBUG("Add to map: '" << ref << "' eClass: '" << object->eClass()->getName() << "'");
}
}
}
/**/
std::string LoadHandler::getPrefix()
{
return m_rootPrefix;
}
std::string LoadHandler::getRootName()
{
return m_rootName;
}
std::string LoadHandler::getLevel()
{
std::stringstream ss;
for (int ii = 0; ii < m_level; ii++)
{
ss << " ";
}
return ss.str();
}
void LoadHandler::handleRoot(std::shared_ptr<ecore::EObject> object)
{
if (object == nullptr)
{
return;
}
m_level++;
m_currentObjects.push_back(object);
m_rootObject = object;
getNextNodeName();
if (!m_isXSIMode)
{
m_refToObject_map.insert(std::pair<std::string, std::shared_ptr<ecore::EObject>>(getCurrentXMIID(), m_rootObject));
}
object->load(m_thisPtr);
}
void LoadHandler::handleChild(std::shared_ptr<ecore::EObject> object)
{
if (object == nullptr)
{
return;
}
m_level++;
m_currentObjects.push_back(object);
if (!m_isXSIMode)
{
addToMap(object); // add 'object' to loadHandler's internal Map, that is used for resolving references.
}
object->load(m_thisPtr); // call recursively 'object.load().
if (m_isXSIMode)
{
addToMap(object); // add 'object' to loadHandler's internal Map, that is used for resolving references.
}
release(); // report loadHandler to set 'this' as new current Object.
}
std::shared_ptr<ecore::EObject> LoadHandler::getCurrentObject()
{
std::shared_ptr<ecore::EObject> tmp_obj = m_currentObjects.back();
assert(tmp_obj);
return tmp_obj;
}
/*
* This API is adapted to API in Project emf4cpp.
*
* LINK to source: https://github.com/catedrasaes-umu/emf4cpp/tree/master/emf4cpp/ecorecpp/serializer/serializer-xerces.cpp
* ::ecorecpp::mapping::type_traits::string_t serializer::get_type(EObject_ptr obj) const
*
*/
std::string LoadHandler::extractType(std::shared_ptr<ecore::EObject> obj) const
{
return persistence::base::HandlerHelper::extractType(obj, m_rootPrefix);
}
void LoadHandler::release()
{
std::shared_ptr<ecore::EObject> tmp_obj = m_currentObjects.back();
if (tmp_obj == nullptr)
{
MSG_ERROR("You can't call " << __PRETTY_FUNCTION__ << " while current Object is nullptr.");
}
else
{
// set current (container) object as new current object (decrease depth)
m_currentObjects.pop_back();
m_level--;
}
}
void LoadHandler::addUnresolvedReference(const std::string &name, std::shared_ptr<ecore::EObject> object, std::shared_ptr<ecore::EStructuralFeature> esf)
{
if (object != nullptr)
{
if (esf != nullptr)
{
m_unresolvedReferences.push_back(persistence::base::UnresolvedReference(name, object, esf));
}
else
{
MSG_ERROR(MSG_FLF << " esf is a nullptr");
}
}
else
{
MSG_ERROR(MSG_FLF << " object is a nullptr");
}
}
void LoadHandler::resolveReferences()
{
while (!m_unresolvedReferences.empty())
{
persistence::base::UnresolvedReference uref = m_unresolvedReferences.back();
m_unresolvedReferences.pop_back();
std::string name = uref.refName;
std::shared_ptr<ecore::EObject> object = uref.eObject;
std::shared_ptr<ecore::EStructuralFeature> esf = uref.eStructuralFeature;
std::list<std::shared_ptr<ecore::EObject>> references;
try
{
if (esf->getUpperBound() == 1)
{
// EStructuralFeature is a single object
solve(name, references, object, esf);
}
else
{
// EStructuralFeature is a list of objects
std::list<std::string> _strs;
std::string _tmpStr;
int nameSize=name.size();
if(nameSize>0)
{
size_t pos = name.find(" ");
size_t initPos = 0;
while( pos != std::string::npos )
{
_strs.push_back( name.substr( initPos, pos - initPos ) );
initPos = pos + 1;
pos = name.find( " ", initPos );
}
// Add last reference
_strs.push_back( name.substr( initPos, nameSize - initPos ) );
while (_strs.size() > 0)
{
_tmpStr = _strs.front();
if (std::string::npos != _tmpStr.find("#//") || !m_isXSIMode)
{
solve(_tmpStr, references, object, esf);
}
_strs.pop_front();
}
// Call resolveReferences() of corresponding 'object'
object->resolveReferences(esf->getFeatureID(), references);
}
}
}
catch (std::exception& e)
{
MSG_ERROR(MSG_FLF << " Exception: " << e.what());
}
}
}
void LoadHandler::setThisPtr(std::shared_ptr<LoadHandler> thisPtr)
{
m_thisPtr = thisPtr;
}
void LoadHandler::solve(const std::string& name, std::list<std::shared_ptr<ecore::EObject>> references, std::shared_ptr<ecore::EObject> object, std::shared_ptr<ecore::EStructuralFeature> esf)
{
bool found = false;
bool libraryLoaded = false;
while (!found)
{
std::shared_ptr<ecore::EObject> resolved_object = this->getObjectByRef(name);
if (resolved_object)
{
references.push_back(resolved_object);
// Call resolveReferences() of corresponding 'object'
object->resolveReferences(esf->getFeatureID(), references);
found = true;
}
else
{
std::string adr= std::to_string ((long)(&(*object)));
std::string adrName="#//";
adrName=adrName+ object->eClass()->getName() + "_" +adr;
std::shared_ptr<ecore::EObject> resolved_object = this->getObjectByRef(adrName);
if (resolved_object)
{
references.push_back(resolved_object);
// Call resolveReferences() of corresponding 'object'
object->resolveReferences(esf->getFeatureID(), references);
found = true;
}
else
{
if (libraryLoaded)
{
return;
}
loadTypes(name);
libraryLoaded = true;
}
}
}
}
void LoadHandler::loadTypes(const std::string& name)
{
unsigned int indexStartUri = name.find(" ");
unsigned int indexEndUri = name.find("#");
if (indexStartUri != std::string::npos)
{
std::string nsURI = name.substr(indexStartUri+1, indexEndUri-indexStartUri-1);
unsigned int index = nsURI.find("file:/");
if (index == 0)
{
loadTypesFromFile(nsURI);
}
else
{
std::shared_ptr<MDE4CPPPlugin> plugin = PluginFramework::eInstance()->findPluginByUri(nsURI);
if (plugin)
{
std::shared_ptr<EcoreModelPlugin> ecorePlugin = std::dynamic_pointer_cast<EcoreModelPlugin>(plugin);
if (ecorePlugin)
{
loadTypes(ecorePlugin->getEPackage(), nsURI);
return;
}
std::shared_ptr<UMLModelPlugin> umlPlugin = std::dynamic_pointer_cast<UMLModelPlugin>(plugin);
if (umlPlugin)
{
loadTypes(umlPlugin->getPackage(), nsURI);
}
}
}
}
}
void LoadHandler::loadTypes(std::shared_ptr<ecore::EPackage> package, const std::string& uri)
{
std::shared_ptr<Subset<ecore::EClassifier, ecore::EObject>> eClassifiers = package->getEClassifiers();
for (std::shared_ptr<ecore::EClassifier> eClassifier : *eClassifiers)
{
// Filter only EDataType objects and add to handler's internal map
std::shared_ptr<ecore::EClass> _metaClass = eClassifier->eClass();
addToMap(eClassifier, false, uri); // TODO add default parameter force=true to addToMap()
}
}
void LoadHandler::loadTypes(std::shared_ptr<uml::Package> package, const std::string& uri)
{
std::shared_ptr<Bag<uml::NamedElement>> memberList = package->getMember();
for (std::shared_ptr<uml::NamedElement> member : *memberList)
{
// Filter only EDataType objects and add to handler's internal map
std::string metaClassName = "";
std::shared_ptr<ecore::EClass> ecoreMetaClass = member->eClass();
if (ecoreMetaClass)
{
auto x = ecoreMetaClass->getEPackage().lock();
if (x)
{
metaClassName = x->getName() + ":" + ecoreMetaClass->getName();
}
else
{
metaClassName = ecoreMetaClass->getName();
}
}
else
{
std::shared_ptr<uml::Class> metaClass = member->getMetaClass();
if (metaClass == nullptr)
{
metaClassName = metaClass->getName();
}
}
std::string ref = metaClassName + " " + uri + "#" + member->getName();
m_refToObject_map.insert(std::pair<std::string, std::shared_ptr<ecore::EObject>>(ref, member));
MSG_DEBUG("Add to map: '" << ref << "'");
}
}
std::map<std::string, std::shared_ptr<ecore::EObject>> LoadHandler::getTypesMap()
{
return m_refToObject_map;
}
<|endoftext|> |
<commit_before>/* Copyright 2022 Google LLC. 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 <memory>
#include <stdexcept>
#include <string>
#include "absl/status/status.h"
#include "absl/strings/string_view.h"
#include "cpp/array_record_reader.h"
#include "cpp/array_record_writer.h"
#include "cpp/thread_pool.h"
#include "pybind11/gil.h"
#include "pybind11/pybind11.h"
#include "pybind11/pytypes.h"
#include "pybind11/stl.h"
#include "riegeli/bytes/fd_reader.h"
#include "riegeli/bytes/fd_writer.h"
namespace py = pybind11;
PYBIND11_MODULE(array_record_module, m) {
using ArrayRecordWriter =
array_record::ArrayRecordWriter<std::unique_ptr<riegeli::Writer>>;
using ArrayRecordReader =
array_record::ArrayRecordReader<std::unique_ptr<riegeli::Reader>>;
py::class_<ArrayRecordWriter>(m, "ArrayRecordWriter")
.def(py::init([](const std::string& path, const std::string& options) {
auto status_or_option =
array_record::ArrayRecordWriterBase::Options::FromString(
options);
if (!status_or_option.ok()) {
throw py::value_error(
std::string(status_or_option.status().message()));
}
auto file_writer = std::make_unique<riegeli::FdWriter<>>(path);
if (!file_writer->ok()) {
throw std::runtime_error(
std::string(file_writer->status().message()));
}
return array_record::ArrayRecordWriter<
std::unique_ptr<riegeli::Writer>>(std::move(file_writer),
status_or_option.value());
}),
py::arg("path"), py::arg("options") = "")
.def("ok", &ArrayRecordWriter::ok)
.def("close",
[](ArrayRecordWriter& writer) {
if (!writer.Close()) {
throw std::runtime_error(std::string(writer.status().message()));
}
})
.def("is_open", &ArrayRecordWriter::is_open)
// We accept only py::bytes (and not unicode strings) since we expect
// most users to store binary data (e.g. serialized protocol buffers).
// We cannot know if a users wants to write+read unicode and forcing users
// to encode() their unicode strings avoids accidential convertions.
.def("write", [](ArrayRecordWriter& writer, py::bytes record) {
if (!writer.WriteRecord(record)) {
throw std::runtime_error(std::string(writer.status().message()));
}
});
py::class_<array_record::ArrayRecordReader<std::unique_ptr<riegeli::Reader>>>(
m, "ArrayRecordReader")
.def(py::init([](const std::string& path, const std::string& options) {
auto status_or_option =
array_record::ArrayRecordReaderBase::Options::FromString(
options);
if (!status_or_option.ok()) {
throw py::value_error(
std::string(status_or_option.status().message()));
}
auto file_reader = std::make_unique<riegeli::FdReader<>>(path);
if (!file_reader->ok()) {
throw std::runtime_error(
std::string(file_reader->status().message()));
}
return array_record::ArrayRecordReader<
std::unique_ptr<riegeli::Reader>>(
std::move(file_reader), status_or_option.value(),
array_record::ArrayRecordGlobalPool());
}),
py::arg("path"), py::arg("options") = "")
.def("ok", &ArrayRecordReader::ok)
.def("close",
[](ArrayRecordReader& reader) {
if (!reader.Close()) {
throw std::runtime_error(std::string(reader.status().message()));
}
})
.def("is_open", &ArrayRecordReader::is_open)
.def("num_records", &ArrayRecordReader::NumRecords)
.def("record_index", &ArrayRecordReader::RecordIndex)
.def("seek",
[](ArrayRecordReader& reader, int64_t record_index) {
if (!reader.SeekRecord(record_index)) {
throw std::runtime_error(std::string(reader.status().message()));
}
})
// See write() for why this returns py::bytes.
.def("read",
[](ArrayRecordReader& reader) {
absl::string_view string_view;
if (!reader.ReadRecord(&string_view)) {
if (reader.ok()) {
throw std::out_of_range(absl::StrFormat(
"Out of range of num_records: %d", reader.NumRecords()));
}
throw std::runtime_error(std::string(reader.status().message()));
}
return py::bytes(string_view);
})
.def(
"read",
[](ArrayRecordReader& reader, std::vector<uint64_t> indices) {
std::vector<py::bytes> output(indices.size());
auto status = reader.ParallelReadRecordsWithIndices(
indices,
[&](uint64_t indices_index,
absl::string_view record_data) -> absl::Status {
output[indices_index] = record_data;
return absl::OkStatus();
});
if (!status.ok()) {
throw std::runtime_error(std::string(status.message()));
}
return output;
},
py::call_guard<py::gil_scoped_release>())
.def(
"read_all",
[](ArrayRecordReader& reader) {
std::vector<py::bytes> output(reader.NumRecords());
auto status = reader.ParallelReadRecords(
[&](uint64_t index,
absl::string_view record_data) -> absl::Status {
output[index] = record_data;
return absl::OkStatus();
});
if (!status.ok()) {
throw std::runtime_error(std::string(status.message()));
}
return output;
},
py::call_guard<py::gil_scoped_release>());
}
<commit_msg>Ensure Python GIL is held when manipulating py::bytes<commit_after>/* Copyright 2022 Google LLC. 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 <memory>
#include <stdexcept>
#include <string>
#include "absl/status/status.h"
#include "absl/strings/string_view.h"
#include "cpp/array_record_reader.h"
#include "cpp/array_record_writer.h"
#include "cpp/thread_pool.h"
#include "pybind11/gil.h"
#include "pybind11/pybind11.h"
#include "pybind11/pytypes.h"
#include "pybind11/stl.h"
#include "riegeli/bytes/fd_reader.h"
#include "riegeli/bytes/fd_writer.h"
namespace py = pybind11;
PYBIND11_MODULE(array_record_module, m) {
using ArrayRecordWriter =
array_record::ArrayRecordWriter<std::unique_ptr<riegeli::Writer>>;
using ArrayRecordReader =
array_record::ArrayRecordReader<std::unique_ptr<riegeli::Reader>>;
py::class_<ArrayRecordWriter>(m, "ArrayRecordWriter")
.def(py::init([](const std::string& path, const std::string& options) {
auto status_or_option =
array_record::ArrayRecordWriterBase::Options::FromString(
options);
if (!status_or_option.ok()) {
throw py::value_error(
std::string(status_or_option.status().message()));
}
auto file_writer = std::make_unique<riegeli::FdWriter<>>(path);
if (!file_writer->ok()) {
throw std::runtime_error(
std::string(file_writer->status().message()));
}
return array_record::ArrayRecordWriter<
std::unique_ptr<riegeli::Writer>>(std::move(file_writer),
status_or_option.value());
}),
py::arg("path"), py::arg("options") = "")
.def("ok", &ArrayRecordWriter::ok)
.def("close",
[](ArrayRecordWriter& writer) {
if (!writer.Close()) {
throw std::runtime_error(std::string(writer.status().message()));
}
})
.def("is_open", &ArrayRecordWriter::is_open)
// We accept only py::bytes (and not unicode strings) since we expect
// most users to store binary data (e.g. serialized protocol buffers).
// We cannot know if a users wants to write+read unicode and forcing users
// to encode() their unicode strings avoids accidential convertions.
.def("write", [](ArrayRecordWriter& writer, py::bytes record) {
if (!writer.WriteRecord(record)) {
throw std::runtime_error(std::string(writer.status().message()));
}
});
py::class_<array_record::ArrayRecordReader<std::unique_ptr<riegeli::Reader>>>(
m, "ArrayRecordReader")
.def(py::init([](const std::string& path, const std::string& options) {
auto status_or_option =
array_record::ArrayRecordReaderBase::Options::FromString(
options);
if (!status_or_option.ok()) {
throw py::value_error(
std::string(status_or_option.status().message()));
}
auto file_reader = std::make_unique<riegeli::FdReader<>>(path);
if (!file_reader->ok()) {
throw std::runtime_error(
std::string(file_reader->status().message()));
}
return array_record::ArrayRecordReader<
std::unique_ptr<riegeli::Reader>>(
std::move(file_reader), status_or_option.value(),
array_record::ArrayRecordGlobalPool());
}),
py::arg("path"), py::arg("options") = "")
.def("ok", &ArrayRecordReader::ok)
.def("close",
[](ArrayRecordReader& reader) {
if (!reader.Close()) {
throw std::runtime_error(std::string(reader.status().message()));
}
})
.def("is_open", &ArrayRecordReader::is_open)
.def("num_records", &ArrayRecordReader::NumRecords)
.def("record_index", &ArrayRecordReader::RecordIndex)
.def("seek",
[](ArrayRecordReader& reader, int64_t record_index) {
if (!reader.SeekRecord(record_index)) {
throw std::runtime_error(std::string(reader.status().message()));
}
})
// See write() for why this returns py::bytes.
.def("read",
[](ArrayRecordReader& reader) {
absl::string_view string_view;
if (!reader.ReadRecord(&string_view)) {
if (reader.ok()) {
throw std::out_of_range(absl::StrFormat(
"Out of range of num_records: %d", reader.NumRecords()));
}
throw std::runtime_error(std::string(reader.status().message()));
}
return py::bytes(string_view);
})
.def("read",
[](ArrayRecordReader& reader, std::vector<uint64_t> indices) {
std::vector<std::string> staging(indices.size());
py::list output(indices.size());
{
py::gil_scoped_release scoped_release;
auto status = reader.ParallelReadRecordsWithIndices(
indices,
[&](uint64_t indices_index,
absl::string_view record_data) -> absl::Status {
staging[indices_index] = record_data;
return absl::OkStatus();
});
if (!status.ok()) {
throw std::runtime_error(std::string(status.message()));
}
}
ssize_t index = 0;
for (const auto& record : staging) {
auto py_record = py::bytes(record);
PyList_SET_ITEM(output.ptr(), index++,
py_record.release().ptr());
}
return output;
})
.def("read_all", [](ArrayRecordReader& reader) {
std::vector<std::string> staging(reader.NumRecords());
py::list output(reader.NumRecords());
{
py::gil_scoped_release scoped_release;
auto status = reader.ParallelReadRecords(
[&](uint64_t index,
absl::string_view record_data) -> absl::Status {
staging[index] = record_data;
return absl::OkStatus();
});
if (!status.ok()) {
throw std::runtime_error(std::string(status.message()));
}
}
ssize_t index = 0;
for (const auto& record : staging) {
auto py_record = py::bytes(record);
PyList_SET_ITEM(output.ptr(), index++, py_record.release().ptr());
}
return output;
});
}
<|endoftext|> |
<commit_before>/* RTcmix - Copyright (C) 2005 The RTcmix Development Team
See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include <Offt.h>
#ifndef FFTW
#include <FFTReal.h>
#endif
Offt::Offt(int fftsize, unsigned int flags)
: _len(fftsize)
{
#ifdef FFTW
_plan_r2c = _plan_r2c = NULL;
_buf = (float *) fftwf_malloc(sizeof(float) * _len);
int csize = sizeof(fftwf_complex) * ((_len / 2) + 1);
_cbuf = (fftwf_complex *) fftwf_malloc(csize);
if (flags & kRealToComplex)
_plan_r2c = fftwf_plan_dft_r2c_1d(_len, _buf, _cbuf, FFTW_ESTIMATE);
if (flags & kComplexToReal)
_plan_c2r = fftwf_plan_dft_c2r_1d(_len, _cbuf, _buf, FFTW_ESTIMATE);
#else // !FFTW
_buf = new float [_len];
_tmp = new float [_len];
_fftobj = new FFTReal(_len);
#endif // !FFTW
}
Offt::~Offt()
{
#ifdef FFTW
if (_plan_r2c)
fftwf_destroy_plan(_plan_r2c);
if (_plan_c2r)
fftwf_destroy_plan(_plan_c2r);
fftwf_free(_buf);
fftwf_free(_cbuf);
#else // !FFTW
delete [] _buf;
delete [] _tmp;
delete _fftobj;
#endif // !FFTW
}
#ifdef FFTW
void Offt::r2c()
{
fftwf_execute(_plan_r2c);
// _cbuf has complex result in real,imaginary pairs from DC to Nyquist;
// copy into _buf while reordering to...
// re(0), re(len/2), re(1), im(1), re(2), im(2)...re(len/2-1), im(len/2-1)
// and normalizing by 1 / fftlen.
float scale = 1.0 / _len;
int last = _len / 2;
_buf[0] = _cbuf[0][0] * scale;
_buf[1] = _cbuf[last][0] * scale;
for (int i = 1; i < last; i++) {
_buf[i + i] = _cbuf[i][0] * scale;
_buf[i + i + 1] = _cbuf[i][1] * scale;
}
}
void Offt::c2r()
{
// _buf has complex data; copy into _cbuf while reordering from...
// re(0), re(len/2), re(1), im(1), re(2), im(2)...re(len/2-1), im(len/2-1)
// to real,imaginary pairs from DC to Nyquist;
int last = _len / 2;
_cbuf[0][0] = _buf[0];
_cbuf[last][0] = _buf[1];
for (int i = 1; i < last; i++) {
_cbuf[i][0] = _buf[i + i];
_cbuf[i][1] = _buf[i + i + 1];
}
fftwf_execute(_plan_c2r);
}
#else // !FFTW
void Offt::r2c()
{
_fftobj->do_fft(_tmp, _buf);
// _tmp has complex result; copy into _buf while reordering from...
// re(0), re(1), re(2)...re(len/2), im(1), im(2)...im(len/2-1)
// to...
// re(0), re(len/2), re(1), im(1), re(2), im(2)...re(len/2-1), im(len/2-1)
// and normalizing by 1 / fftlen.
float scale = 1.0 / _len;
int j = _len / 2;
_buf[0] = _tmp[0] * scale;
_buf[1] = _tmp[j] * scale;
#if 0
for (int i = 1; i < j; i++) {
_buf[i + i] = _tmp[i] * scale; // real
_buf[i + i + 1] = _tmp[j + i] * scale; // imag
}
#else
int i = j - 1;
float *bp = &_buf[_len - 1];
float *tp = &_tmp[j + i];
do {
*bp-- = *tp-- * scale; // imag
*bp-- = _tmp[i--] * scale; // real
} while (i > 0);
#endif
}
void Offt::c2r()
{
// _buf has complex data; copy into _tmp while reordering from...
// re(0), re(len/2), re(1), im(1), re(2), im(2)...re(len/2-1), im(len/2-1)
// to...
// re(0), re(1), re(2)...re(len/2), im(1), im(2)...im(len/2-1)
int j = _len / 2;
_tmp[0] = _buf[0];
_tmp[j] = _buf[1];
#if 0
for (int i = 1; i < j; i++) {
_tmp[i] = _buf[i + i]; // real
_tmp[j + i] = _buf[i + i + 1]; // imag
}
#else
int i = j - 1;
float *bp = &_buf[_len - 1];
float *tp = &_tmp[j + i];
do {
*tp-- = *bp--; // imag
_tmp[i--] = *bp--; // real
} while (i > 0);
#endif
_fftobj->do_ifft(_tmp, _buf);
// _buf now holds real output
}
#endif // !FFTW
#include <stdio.h>
void Offt::printbuf(float *buf, char *msg)
{
printf("\n%s\n", msg);
for (int i = 0; i < _len; i++)
printf("\t[%d] = %f\n", i, buf[i]);
}
<commit_msg>Fix init typo.<commit_after>/* RTcmix - Copyright (C) 2005 The RTcmix Development Team
See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include <Offt.h>
#ifndef FFTW
#include <FFTReal.h>
#endif
Offt::Offt(int fftsize, unsigned int flags)
: _len(fftsize)
{
#ifdef FFTW
_plan_r2c = _plan_c2r = NULL;
_buf = (float *) fftwf_malloc(sizeof(float) * _len);
int csize = sizeof(fftwf_complex) * ((_len / 2) + 1);
_cbuf = (fftwf_complex *) fftwf_malloc(csize);
if (flags & kRealToComplex)
_plan_r2c = fftwf_plan_dft_r2c_1d(_len, _buf, _cbuf, FFTW_ESTIMATE);
if (flags & kComplexToReal)
_plan_c2r = fftwf_plan_dft_c2r_1d(_len, _cbuf, _buf, FFTW_ESTIMATE);
#else // !FFTW
_buf = new float [_len];
_tmp = new float [_len];
_fftobj = new FFTReal(_len);
#endif // !FFTW
}
Offt::~Offt()
{
#ifdef FFTW
if (_plan_r2c)
fftwf_destroy_plan(_plan_r2c);
if (_plan_c2r)
fftwf_destroy_plan(_plan_c2r);
fftwf_free(_buf);
fftwf_free(_cbuf);
#else // !FFTW
delete [] _buf;
delete [] _tmp;
delete _fftobj;
#endif // !FFTW
}
#ifdef FFTW
void Offt::r2c()
{
fftwf_execute(_plan_r2c);
// _cbuf has complex result in real,imaginary pairs from DC to Nyquist;
// copy into _buf while reordering to...
// re(0), re(len/2), re(1), im(1), re(2), im(2)...re(len/2-1), im(len/2-1)
// and normalizing by 1 / fftlen.
float scale = 1.0 / _len;
int last = _len / 2;
_buf[0] = _cbuf[0][0] * scale;
_buf[1] = _cbuf[last][0] * scale;
for (int i = 1; i < last; i++) {
_buf[i + i] = _cbuf[i][0] * scale;
_buf[i + i + 1] = _cbuf[i][1] * scale;
}
}
void Offt::c2r()
{
// _buf has complex data; copy into _cbuf while reordering from...
// re(0), re(len/2), re(1), im(1), re(2), im(2)...re(len/2-1), im(len/2-1)
// to real,imaginary pairs from DC to Nyquist;
int last = _len / 2;
_cbuf[0][0] = _buf[0];
_cbuf[last][0] = _buf[1];
for (int i = 1; i < last; i++) {
_cbuf[i][0] = _buf[i + i];
_cbuf[i][1] = _buf[i + i + 1];
}
fftwf_execute(_plan_c2r);
}
#else // !FFTW
void Offt::r2c()
{
_fftobj->do_fft(_tmp, _buf);
// _tmp has complex result; copy into _buf while reordering from...
// re(0), re(1), re(2)...re(len/2), im(1), im(2)...im(len/2-1)
// to...
// re(0), re(len/2), re(1), im(1), re(2), im(2)...re(len/2-1), im(len/2-1)
// and normalizing by 1 / fftlen.
float scale = 1.0 / _len;
int j = _len / 2;
_buf[0] = _tmp[0] * scale;
_buf[1] = _tmp[j] * scale;
#if 0
for (int i = 1; i < j; i++) {
_buf[i + i] = _tmp[i] * scale; // real
_buf[i + i + 1] = _tmp[j + i] * scale; // imag
}
#else
int i = j - 1;
float *bp = &_buf[_len - 1];
float *tp = &_tmp[j + i];
do {
*bp-- = *tp-- * scale; // imag
*bp-- = _tmp[i--] * scale; // real
} while (i > 0);
#endif
}
void Offt::c2r()
{
// _buf has complex data; copy into _tmp while reordering from...
// re(0), re(len/2), re(1), im(1), re(2), im(2)...re(len/2-1), im(len/2-1)
// to...
// re(0), re(1), re(2)...re(len/2), im(1), im(2)...im(len/2-1)
int j = _len / 2;
_tmp[0] = _buf[0];
_tmp[j] = _buf[1];
#if 0
for (int i = 1; i < j; i++) {
_tmp[i] = _buf[i + i]; // real
_tmp[j + i] = _buf[i + i + 1]; // imag
}
#else
int i = j - 1;
float *bp = &_buf[_len - 1];
float *tp = &_tmp[j + i];
do {
*tp-- = *bp--; // imag
_tmp[i--] = *bp--; // real
} while (i > 0);
#endif
_fftobj->do_ifft(_tmp, _buf);
// _buf now holds real output
}
#endif // !FFTW
#include <stdio.h>
void Offt::printbuf(float *buf, char *msg)
{
printf("\n%s\n", msg);
for (int i = 0; i < _len; i++)
printf("\t[%d] = %f\n", i, buf[i]);
}
<|endoftext|> |
<commit_before>#include "lexer.h"
#include <node.h>
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>
#include <string.h>
/* Type Definitions */
#define COMMENTTYPE 0x01
#define KEYTYPE 0x02
#define STRINGTYPE 0x03
/* State definitions */
#define NONESTATE 0x01
#define COMMENTSTATE 0x02
#define KEYSTATE 0x03
#define STRINGSTATE 0x04
using namespace v8;
char *v8StrToCharStar(v8::Local<v8::Value> value) {
v8::String::Utf8Value string(value);
char *str = (char *) malloc(string.length() + 1);
strcpy(str, *string);
return str;
}
void parse(const FunctionCallbackInfo<Value>& args) {
bool escaped = false;
char chr;
char quote;
int i;
int ntokens;
int state = NONESTATE;
struct Token * tokens;
char * po_string;
char * buffer;
buffer = NULL;
tokens = NULL;
ntokens = 0;
quote = '\0';
Isolate* isolate = Isolate::GetCurrent();
Local<Object> catalog_obj;
Local<String> catalog_str;
HandleScope scope(isolate);
if (args.Length() < 1) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Takes two arguments")));
return;
}
if (!args[0]->IsString()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
catalog_obj = Object::New(isolate);
po_string = v8StrToCharStar(args[0]);
catalog_str = args[0]->ToString();
for (i = 0; i < catalog_str->Length(); i++) {
chr = po_string[i];
switch(state) {
case NONESTATE:
if (chr == '\'' || chr == '"') {
state = STRINGSTATE;
quote = chr;
} else if (chr == '#') {
state = COMMENTSTATE;
tokens = append(tokens, ntokens, COMMENTTYPE, '\0', NULL);
++ntokens;
} else if (!isspace(chr)) {
state = KEYSTATE;
buffer = append_to_buffer(buffer, chr);
} else if (isspace(chr) && buffer != NULL) {
tokens = append(tokens, ntokens, KEYTYPE, '\0', buffer);
free(buffer);
buffer = NULL;
++ntokens;
}
break;
case COMMENTSTATE:
if (chr == '\n') {
tokens = append(tokens, ntokens, COMMENTTYPE, '\0', buffer);
state = NONESTATE;
free(buffer);
buffer = NULL;
++ntokens;
} else if (chr != '\r') {
buffer = append_to_buffer(buffer, chr);
}
break;
case STRINGSTATE:
if(escaped) {
switch(chr) {
case 't':
buffer = append_to_buffer(buffer, '\t');
break;
case 'n':
buffer = append_to_buffer(buffer, '\n');
break;
case 'r':
buffer = append_to_buffer(buffer, '\r');
break;
}
escaped = false;
} else {
if(chr == quote) {
tokens = append(tokens, ntokens, STRINGTYPE, quote, buffer);
free(buffer);
buffer = NULL;
state = NONESTATE;
++ntokens;
} else if (chr == '\\') {
escaped = true;
break;
} else {
buffer = append_to_buffer(buffer, chr);
}
escaped = false;
}
break;
case KEYSTATE:
if(isalpha(chr) || chr == '-' || chr == '[' || chr == ']') {
buffer = append_to_buffer(buffer, chr);
} else {
state = NONESTATE;
--i;
}
break;
}
}
args.GetReturnValue().Set(catalog_obj);
print_token_array(tokens, ntokens);
free_token_array(tokens, ntokens);
free(po_string);
free(buffer);
}
void Init(Handle<Object> exports) {
NODE_SET_METHOD(exports, "parse", parse);
}
NODE_MODULE(gettextlexer, Init)
<commit_msg>Remove unused include<commit_after>#include "lexer.h"
#include <node.h>
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string.h>
/* Type Definitions */
#define COMMENTTYPE 0x01
#define KEYTYPE 0x02
#define STRINGTYPE 0x03
/* State definitions */
#define NONESTATE 0x01
#define COMMENTSTATE 0x02
#define KEYSTATE 0x03
#define STRINGSTATE 0x04
using namespace v8;
char *v8StrToCharStar(v8::Local<v8::Value> value) {
v8::String::Utf8Value string(value);
char *str = (char *) malloc(string.length() + 1);
strcpy(str, *string);
return str;
}
void parse(const FunctionCallbackInfo<Value>& args) {
bool escaped = false;
char chr;
char quote;
int i;
int ntokens;
int state = NONESTATE;
struct Token * tokens;
char * po_string;
char * buffer;
buffer = NULL;
tokens = NULL;
ntokens = 0;
quote = '\0';
Isolate* isolate = Isolate::GetCurrent();
Local<Object> catalog_obj;
Local<String> catalog_str;
HandleScope scope(isolate);
if (args.Length() < 1) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Takes two arguments")));
return;
}
if (!args[0]->IsString()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument must be a string")));
return;
}
catalog_obj = Object::New(isolate);
po_string = v8StrToCharStar(args[0]);
catalog_str = args[0]->ToString();
for (i = 0; i < catalog_str->Length(); i++) {
chr = po_string[i];
switch(state) {
case NONESTATE:
if (chr == '\'' || chr == '"') {
state = STRINGSTATE;
quote = chr;
} else if (chr == '#') {
state = COMMENTSTATE;
tokens = append(tokens, ntokens, COMMENTTYPE, '\0', NULL);
++ntokens;
} else if (!isspace(chr)) {
state = KEYSTATE;
buffer = append_to_buffer(buffer, chr);
} else if (isspace(chr) && buffer != NULL) {
tokens = append(tokens, ntokens, KEYTYPE, '\0', buffer);
free(buffer);
buffer = NULL;
++ntokens;
}
break;
case COMMENTSTATE:
if (chr == '\n') {
tokens = append(tokens, ntokens, COMMENTTYPE, '\0', buffer);
state = NONESTATE;
free(buffer);
buffer = NULL;
++ntokens;
} else if (chr != '\r') {
buffer = append_to_buffer(buffer, chr);
}
break;
case STRINGSTATE:
if(escaped) {
switch(chr) {
case 't':
buffer = append_to_buffer(buffer, '\t');
break;
case 'n':
buffer = append_to_buffer(buffer, '\n');
break;
case 'r':
buffer = append_to_buffer(buffer, '\r');
break;
}
escaped = false;
} else {
if(chr == quote) {
tokens = append(tokens, ntokens, STRINGTYPE, quote, buffer);
free(buffer);
buffer = NULL;
state = NONESTATE;
++ntokens;
} else if (chr == '\\') {
escaped = true;
break;
} else {
buffer = append_to_buffer(buffer, chr);
}
escaped = false;
}
break;
case KEYSTATE:
if(isalpha(chr) || chr == '-' || chr == '[' || chr == ']') {
buffer = append_to_buffer(buffer, chr);
} else {
state = NONESTATE;
--i;
}
break;
}
}
args.GetReturnValue().Set(catalog_obj);
print_token_array(tokens, ntokens);
free_token_array(tokens, ntokens);
free(po_string);
free(buffer);
}
void Init(Handle<Object> exports) {
NODE_SET_METHOD(exports, "parse", parse);
}
NODE_MODULE(gettextlexer, Init)
<|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 "gfx/font.h"
#include <windows.h>
#include <math.h>
#include <algorithm>
#include "base/logging.h"
#include "base/string_util.h"
#include "base/win_util.h"
#include "gfx/canvas_skia.h"
namespace gfx {
// static
Font::HFontRef* Font::base_font_ref_;
// static
Font::AdjustFontCallback Font::adjust_font_callback = NULL;
Font::GetMinimumFontSizeCallback Font::get_minimum_font_size_callback = NULL;
// If the tmWeight field of a TEXTMETRIC structure has a value >= this, the
// font is bold.
static const int kTextMetricWeightBold = 700;
// Returns either minimum font allowed for a current locale or
// lf_height + size_delta value.
static int AdjustFontSize(int lf_height, int size_delta) {
if (lf_height < 0) {
lf_height -= size_delta;
} else {
lf_height += size_delta;
}
int min_font_size = 0;
if (Font::get_minimum_font_size_callback)
min_font_size = Font::get_minimum_font_size_callback();
// Make sure lf_height is not smaller than allowed min font size for current
// locale.
if (abs(lf_height) < min_font_size) {
return lf_height < 0 ? -min_font_size : min_font_size;
} else {
return lf_height;
}
}
//
// Font
//
Font::Font()
: font_ref_(GetBaseFontRef()) {
}
int Font::height() const {
return font_ref_->height();
}
int Font::baseline() const {
return font_ref_->baseline();
}
int Font::ave_char_width() const {
return font_ref_->ave_char_width();
}
int Font::GetExpectedTextWidth(int length) const {
return length * std::min(font_ref_->dlu_base_x(), ave_char_width());
}
int Font::style() const {
return font_ref_->style();
}
NativeFont Font::nativeFont() const {
return hfont();
}
// static
Font Font::CreateFont(HFONT font) {
DCHECK(font);
LOGFONT font_info;
GetObject(font, sizeof(LOGFONT), &font_info);
return Font(CreateHFontRef(CreateFontIndirect(&font_info)));
}
Font Font::CreateFont(const std::wstring& font_name, int font_size) {
HDC hdc = GetDC(NULL);
long lf_height = -MulDiv(font_size, GetDeviceCaps(hdc, LOGPIXELSY), 72);
ReleaseDC(NULL, hdc);
HFONT hf = ::CreateFont(lf_height, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
font_name.c_str());
return Font::CreateFont(hf);
}
// static
Font::HFontRef* Font::GetBaseFontRef() {
if (base_font_ref_ == NULL) {
NONCLIENTMETRICS metrics;
win_util::GetNonClientMetrics(&metrics);
if (adjust_font_callback)
adjust_font_callback(&metrics.lfMessageFont);
metrics.lfMessageFont.lfHeight =
AdjustFontSize(metrics.lfMessageFont.lfHeight, 0);
HFONT font = CreateFontIndirect(&metrics.lfMessageFont);
DLOG_ASSERT(font);
base_font_ref_ = Font::CreateHFontRef(font);
// base_font_ref_ is global, up the ref count so it's never deleted.
base_font_ref_->AddRef();
}
return base_font_ref_;
}
const std::wstring& Font::FontName() const {
return font_ref_->font_name();
}
int Font::FontSize() {
LOGFONT font_info;
GetObject(hfont(), sizeof(LOGFONT), &font_info);
long lf_height = font_info.lfHeight;
HDC hdc = GetDC(NULL);
int device_caps = GetDeviceCaps(hdc, LOGPIXELSY);
int font_size = 0;
if (device_caps != 0) {
float font_size_float = -static_cast<float>(lf_height)*72/device_caps;
font_size = static_cast<int>(::ceil(font_size_float - 0.5));
}
ReleaseDC(NULL, hdc);
return font_size;
}
Font::HFontRef::HFontRef(HFONT hfont,
int height,
int baseline,
int ave_char_width,
int style,
int dlu_base_x)
: hfont_(hfont),
height_(height),
baseline_(baseline),
ave_char_width_(ave_char_width),
style_(style),
dlu_base_x_(dlu_base_x) {
DLOG_ASSERT(hfont);
LOGFONT font_info;
GetObject(hfont_, sizeof(LOGFONT), &font_info);
font_name_ = std::wstring(font_info.lfFaceName);
}
Font::HFontRef::~HFontRef() {
DeleteObject(hfont_);
}
Font Font::DeriveFont(int size_delta, int style) const {
LOGFONT font_info;
GetObject(hfont(), sizeof(LOGFONT), &font_info);
font_info.lfHeight = AdjustFontSize(font_info.lfHeight, size_delta);
font_info.lfUnderline = ((style & UNDERLINED) == UNDERLINED);
font_info.lfItalic = ((style & ITALIC) == ITALIC);
font_info.lfWeight = (style & BOLD) ? FW_BOLD : FW_NORMAL;
HFONT hfont = CreateFontIndirect(&font_info);
return Font(CreateHFontRef(hfont));
}
int Font::GetStringWidth(const std::wstring& text) const {
int width = 0;
HDC dc = GetDC(NULL);
HFONT previous_font = static_cast<HFONT>(SelectObject(dc, hfont()));
SIZE size;
if (GetTextExtentPoint32(dc, text.c_str(), static_cast<int>(text.size()),
&size)) {
width = size.cx;
} else {
width = 0;
}
SelectObject(dc, previous_font);
ReleaseDC(NULL, dc);
return width;
}
Font::HFontRef* Font::CreateHFontRef(HFONT font) {
TEXTMETRIC font_metrics;
HDC screen_dc = GetDC(NULL);
HFONT previous_font = static_cast<HFONT>(SelectObject(screen_dc, font));
int last_map_mode = SetMapMode(screen_dc, MM_TEXT);
GetTextMetrics(screen_dc, &font_metrics);
// Yes, this is how Microsoft recommends calculating the dialog unit
// conversions.
SIZE ave_text_size;
GetTextExtentPoint32(screen_dc,
L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
52, &ave_text_size);
const int dlu_base_x = (ave_text_size.cx / 26 + 1) / 2;
// To avoid the DC referencing font_handle_, select the previous font.
SelectObject(screen_dc, previous_font);
SetMapMode(screen_dc, last_map_mode);
ReleaseDC(NULL, screen_dc);
const int height = std::max(1, static_cast<int>(font_metrics.tmHeight));
const int baseline = std::max(1, static_cast<int>(font_metrics.tmAscent));
const int ave_char_width =
std::max(1, static_cast<int>(font_metrics.tmAveCharWidth));
int style = 0;
if (font_metrics.tmItalic) {
style |= Font::ITALIC;
}
if (font_metrics.tmUnderlined) {
style |= Font::UNDERLINED;
}
if (font_metrics.tmWeight >= kTextMetricWeightBold) {
style |= Font::BOLD;
}
return new HFontRef(font, height, baseline, ave_char_width, style,
dlu_base_x);
}
} // namespace gfx
<commit_msg>Revert 52441 - Revert Win specific elements of 46492 to look for perf impact<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 "gfx/font.h"
#include <windows.h>
#include <math.h>
#include <algorithm>
#include "base/logging.h"
#include "base/string_util.h"
#include "base/win_util.h"
#include "gfx/canvas_skia.h"
namespace gfx {
// static
Font::HFontRef* Font::base_font_ref_;
// static
Font::AdjustFontCallback Font::adjust_font_callback = NULL;
Font::GetMinimumFontSizeCallback Font::get_minimum_font_size_callback = NULL;
// If the tmWeight field of a TEXTMETRIC structure has a value >= this, the
// font is bold.
static const int kTextMetricWeightBold = 700;
// Returns either minimum font allowed for a current locale or
// lf_height + size_delta value.
static int AdjustFontSize(int lf_height, int size_delta) {
if (lf_height < 0) {
lf_height -= size_delta;
} else {
lf_height += size_delta;
}
int min_font_size = 0;
if (Font::get_minimum_font_size_callback)
min_font_size = Font::get_minimum_font_size_callback();
// Make sure lf_height is not smaller than allowed min font size for current
// locale.
if (abs(lf_height) < min_font_size) {
return lf_height < 0 ? -min_font_size : min_font_size;
} else {
return lf_height;
}
}
//
// Font
//
Font::Font()
: font_ref_(GetBaseFontRef()) {
}
int Font::height() const {
return font_ref_->height();
}
int Font::baseline() const {
return font_ref_->baseline();
}
int Font::ave_char_width() const {
return font_ref_->ave_char_width();
}
int Font::GetExpectedTextWidth(int length) const {
return length * std::min(font_ref_->dlu_base_x(), ave_char_width());
}
int Font::style() const {
return font_ref_->style();
}
NativeFont Font::nativeFont() const {
return hfont();
}
// static
Font Font::CreateFont(HFONT font) {
DCHECK(font);
LOGFONT font_info;
GetObject(font, sizeof(LOGFONT), &font_info);
return Font(CreateHFontRef(CreateFontIndirect(&font_info)));
}
Font Font::CreateFont(const std::wstring& font_name, int font_size) {
HDC hdc = GetDC(NULL);
long lf_height = -MulDiv(font_size, GetDeviceCaps(hdc, LOGPIXELSY), 72);
ReleaseDC(NULL, hdc);
HFONT hf = ::CreateFont(lf_height, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
font_name.c_str());
return Font::CreateFont(hf);
}
// static
Font::HFontRef* Font::GetBaseFontRef() {
if (base_font_ref_ == NULL) {
NONCLIENTMETRICS metrics;
win_util::GetNonClientMetrics(&metrics);
if (adjust_font_callback)
adjust_font_callback(&metrics.lfMessageFont);
metrics.lfMessageFont.lfHeight =
AdjustFontSize(metrics.lfMessageFont.lfHeight, 0);
HFONT font = CreateFontIndirect(&metrics.lfMessageFont);
DLOG_ASSERT(font);
base_font_ref_ = Font::CreateHFontRef(font);
// base_font_ref_ is global, up the ref count so it's never deleted.
base_font_ref_->AddRef();
}
return base_font_ref_;
}
const std::wstring& Font::FontName() const {
return font_ref_->font_name();
}
int Font::FontSize() {
LOGFONT font_info;
GetObject(hfont(), sizeof(LOGFONT), &font_info);
long lf_height = font_info.lfHeight;
HDC hdc = GetDC(NULL);
int device_caps = GetDeviceCaps(hdc, LOGPIXELSY);
int font_size = 0;
if (device_caps != 0) {
float font_size_float = -static_cast<float>(lf_height)*72/device_caps;
font_size = static_cast<int>(::ceil(font_size_float - 0.5));
}
ReleaseDC(NULL, hdc);
return font_size;
}
Font::HFontRef::HFontRef(HFONT hfont,
int height,
int baseline,
int ave_char_width,
int style,
int dlu_base_x)
: hfont_(hfont),
height_(height),
baseline_(baseline),
ave_char_width_(ave_char_width),
style_(style),
dlu_base_x_(dlu_base_x) {
DLOG_ASSERT(hfont);
LOGFONT font_info;
GetObject(hfont_, sizeof(LOGFONT), &font_info);
font_name_ = std::wstring(font_info.lfFaceName);
}
Font::HFontRef::~HFontRef() {
DeleteObject(hfont_);
}
Font Font::DeriveFont(int size_delta, int style) const {
LOGFONT font_info;
GetObject(hfont(), sizeof(LOGFONT), &font_info);
font_info.lfHeight = AdjustFontSize(font_info.lfHeight, size_delta);
font_info.lfUnderline = ((style & UNDERLINED) == UNDERLINED);
font_info.lfItalic = ((style & ITALIC) == ITALIC);
font_info.lfWeight = (style & BOLD) ? FW_BOLD : FW_NORMAL;
HFONT hfont = CreateFontIndirect(&font_info);
return Font(CreateHFontRef(hfont));
}
int Font::GetStringWidth(const std::wstring& text) const {
int width = 0, height = 0;
CanvasSkia::SizeStringInt(text, *this, &width, &height,
gfx::Canvas::NO_ELLIPSIS);
return width;
}
Font::HFontRef* Font::CreateHFontRef(HFONT font) {
TEXTMETRIC font_metrics;
HDC screen_dc = GetDC(NULL);
HFONT previous_font = static_cast<HFONT>(SelectObject(screen_dc, font));
int last_map_mode = SetMapMode(screen_dc, MM_TEXT);
GetTextMetrics(screen_dc, &font_metrics);
// Yes, this is how Microsoft recommends calculating the dialog unit
// conversions.
SIZE ave_text_size;
GetTextExtentPoint32(screen_dc,
L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
52, &ave_text_size);
const int dlu_base_x = (ave_text_size.cx / 26 + 1) / 2;
// To avoid the DC referencing font_handle_, select the previous font.
SelectObject(screen_dc, previous_font);
SetMapMode(screen_dc, last_map_mode);
ReleaseDC(NULL, screen_dc);
const int height = std::max(1, static_cast<int>(font_metrics.tmHeight));
const int baseline = std::max(1, static_cast<int>(font_metrics.tmAscent));
const int ave_char_width =
std::max(1, static_cast<int>(font_metrics.tmAveCharWidth));
int style = 0;
if (font_metrics.tmItalic) {
style |= Font::ITALIC;
}
if (font_metrics.tmUnderlined) {
style |= Font::UNDERLINED;
}
if (font_metrics.tmWeight >= kTextMetricWeightBold) {
style |= Font::BOLD;
}
return new HFontRef(font, height, baseline, ave_char_width, style,
dlu_base_x);
}
} // namespace gfx
<|endoftext|> |
<commit_before>#include "qgeotilefetchergooglemaps.h"
#include "qgeomapreplygooglemaps.h"
#include "qgeotiledmapgooglemaps.h"
#include "qgeotiledmappingmanagerenginegooglemaps.h"
#include <QtLocation/private/qgeotilespec_p.h>
#include <QDebug>
#include <QSize>
#include <QDir>
#include <QUrl>
#include <QUrlQuery>
#include <QTime>
#include <QNetworkProxy>
#include <math.h>
#include <map>
QT_BEGIN_NAMESPACE
namespace
{
double tilex2long(int x, int z)
{
return (double)x / pow(2.0, z) * 360.0 - 180.0;
}
double tiley2lat(int y, int z)
{
double n = M_PI - 2.0 * M_PI * (double)y / pow(2.0, z);
return 180.0 / M_PI * atan(0.5 * (exp(n) - exp(-n)));
}
QGeoCoordinate xyzToCoord(int x, int y, int z)
{
return QGeoCoordinate(tiley2lat(y, z), tilex2long(x, z), 0.0);
}
QString sizeToStr(const QSize &size)
{
if (size.height() >= 512 || size.width() >= 512)
return QStringLiteral("512x512");
else if (size.height() >= 256 || size.width() >= 256)
return QStringLiteral("256x256");
else
return QStringLiteral("128x128"); // 128 pixel tiles are deprecated.
}
QGeoCoordinate tileCenter(const QGeoTileSpec &spec) {
int viewX0, viewY0, viewX1, viewY1;
viewX0 = spec.x();
viewY0 = spec.y();
viewX1 = spec.x() + 1;
viewY1 = spec.y() + 1;
QGeoRectangle viewport(xyzToCoord(viewX0, viewY0, spec.zoom()), xyzToCoord(viewX1, viewY1, spec.zoom()));
return viewport.center();
}
QString coordToStr(const QGeoCoordinate &coord)
{
//its important to have precision 8. otherwise tile will not be fitted correctly
char format = 'g';
return QString::number(coord.latitude(), format, 8) + "," + QString::number(coord.longitude(), format, 8);
}
int _getServerNum(int x, int y, int max)
{
return (x + 2 * y) % max;
}
}
QGeoTileFetcherGooglemaps::QGeoTileFetcherGooglemaps(const QVariantMap ¶meters,
QGeoTiledMappingManagerEngineGooglemaps *engine,
const QSize &tileSize)
: QGeoTileFetcher(engine),
m_networkManager(new QNetworkAccessManager(this)),
m_engineGooglemaps(engine),
m_tileSize(tileSize)
{
m_apiKey = parameters.value(QStringLiteral("googlemaps.maps.apikey")).toString();
m_signature = parameters.value(QStringLiteral("googlemaps.maps.signature")).toString();
m_client = parameters.value(QStringLiteral("googlemaps.maps.client")).toString();
m_baseUri = QStringLiteral("http://maps.googleapis.com/maps/api/staticmap");
if (parameters.contains(QStringLiteral("googlemaps.useragent")))
_userAgent = parameters.value(QStringLiteral("googlemaps.useragent")).toString().toLatin1();
else
_userAgent = "Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0";
QStringList langs = QLocale::system().uiLanguages();
if (langs.length() > 0) {
_language = langs[0];
}
// Google version strings
_versionGoogleMap = "m@336";
_versionGoogleSatellite = "194";
_versionGoogleLabels = "h@336";
_versionGoogleTerrain = "t@132,r@336";
_secGoogleWord = "Galileo";
_tryCorrectGoogleVersions(m_networkManager);
netRequest.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);
netRequest.setRawHeader("Referrer", "http://maps.google.com/");
netRequest.setRawHeader("Accept", "*/*");
netRequest.setRawHeader("User-Agent", _userAgent);
}
QGeoTileFetcherGooglemaps::~QGeoTileFetcherGooglemaps()
{
}
QGeoTiledMapReply *QGeoTileFetcherGooglemaps::getTileImage(const QGeoTileSpec &spec)
{
if (m_apiKey.isEmpty()) {
QGeoTiledMapReply *reply = new QGeoTiledMapReply(QGeoTiledMapReply::UnknownError, "Set googlemaps.maps.apikey with google maps application key, supporting static maps", this);
emit tileError(spec, reply->errorString());
return reply;
}
QString surl = _getURL(spec.mapId(), spec.x(), spec.y(), spec.zoom());
QUrl url(surl);
//qDebug() << "maps url:" << url;
netRequest.setUrl(url); // The extra pair of parens disambiguates this from a function declaration
QNetworkReply *netReply = m_networkManager->get(netRequest);
QGeoTiledMapReply *mapReply = new QGeoMapReplyGooglemaps(netReply, spec);
return mapReply;
}
void QGeoTileFetcherGooglemaps::_getSecGoogleWords(int x, int y, QString &sec1, QString &sec2)
{
sec1 = ""; // after &x=...
sec2 = ""; // after &zoom=...
int seclen = ((x * 3) + y) % 8;
sec2 = _secGoogleWord.left(seclen);
if (y >= 10000 && y < 100000) {
sec1 = "&s=";
}
}
QString QGeoTileFetcherGooglemaps::_getURL(int type, int x, int y, int zoom)
{
switch (type) {
case 0:
case 1:
{
// http://mt1.google.com/vt/lyrs=m
QString server = "mt";
QString request = "vt";
QString sec1 = ""; // after &x=...
QString sec2 = ""; // after &zoom=...
_getSecGoogleWords(x, y, sec1, sec2);
//_tryCorrectGoogleVersions(networkManager);
return QString("http://%1%2.google.com/%3/lyrs=%4&hl=%5&x=%6%7&y=%8&z=%9&s=%10").arg(server).arg(_getServerNum(x, y, 4)).arg(request).arg(_versionGoogleMap).arg(_language).arg(x).arg(sec1).arg(y).arg(zoom).arg(sec2);
}
break;
case 2:
{
// http://mt1.google.com/vt/lyrs=s
QString server = "khm";
QString request = "kh";
QString sec1 = ""; // after &x=...
QString sec2 = ""; // after &zoom=...
_getSecGoogleWords(x, y, sec1, sec2);
//_tryCorrectGoogleVersions(networkManager);
return QString("http://%1%2.google.com/%3/v=%4&hl=%5&x=%6%7&y=%8&z=%9&s=%10").arg(server).arg(_getServerNum(x, y, 4)).arg(request).arg(_versionGoogleSatellite).arg(_language).arg(x).arg(sec1).arg(y).arg(zoom).arg(sec2);
}
break;
case 3:
{
QString server = "mts";
QString request = "vt";
QString sec1 = ""; // after &x=...
QString sec2 = ""; // after &zoom=...
_getSecGoogleWords(x, y, sec1, sec2);
//_tryCorrectGoogleVersions(networkManager);
return QString("http://%1%2.google.com/%3/lyrs=%4&hl=%5&x=%6%7&y=%8&z=%9&s=%10").arg(server).arg(_getServerNum(x, y, 4)).arg(request).arg(_versionGoogleLabels).arg(_language).arg(x).arg(sec1).arg(y).arg(zoom).arg(sec2);
}
break;
case 4:
{
QString server = "mt";
QString request = "vt";
QString sec1 = ""; // after &x=...
QString sec2 = ""; // after &zoom=...
_getSecGoogleWords(x, y, sec1, sec2);
//_tryCorrectGoogleVersions(networkManager);
return QString("http://%1%2.google.com/%3/v=%4&hl=%5&x=%6%7&y=%8&z=%9&s=%10").arg(server).arg(_getServerNum(x, y, 4)).arg(request).arg(_versionGoogleTerrain).arg(_language).arg(x).arg(sec1).arg(y).arg(zoom).arg(sec2);
}
break;
}
return "";
}
void QGeoTileFetcherGooglemaps::_networkReplyError(QNetworkReply::NetworkError error)
{
qWarning() << "Could not connect to google maps. Error:" << error;
if(_googleReply)
{
_googleReply->deleteLater();
_googleReply = NULL;
}
}
void QGeoTileFetcherGooglemaps::_replyDestroyed()
{
_googleReply = NULL;
}
void QGeoTileFetcherGooglemaps::_googleVersionCompleted()
{
if (!_googleReply || (_googleReply->error() != QNetworkReply::NoError)) {
qDebug() << "Error collecting Google maps version info";
return;
}
QString html = QString(_googleReply->readAll());
QRegExp reg("\"*http://mt0.google.com/vt/lyrs=m@(\\d*)",Qt::CaseInsensitive);
if (reg.indexIn(html) != -1) {
QStringList gc = reg.capturedTexts();
_versionGoogleMap = QString("m@%1").arg(gc[1]);
}
reg = QRegExp("\"*http://mt0.google.com/vt/lyrs=h@(\\d*)",Qt::CaseInsensitive);
if (reg.indexIn(html) != -1) {
QStringList gc = reg.capturedTexts();
_versionGoogleLabels = QString("h@%1").arg(gc[1]);
}
reg = QRegExp("\"*http://khm\\D?\\d.google.com/kh/v=(\\d*)",Qt::CaseInsensitive);
if (reg.indexIn(html) != -1) {
QStringList gc = reg.capturedTexts();
_versionGoogleSatellite = gc[1];
}
reg = QRegExp("\"*http://mt0.google.com/vt/lyrs=t@(\\d*),r@(\\d*)",Qt::CaseInsensitive);
if (reg.indexIn(html) != -1) {
QStringList gc = reg.capturedTexts();
_versionGoogleTerrain = QString("t@%1,r@%2").arg(gc[1]).arg(gc[2]);
}
_googleReply->deleteLater();
_googleReply = NULL;
}
void QGeoTileFetcherGooglemaps::_tryCorrectGoogleVersions(QNetworkAccessManager* networkManager)
{
QMutexLocker locker(&_googleVersionMutex);
if (_googleVersionRetrieved) {
return;
}
_googleVersionRetrieved = true;
if(networkManager)
{
QNetworkRequest qheader;
QNetworkProxy proxy = networkManager->proxy();
QNetworkProxy tProxy;
tProxy.setType(QNetworkProxy::NoProxy);
networkManager->setProxy(tProxy);
QString url = "http://maps.google.com/maps";
qheader.setUrl(QUrl(url));
QByteArray ua;
ua.append(_userAgent);
qheader.setRawHeader("User-Agent", ua);
_googleReply = networkManager->get(qheader);
connect(_googleReply, &QNetworkReply::finished, this, &QGeoTileFetcherGooglemaps::_googleVersionCompleted);
connect(_googleReply, &QNetworkReply::destroyed, this, &QGeoTileFetcherGooglemaps::_replyDestroyed);
connect(_googleReply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error),
this, &QGeoTileFetcherGooglemaps::_networkReplyError);
networkManager->setProxy(proxy);
}
}
QT_END_NAMESPACE
<commit_msg>Fixed Sattelite maps sometime doesnt works. Updated versions strings Work thru proxy fixed URL scheme moved to https, so SSL is required now<commit_after>#include "qgeotilefetchergooglemaps.h"
#include "qgeomapreplygooglemaps.h"
#include "qgeotiledmapgooglemaps.h"
#include "qgeotiledmappingmanagerenginegooglemaps.h"
#include <QtLocation/private/qgeotilespec_p.h>
#include <QDebug>
#include <QSize>
#include <QDir>
#include <QUrl>
#include <QUrlQuery>
#include <QTime>
#include <QNetworkProxy>
#include <math.h>
#include <map>
QT_BEGIN_NAMESPACE
namespace
{
double tilex2long(int x, int z)
{
return (double)x / pow(2.0, z) * 360.0 - 180.0;
}
double tiley2lat(int y, int z)
{
double n = M_PI - 2.0 * M_PI * (double)y / pow(2.0, z);
return 180.0 / M_PI * atan(0.5 * (exp(n) - exp(-n)));
}
QGeoCoordinate xyzToCoord(int x, int y, int z)
{
return QGeoCoordinate(tiley2lat(y, z), tilex2long(x, z), 0.0);
}
QString sizeToStr(const QSize &size)
{
if (size.height() >= 512 || size.width() >= 512)
return QStringLiteral("512x512");
else if (size.height() >= 256 || size.width() >= 256)
return QStringLiteral("256x256");
else
return QStringLiteral("128x128"); // 128 pixel tiles are deprecated.
}
QGeoCoordinate tileCenter(const QGeoTileSpec &spec) {
int viewX0, viewY0, viewX1, viewY1;
viewX0 = spec.x();
viewY0 = spec.y();
viewX1 = spec.x() + 1;
viewY1 = spec.y() + 1;
QGeoRectangle viewport(xyzToCoord(viewX0, viewY0, spec.zoom()), xyzToCoord(viewX1, viewY1, spec.zoom()));
return viewport.center();
}
QString coordToStr(const QGeoCoordinate &coord)
{
//its important to have precision 8. otherwise tile will not be fitted correctly
char format = 'g';
return QString::number(coord.latitude(), format, 8) + "," + QString::number(coord.longitude(), format, 8);
}
int _getServerNum(int x, int y, int max)
{
return (x + 2 * y) % max;
}
}
QGeoTileFetcherGooglemaps::QGeoTileFetcherGooglemaps(const QVariantMap ¶meters,
QGeoTiledMappingManagerEngineGooglemaps *engine,
const QSize &tileSize)
: QGeoTileFetcher(engine),
m_networkManager(new QNetworkAccessManager(this)),
m_engineGooglemaps(engine),
m_tileSize(tileSize),
_googleVersionRetrieved(false)
{
m_apiKey = parameters.value(QStringLiteral("googlemaps.maps.apikey")).toString();
m_signature = parameters.value(QStringLiteral("googlemaps.maps.signature")).toString();
m_client = parameters.value(QStringLiteral("googlemaps.maps.client")).toString();
m_baseUri = QStringLiteral("http://maps.googleapis.com/maps/api/staticmap");
if (parameters.contains(QStringLiteral("googlemaps.useragent")))
_userAgent = parameters.value(QStringLiteral("googlemaps.useragent")).toString().toLatin1();
else
_userAgent = "Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0";
QStringList langs = QLocale::system().uiLanguages();
if (langs.length() > 0) {
_language = langs[0];
}
// Google version strings
_versionGoogleMap = "m@338000000";
_versionGoogleSatellite = "198";
_versionGoogleLabels = "h@336";
_versionGoogleTerrain = "t@132,r@338000000";
_secGoogleWord = "Galileo";
_tryCorrectGoogleVersions(m_networkManager);
netRequest.setRawHeader("Referrer", "https://www.google.com/maps/preview");
netRequest.setRawHeader("Accept", "*/*");
netRequest.setRawHeader("User-Agent", _userAgent);
}
QGeoTileFetcherGooglemaps::~QGeoTileFetcherGooglemaps()
{
}
QGeoTiledMapReply *QGeoTileFetcherGooglemaps::getTileImage(const QGeoTileSpec &spec)
{
if (m_apiKey.isEmpty()) {
QGeoTiledMapReply *reply = new QGeoTiledMapReply(QGeoTiledMapReply::UnknownError, "Set googlemaps.maps.apikey with google maps application key, supporting static maps", this);
emit tileError(spec, reply->errorString());
return reply;
}
QString surl = _getURL(spec.mapId(), spec.x(), spec.y(), spec.zoom());
QUrl url(surl);
netRequest.setUrl(url); // The extra pair of parens disambiguates this from a function declaration
QNetworkReply *netReply = m_networkManager->get(netRequest);
QGeoTiledMapReply *mapReply = new QGeoMapReplyGooglemaps(netReply, spec);
return mapReply;
}
void QGeoTileFetcherGooglemaps::_getSecGoogleWords(int x, int y, QString &sec1, QString &sec2)
{
sec1 = ""; // after &x=...
sec2 = ""; // after &zoom=...
int seclen = ((x * 3) + y) % 8;
sec2 = _secGoogleWord.left(seclen);
if (y >= 10000 && y < 100000) {
sec1 = "&s=";
}
}
QString QGeoTileFetcherGooglemaps::_getURL(int type, int x, int y, int zoom)
{
switch (type) {
case 0:
case 1:
{
// http://mt1.google.com/vt/lyrs=m
QString server = "mt";
QString request = "vt";
QString sec1 = ""; // after &x=...
QString sec2 = ""; // after &zoom=...
_getSecGoogleWords(x, y, sec1, sec2);
return QString("http://%1%2.google.com/%3/lyrs=%4&hl=%5&x=%6%7&y=%8&z=%9&s=%10").arg(server).arg(_getServerNum(x, y, 4)).arg(request).arg(_versionGoogleMap).arg(_language).arg(x).arg(sec1).arg(y).arg(zoom).arg(sec2);
}
break;
case 2:
{
// http://mt1.google.com/vt/lyrs=s
QString server = "khm";
QString request = "kh";
QString sec1 = ""; // after &x=...
QString sec2 = ""; // after &zoom=...
_getSecGoogleWords(x, y, sec1, sec2);
return QString("http://%1%2.google.com/%3/v=%4&hl=%5&x=%6%7&y=%8&z=%9&s=%10").arg(server).arg(_getServerNum(x, y, 4)).arg(request).arg(_versionGoogleSatellite).arg(_language).arg(x).arg(sec1).arg(y).arg(zoom).arg(sec2);
}
break;
case 3:
{
QString server = "mts";
QString request = "vt";
QString sec1 = ""; // after &x=...
QString sec2 = ""; // after &zoom=...
_getSecGoogleWords(x, y, sec1, sec2);
return QString("http://%1%2.google.com/%3/lyrs=%4&hl=%5&x=%6%7&y=%8&z=%9&s=%10").arg(server).arg(_getServerNum(x, y, 4)).arg(request).arg(_versionGoogleLabels).arg(_language).arg(x).arg(sec1).arg(y).arg(zoom).arg(sec2);
}
break;
case 4:
{
QString server = "mt";
QString request = "vt";
QString sec1 = ""; // after &x=...
QString sec2 = ""; // after &zoom=...
_getSecGoogleWords(x, y, sec1, sec2);
return QString("http://%1%2.google.com/%3/v=%4&hl=%5&x=%6%7&y=%8&z=%9&s=%10").arg(server).arg(_getServerNum(x, y, 4)).arg(request).arg(_versionGoogleTerrain).arg(_language).arg(x).arg(sec1).arg(y).arg(zoom).arg(sec2);
}
break;
}
return "";
}
void QGeoTileFetcherGooglemaps::_networkReplyError(QNetworkReply::NetworkError error)
{
qWarning() << "Could not connect to google maps. Error:" << error;
if(_googleReply)
{
_googleReply->deleteLater();
_googleReply = NULL;
}
}
void QGeoTileFetcherGooglemaps::_replyDestroyed()
{
_googleReply = NULL;
}
void QGeoTileFetcherGooglemaps::_googleVersionCompleted()
{
if (!_googleReply || (_googleReply->error() != QNetworkReply::NoError)) {
qDebug() << "Error collecting Google maps version info";
return;
}
QString html = QString(_googleReply->readAll());
QRegExp reg("\"*https?://mt\\D?\\d..*/vt\\?lyrs=m@(\\d*)", Qt::CaseInsensitive);
if (reg.indexIn(html) != -1) {
QStringList gc = reg.capturedTexts();
_versionGoogleMap = QString("m@%1").arg(gc[1]);
}
reg = QRegExp("\"*https?://khm\\D?\\d.googleapis.com/kh\\?v=(\\d*)", Qt::CaseInsensitive);
if (reg.indexIn(html) != -1) {
QStringList gc = reg.capturedTexts();
_versionGoogleSatellite = gc[1];
}
reg = QRegExp("\"*https?://mt\\D?\\d..*/vt\\?lyrs=t@(\\d*),r@(\\d*)", Qt::CaseInsensitive);
if (reg.indexIn(html) != -1) {
QStringList gc = reg.capturedTexts();
_versionGoogleTerrain = QString("t@%1,r@%2").arg(gc[1]).arg(gc[2]);
}
_googleReply->deleteLater();
_googleReply = NULL;
}
void QGeoTileFetcherGooglemaps::_tryCorrectGoogleVersions(QNetworkAccessManager* networkManager)
{
QMutexLocker locker(&_googleVersionMutex);
if (_googleVersionRetrieved) {
return;
}
_googleVersionRetrieved = true;
if(networkManager)
{
QNetworkRequest qheader;
QNetworkProxy proxy = networkManager->proxy();
QNetworkProxy tProxy;
tProxy.setType(QNetworkProxy::DefaultProxy);
networkManager->setProxy(tProxy);
QSslConfiguration conf = qheader.sslConfiguration();
conf.setPeerVerifyMode(QSslSocket::VerifyNone);
qheader.setSslConfiguration(conf);
QString url = "http://maps.google.com/maps/api/js?v=3.2&sensor=false";
qheader.setUrl(QUrl(url));
qheader.setRawHeader("User-Agent", _userAgent);
_googleReply = networkManager->get(qheader);
connect(_googleReply, &QNetworkReply::finished, this, &QGeoTileFetcherGooglemaps::_googleVersionCompleted);
connect(_googleReply, &QNetworkReply::destroyed, this, &QGeoTileFetcherGooglemaps::_replyDestroyed);
connect(_googleReply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error),
this, &QGeoTileFetcherGooglemaps::_networkReplyError);
networkManager->setProxy(proxy);
}
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>/*
* Copyright 2013 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 "SkGradientShader.h"
#include "SkRandom.h"
static SkShader* make_shader(SkScalar w, SkScalar h) {
const SkColor colors[] = {
SK_ColorRED, SK_ColorCYAN, SK_ColorGREEN, SK_ColorWHITE,
SK_ColorMAGENTA, SK_ColorBLUE, SK_ColorYELLOW,
};
const SkPoint pts[] = { { w/4, 0 }, { 3*w/4, h } };
return SkGradientShader::CreateLinear(pts, colors, NULL,
SK_ARRAY_COUNT(colors),
SkShader::kMirror_TileMode);
}
class VerticesGM : public skiagm::GM {
SkPoint fPts[9];
SkPoint fTexs[9];
SkColor fColors[9];
SkShader* fShader;
public:
VerticesGM() : fShader(NULL) {
}
virtual ~VerticesGM() {
SkSafeUnref(fShader);
}
protected:
virtual void onOnceBeforeDraw() SK_OVERRIDE {
const SkScalar X = 150;
const SkScalar Y = 150;
fPts[0].set(0, 0); fPts[1].set(X/2, 10); fPts[2].set(X, 0);
fPts[3].set(10, Y/2); fPts[4].set(X/2, Y/2); fPts[5].set(X-10, Y/2);
fPts[6].set(0, Y); fPts[7].set(X/2, Y-10); fPts[8].set(X, Y);
const SkScalar w = 200;
const SkScalar h = 200;
fTexs[0].set(0, 0); fTexs[1].set(w/2, 0); fTexs[2].set(w, 0);
fTexs[3].set(0, h/2); fTexs[4].set(w/2, h/2); fTexs[5].set(w, h/2);
fTexs[6].set(0, h); fTexs[7].set(w/2, h); fTexs[8].set(w, h);
fShader = make_shader(w, h);
SkRandom rand;
for (size_t i = 0; i < SK_ARRAY_COUNT(fColors); ++i) {
fColors[i] = rand.nextU() | 0xFF000000;
}
}
virtual SkString onShortName() SK_OVERRIDE {
return SkString("vertices");
}
virtual SkISize onISize() SK_OVERRIDE {
return SkISize::Make(600, 600);
}
virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
// start with the center of a 3x3 grid
static const uint16_t fan[] = {
4,
0, 1, 2, 5, 8, 7, 6, 3, 0
};
const struct {
const SkColor* fColors;
const SkPoint* fTexs;
} rec[] = {
{ fColors, NULL },
{ NULL, fTexs },
{ fColors, fTexs },
};
const SkXfermode::Mode modes[] = {
SkXfermode::kSrc_Mode,
SkXfermode::kDst_Mode,
SkXfermode::kModulate_Mode,
};
SkPaint paint;
paint.setShader(fShader);
canvas->translate(20, 20);
for (size_t j = 0; j < SK_ARRAY_COUNT(modes); ++j) {
SkXfermode* xfer = SkXfermode::Create(modes[j]);
canvas->save();
for (size_t i = 0; i < SK_ARRAY_COUNT(rec); ++i) {
canvas->drawVertices(SkCanvas::kTriangleFan_VertexMode,
SK_ARRAY_COUNT(fPts), fPts,
rec[i].fTexs, rec[i].fColors,
xfer, fan, SK_ARRAY_COUNT(fan), paint);
canvas->translate(200, 0);
}
canvas->restore();
canvas->translate(0, 200);
xfer->unref();
}
}
#if 0
virtual uint32_t onGetFlags() const {
return kSkipPipe_Flag | kSkipPicture_Flag;
}
#endif
private:
typedef skiagm::GM INHERITED;
};
DEF_GM( return SkNEW(VerticesGM); )
<commit_msg>suppress on gpu for now<commit_after>/*
* Copyright 2013 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 "SkGradientShader.h"
#include "SkRandom.h"
static SkShader* make_shader(SkScalar w, SkScalar h) {
const SkColor colors[] = {
SK_ColorRED, SK_ColorCYAN, SK_ColorGREEN, SK_ColorWHITE,
SK_ColorMAGENTA, SK_ColorBLUE, SK_ColorYELLOW,
};
const SkPoint pts[] = { { w/4, 0 }, { 3*w/4, h } };
return SkGradientShader::CreateLinear(pts, colors, NULL,
SK_ARRAY_COUNT(colors),
SkShader::kMirror_TileMode);
}
class VerticesGM : public skiagm::GM {
SkPoint fPts[9];
SkPoint fTexs[9];
SkColor fColors[9];
SkShader* fShader;
public:
VerticesGM() : fShader(NULL) {
}
virtual ~VerticesGM() {
SkSafeUnref(fShader);
}
protected:
virtual void onOnceBeforeDraw() SK_OVERRIDE {
const SkScalar X = 150;
const SkScalar Y = 150;
fPts[0].set(0, 0); fPts[1].set(X/2, 10); fPts[2].set(X, 0);
fPts[3].set(10, Y/2); fPts[4].set(X/2, Y/2); fPts[5].set(X-10, Y/2);
fPts[6].set(0, Y); fPts[7].set(X/2, Y-10); fPts[8].set(X, Y);
const SkScalar w = 200;
const SkScalar h = 200;
fTexs[0].set(0, 0); fTexs[1].set(w/2, 0); fTexs[2].set(w, 0);
fTexs[3].set(0, h/2); fTexs[4].set(w/2, h/2); fTexs[5].set(w, h/2);
fTexs[6].set(0, h); fTexs[7].set(w/2, h); fTexs[8].set(w, h);
fShader = make_shader(w, h);
SkRandom rand;
for (size_t i = 0; i < SK_ARRAY_COUNT(fColors); ++i) {
fColors[i] = rand.nextU() | 0xFF000000;
}
}
virtual SkString onShortName() SK_OVERRIDE {
return SkString("vertices");
}
virtual SkISize onISize() SK_OVERRIDE {
return SkISize::Make(600, 600);
}
virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
// start with the center of a 3x3 grid
static const uint16_t fan[] = {
4,
0, 1, 2, 5, 8, 7, 6, 3, 0
};
const struct {
const SkColor* fColors;
const SkPoint* fTexs;
} rec[] = {
{ fColors, NULL },
{ NULL, fTexs },
{ fColors, fTexs },
};
const SkXfermode::Mode modes[] = {
SkXfermode::kSrc_Mode,
SkXfermode::kDst_Mode,
SkXfermode::kModulate_Mode,
};
SkPaint paint;
paint.setShader(fShader);
canvas->translate(20, 20);
for (size_t j = 0; j < SK_ARRAY_COUNT(modes); ++j) {
SkXfermode* xfer = SkXfermode::Create(modes[j]);
canvas->save();
for (size_t i = 0; i < SK_ARRAY_COUNT(rec); ++i) {
canvas->drawVertices(SkCanvas::kTriangleFan_VertexMode,
SK_ARRAY_COUNT(fPts), fPts,
rec[i].fTexs, rec[i].fColors,
xfer, fan, SK_ARRAY_COUNT(fan), paint);
canvas->translate(200, 0);
}
canvas->restore();
canvas->translate(0, 200);
xfer->unref();
}
}
#if 1
virtual uint32_t onGetFlags() const {
// https://code.google.com/p/skia/issues/detail?id=1956
return kSkipGPU_Flag;
}
#endif
private:
typedef skiagm::GM INHERITED;
};
DEF_GM( return SkNEW(VerticesGM); )
<|endoftext|> |
<commit_before>/*
* Copyright 2013 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 "SkGradientShader.h"
#include "SkRandom.h"
static SkShader* make_shader(SkScalar w, SkScalar h) {
const SkColor colors[] = {
SK_ColorRED, SK_ColorCYAN, SK_ColorGREEN, SK_ColorWHITE,
SK_ColorMAGENTA, SK_ColorBLUE, SK_ColorYELLOW,
};
const SkPoint pts[] = { { w/4, 0 }, { 3*w/4, h } };
return SkGradientShader::CreateLinear(pts, colors, NULL,
SK_ARRAY_COUNT(colors),
SkShader::kMirror_TileMode);
}
class VerticesGM : public skiagm::GM {
SkPoint fPts[9];
SkPoint fTexs[9];
SkColor fColors[9];
SkShader* fShader;
public:
VerticesGM() : fShader(NULL) {
}
virtual ~VerticesGM() {
SkSafeUnref(fShader);
}
protected:
virtual uint32_t onGetFlags() const SK_OVERRIDE {
return kSkipTiled_Flag;
}
virtual void onOnceBeforeDraw() SK_OVERRIDE {
const SkScalar X = 150;
const SkScalar Y = 150;
fPts[0].set(0, 0); fPts[1].set(X/2, 10); fPts[2].set(X, 0);
fPts[3].set(10, Y/2); fPts[4].set(X/2, Y/2); fPts[5].set(X-10, Y/2);
fPts[6].set(0, Y); fPts[7].set(X/2, Y-10); fPts[8].set(X, Y);
const SkScalar w = 200;
const SkScalar h = 200;
fTexs[0].set(0, 0); fTexs[1].set(w/2, 0); fTexs[2].set(w, 0);
fTexs[3].set(0, h/2); fTexs[4].set(w/2, h/2); fTexs[5].set(w, h/2);
fTexs[6].set(0, h); fTexs[7].set(w/2, h); fTexs[8].set(w, h);
fShader = make_shader(w, h);
SkRandom rand;
for (size_t i = 0; i < SK_ARRAY_COUNT(fColors); ++i) {
fColors[i] = rand.nextU() | 0xFF000000;
}
}
virtual SkString onShortName() SK_OVERRIDE {
return SkString("vertices");
}
virtual SkISize onISize() SK_OVERRIDE {
return SkISize::Make(600, 600);
}
virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
// start with the center of a 3x3 grid
static const uint16_t fan[] = {
4,
0, 1, 2, 5, 8, 7, 6, 3, 0
};
const struct {
const SkColor* fColors;
const SkPoint* fTexs;
} rec[] = {
{ fColors, NULL },
{ NULL, fTexs },
{ fColors, fTexs },
};
const SkXfermode::Mode modes[] = {
SkXfermode::kSrc_Mode,
SkXfermode::kDst_Mode,
SkXfermode::kModulate_Mode,
};
SkPaint paint;
paint.setShader(fShader);
canvas->translate(20, 20);
for (size_t j = 0; j < SK_ARRAY_COUNT(modes); ++j) {
SkXfermode* xfer = SkXfermode::Create(modes[j]);
canvas->save();
for (size_t i = 0; i < SK_ARRAY_COUNT(rec); ++i) {
canvas->drawVertices(SkCanvas::kTriangleFan_VertexMode,
SK_ARRAY_COUNT(fPts), fPts,
rec[i].fTexs, rec[i].fColors,
xfer, fan, SK_ARRAY_COUNT(fan), paint);
canvas->translate(200, 0);
}
canvas->restore();
canvas->translate(0, 200);
xfer->unref();
}
}
private:
typedef skiagm::GM INHERITED;
};
DEF_GM( return SkNEW(VerticesGM); )
<commit_msg>new vertices gm to test alpha<commit_after>/*
* Copyright 2013 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 "SkGradientShader.h"
#include "SkRandom.h"
static SkShader* make_shader(SkScalar w, SkScalar h) {
const SkColor colors[] = {
SK_ColorRED, SK_ColorCYAN, SK_ColorGREEN, SK_ColorWHITE,
SK_ColorMAGENTA, SK_ColorBLUE, SK_ColorYELLOW,
};
const SkPoint pts[] = { { w/4, 0 }, { 3*w/4, h } };
return SkGradientShader::CreateLinear(pts, colors, NULL,
SK_ARRAY_COUNT(colors),
SkShader::kMirror_TileMode);
}
class VerticesGM : public skiagm::GM {
SkPoint fPts[9];
SkPoint fTexs[9];
SkColor fColors[9];
SkShader* fShader;
unsigned fAlpha;
public:
VerticesGM(unsigned alpha) : fShader(NULL), fAlpha(alpha) {
}
virtual ~VerticesGM() {
SkSafeUnref(fShader);
}
protected:
virtual uint32_t onGetFlags() const SK_OVERRIDE {
return kSkipTiled_Flag;
}
virtual void onOnceBeforeDraw() SK_OVERRIDE {
const SkScalar X = 150;
const SkScalar Y = 150;
fPts[0].set(0, 0); fPts[1].set(X/2, 10); fPts[2].set(X, 0);
fPts[3].set(10, Y/2); fPts[4].set(X/2, Y/2); fPts[5].set(X-10, Y/2);
fPts[6].set(0, Y); fPts[7].set(X/2, Y-10); fPts[8].set(X, Y);
const SkScalar w = 200;
const SkScalar h = 200;
fTexs[0].set(0, 0); fTexs[1].set(w/2, 0); fTexs[2].set(w, 0);
fTexs[3].set(0, h/2); fTexs[4].set(w/2, h/2); fTexs[5].set(w, h/2);
fTexs[6].set(0, h); fTexs[7].set(w/2, h); fTexs[8].set(w, h);
fShader = make_shader(w, h);
SkRandom rand;
for (size_t i = 0; i < SK_ARRAY_COUNT(fColors); ++i) {
fColors[i] = rand.nextU() | 0xFF000000;
}
}
virtual SkString onShortName() SK_OVERRIDE {
SkString name("vertices");
if (0xFF != fAlpha) {
name.appendf("_%02X", fAlpha);
}
return name;
}
virtual SkISize onISize() SK_OVERRIDE {
return SkISize::Make(600, 600);
}
virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
// start with the center of a 3x3 grid
static const uint16_t fan[] = {
4,
0, 1, 2, 5, 8, 7, 6, 3, 0
};
const struct {
const SkColor* fColors;
const SkPoint* fTexs;
} rec[] = {
{ fColors, NULL },
{ NULL, fTexs },
{ fColors, fTexs },
};
const SkXfermode::Mode modes[] = {
SkXfermode::kSrc_Mode,
SkXfermode::kDst_Mode,
SkXfermode::kModulate_Mode,
};
SkPaint paint;
paint.setShader(fShader);
paint.setAlpha(fAlpha);
canvas->translate(20, 20);
for (size_t j = 0; j < SK_ARRAY_COUNT(modes); ++j) {
SkXfermode* xfer = SkXfermode::Create(modes[j]);
canvas->save();
for (size_t i = 0; i < SK_ARRAY_COUNT(rec); ++i) {
canvas->drawVertices(SkCanvas::kTriangleFan_VertexMode,
SK_ARRAY_COUNT(fPts), fPts,
rec[i].fTexs, rec[i].fColors,
xfer, fan, SK_ARRAY_COUNT(fan), paint);
canvas->translate(200, 0);
}
canvas->restore();
canvas->translate(0, 200);
xfer->unref();
}
}
private:
typedef skiagm::GM INHERITED;
};
/////////////////////////////////////////////////////////////////////////////////////
DEF_GM( return SkNEW_ARGS(VerticesGM, (0xFF)); )
DEF_GM( return SkNEW_ARGS(VerticesGM, (0x80)); )
<|endoftext|> |
<commit_before><commit_msg>Check the bookmark bar state when updating the title of the page.<commit_after><|endoftext|> |
<commit_before><commit_msg>Refine where keypresses are sent with window focus<commit_after><|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_FUN_FILL_HPP
#define STAN_MATH_PRIM_FUN_FILL_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <vector>
namespace stan {
namespace math {
/**
* Fill the specified container with the specified value.
*
* The specified matrix is filled by element.
*
* @tparam T type of elements in the matrix
* @tparam R number of rows, can be Eigen::Dynamic
* @tparam C number of columns, can be Eigen::Dynamic
* @tparam S Type of value.
*
* @param x Container.
* @param y Value.
*/
template <typename EigMat, typename S, require_eigen_t<EigMat>* = nullptr,
require_stan_scalar_t<S>* = nullptr>
inline void fill(EigMat& x, const S& y) {
x.fill(y);
}
/**
* Fill the specified container with the specified value.
*
* This base case simply assigns the value to the container.
*
* @tparam T Type of reference container.
* @tparam S Type of value.
* @param x Container.
* @param y Value.
*/
template <typename T, typename S,
require_any_t<std::is_assignable<std::decay_t<T>, std::decay_t<S>>>* = nullptr>
inline void fill(T& x, const S& y) {
x = y;
}
/**
* Fill the specified container with the specified value.
*
* Each container in the specified standard vector is filled
* recursively by calling <code>fill</code>.
*
* @tparam T type of elements in the vector
* @tparam S type of value
* @param[in] x Container.
* @param[in, out] y Value.
*/
template <typename Vec, typename S, require_std_vector_t<Vec>* = nullptr>
inline void fill(Vec& x, const S& y) {
for (typename std::decay_t<Vec>::size_type i = 0; i < x.size(); ++i) {
fill(x[i], y);
}
}
} // namespace math
} // namespace stan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)<commit_after>#ifndef STAN_MATH_PRIM_FUN_FILL_HPP
#define STAN_MATH_PRIM_FUN_FILL_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <vector>
namespace stan {
namespace math {
/**
* Fill the specified container with the specified value.
*
* The specified matrix is filled by element.
*
* @tparam T type of elements in the matrix
* @tparam R number of rows, can be Eigen::Dynamic
* @tparam C number of columns, can be Eigen::Dynamic
* @tparam S Type of value.
*
* @param x Container.
* @param y Value.
*/
template <typename EigMat, typename S, require_eigen_t<EigMat>* = nullptr,
require_stan_scalar_t<S>* = nullptr>
inline void fill(EigMat& x, const S& y) {
x.fill(y);
}
/**
* Fill the specified container with the specified value.
*
* This base case simply assigns the value to the container.
*
* @tparam T Type of reference container.
* @tparam S Type of value.
* @param x Container.
* @param y Value.
*/
template <typename T, typename S,
require_any_t<
std::is_assignable<std::decay_t<T>, std::decay_t<S>>>* = nullptr>
inline void fill(T& x, const S& y) {
x = y;
}
/**
* Fill the specified container with the specified value.
*
* Each container in the specified standard vector is filled
* recursively by calling <code>fill</code>.
*
* @tparam T type of elements in the vector
* @tparam S type of value
* @param[in] x Container.
* @param[in, out] y Value.
*/
template <typename Vec, typename S, require_std_vector_t<Vec>* = nullptr>
inline void fill(Vec& x, const S& y) {
for (typename std::decay_t<Vec>::size_type i = 0; i < x.size(); ++i) {
fill(x[i], y);
}
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>
#include <Alert.h>
#include <Box.h>
#include <Button.h>
#include <Font.h>
#include <ScrollView.h>
#include <StatusBar.h>
#include <StringView.h>
#include <TextView.h>
#include "CLVEasyItem.h"
#include "ColumnListView.h"
#include "globals.h"
#include "smsinboxview.h"
#include <stdio.h>
const uint32 SMSLIST_INV = 'SI00';
const uint32 SMSLIST_SEL = 'SI01';
const uint32 SMSREFRESH = 'SI02';
const uint32 SMSDELETE = 'SI03';
const uint32 SMSNEW = 'SI04';
smsInboxView::smsInboxView(BRect r, const char *slot) : mobileView(r, "smsInboxView") {
caption->SetText(_("SMS Inbox"));
memSlot = slot;
BFont font(be_plain_font);
float maxw, totalw = 0;
BRect r = this->MyBounds();
r.InsetBy(10,15);
r.right -= B_V_SCROLL_BAR_WIDTH;
r.bottom = r.top + r.Height()/2 - 50;
// add column list
CLVContainerView *containerView;
list = new ColumnListView(r, &containerView, NULL, B_FOLLOW_TOP_BOTTOM|B_FOLLOW_LEFT_RIGHT,
B_WILL_DRAW|B_FRAME_EVENTS|B_NAVIGABLE, B_SINGLE_SELECTION_LIST, false, true, true, true,
B_FANCY_BORDER);
maxw = font.StringWidth("XX"); totalw += maxw;
list->AddColumn(new CLVColumn("#", maxw, CLV_TELL_ITEMS_WIDTH|CLV_SORT_KEYABLE));
maxw = font.StringWidth("+999999999") + 20; totalw += maxw;
list->AddColumn(new CLVColumn(_("Sender"), maxw, CLV_TELL_ITEMS_WIDTH|CLV_HEADER_TRUNCATE|CLV_SORT_KEYABLE));
maxw = font.StringWidth("8888/88/88, 88:88") + 20; totalw += maxw;
list->AddColumn(new CLVColumn(_("Date"), maxw, CLV_TELL_ITEMS_WIDTH|CLV_HEADER_TRUNCATE|CLV_SORT_KEYABLE));
list->AddColumn(new CLVColumn(_("Text"), r.right-B_V_SCROLL_BAR_WIDTH-4-totalw, CLV_TELL_ITEMS_WIDTH|CLV_HEADER_TRUNCATE|CLV_SORT_KEYABLE));
list->SetSortFunction(CLVEasyItem::CompareItems);
this->AddChild(containerView);
list->SetInvocationMessage(new BMessage(SMSLIST_INV));
list->SetSelectionMessage(new BMessage(SMSLIST_SEL));
r.right += 16;
r.OffsetBy(0,r.Height()+25);
BBox *box;
this->AddChild(box = new BBox(r,"smsPrvBox"));
box->SetResizingMode(B_FOLLOW_LEFT_RIGHT|B_FOLLOW_BOTTOM);
BRect s = box->Bounds(); s.InsetBy(10,10); s.right -= B_V_SCROLL_BAR_WIDTH;
BRect t; t.top = t.left = 0; t.right = s.Width(); t.bottom = s.Height();
prv = new BTextView(s, "smsPrv", t, B_FOLLOW_LEFT_RIGHT|B_FOLLOW_BOTTOM);
prv->MakeEditable(false);
prv->SetStylable(true);
box->AddChild(new BScrollView("smsPrvScroll",prv,B_FOLLOW_LEFT_RIGHT|B_FOLLOW_BOTTOM,0,false,true));
r.OffsetBy(0,r.Height()+5);
r.bottom = r.top + font.Size()*2;
this->AddChild(progress = new BStatusBar(r, "smsStatusBar"));
progress->SetResizingMode(B_FOLLOW_LEFT_RIGHT|B_FOLLOW_BOTTOM);
progress->SetMaxValue(100);
progress->Hide();
r = this->MyBounds();
r.InsetBy(20,20);
s = r; s.top = s.bottom - font.Size()*2; s.right = s.left + font.StringWidth("MMMMMMMMMM")+40;
this->AddChild(refresh = new BButton(s, "smsRefresh", _("Refresh"), new BMessage(SMSREFRESH), B_FOLLOW_LEFT|B_FOLLOW_BOTTOM));
t = r; t.top = s.top; t.bottom = s.bottom; t.right = r.right; t.left = t.right - (font.StringWidth("MMMMMMMMMM")+40);
this->AddChild(del = new BButton(t, "smsDelete", _("Delete"), new BMessage(SMSDELETE), B_FOLLOW_RIGHT|B_FOLLOW_BOTTOM));
}
void smsInboxView::clearList(void) {
// clear list
if (list->CountItems()>0) {
CLVEasyItem *anItem;
for (int i=0; (anItem=(smsInboxListItem*)list->ItemAt(i)); i++)
delete anItem;
if (!list->IsEmpty())
list->MakeEmpty();
}
}
void smsInboxView::fillList(void) {
BString right;
struct memSlotSMS *sl;
struct SMS *sms;
int i, msgnum;
float delta;
clearList();
progress->Reset();
progress->Show();
progress->Update(0, _("Checking number of messagess..."));
msgnum = gsm->changeSMSMemSlot(memSlot.String());
sl = gsm->getSMSSlot(memSlot.String());
if (msgnum > 0) {
right = ""; right << msgnum;
delta = 100/msgnum;
gsm->getSMSList(memSlot.String());
int j = sl->msg->CountItems();
for (i=0;i<j;i++) {
sms = (struct SMS*)sl->msg->ItemAt(i);
gsm->getSMSContent(sms);
list->AddItem(new smsInboxListItem(sms));
progress->Update(delta, "0", right.String());
}
}
progress->Hide();
gsm->changeSMSMemSlot("MT"); // XXX configurable?
}
void smsInboxView::updatePreview(struct SMS *sms) {
BString tmp, tmp2;
int textlen;
static BFont font(be_plain_font);
static BFont bfont(be_bold_font);
static rgb_color *red = NULL, *blue = NULL, *green = NULL, *black = NULL;
if (!red) {
red = new rgb_color; red->red = 255; red->blue = red->green = 0;
blue = new rgb_color; blue->blue = 255; blue->red = blue->green = 0;
green = new rgb_color; green->green = 255; green->red = green->blue = 0;
black = new rgb_color; black->red = black->green = black->blue = 0;
}
switch (sms->type) {
// case GSM::STO_SENT:
// tmp = _("Message sent");
// tmp2 = _("To:");
// break;
// case GSM::STO_UNSENT:
// tmp = _("Message not yet sent");
// tmp2 = _("To:");
// break;
case GSM::REC_READ:
tmp = _("Message received");
tmp2 = _("From");
break;
case GSM::REC_UNREAD:
tmp = _("Message unread");
tmp2 = _("From:");
break;
default:
tmp = _("Message");
break;
}
tmp += "\n"; tmp += tmp2; tmp += " ";
prv->SetText("");
textlen = 0;
bfont.SetSize(14.0);
prv->SetFontAndColor(&bfont,B_FONT_ALL,blue);
prv->Insert(textlen,tmp.String(),tmp.Length());
textlen += tmp.Length();
prv->SetFontAndColor(&bfont,B_FONT_ALL,red);
prv->Insert(textlen,sms->number.String(),sms->number.Length());
textlen += sms->number.Length();
prv->Insert(textlen,"\n",1);
textlen++;
if (sms->date.Length() > 0) {
prv->SetFontAndColor(&bfont,B_FONT_ALL,blue);
tmp = _("Date:"); tmp += " ";
prv->Insert(textlen,tmp.String(),tmp.Length());
textlen += tmp.Length();
prv->SetFontAndColor(&bfont,B_FONT_ALL,red);
prv->Insert(textlen,sms->date.String(),sms->date.Length());
textlen += sms->date.Length();
}
prv->Insert(textlen,"\n\n",2);
textlen += 2;
font.SetSize(12.0);
prv->SetFontAndColor(&font,B_FONT_ALL,black);
prv->Insert(textlen,sms->msg.String(),sms->msg.Length());
textlen += sms->msg.Length();
prv->Insert(textlen,"\n",1);
}
#include <Window.h>
void smsInboxView::Show(void) {
printf("show!\n");
BView::Show();
if (list->CountItems()==0) {
BView::Flush();
BView::Sync();
this->Window()->Flush();
this->Window()->Sync();
fillList();
}
}
void smsInboxView::MessageReceived(BMessage *Message) {
switch (Message->what) {
case SMSREFRESH:
fillList();
break;
case SMSDELETE:
{ int i = list->CurrentSelection(0);
if (i>=0) {
BAlert *ask = new BAlert(APP_NAME, _("Do you really want to delete this message?"), _("Yes"), _("No"), NULL, B_WIDTH_AS_USUAL, B_WARNING_ALERT);
if (ask->Go() == 0) {
struct SMS *sms = ((smsInboxListItem*)list->ItemAt(list->CurrentSelection(0)))->Msg();
if (gsm->removeSMS(sms) == 0)
list->RemoveItem(i);
}
}
break;
}
case SMSLIST_INV:
case SMSLIST_SEL:
{ int i = list->CurrentSelection(0);
if (i>=0) {
struct SMS *sms = ((smsInboxListItem*)list->ItemAt(list->CurrentSelection(0)))->Msg();
if (sms)
updatePreview(sms);
} else {
prv->SetText("");
}
break;
}
default:
break;
}
}
<commit_msg>- fixed typo<commit_after>
#include <Alert.h>
#include <Box.h>
#include <Button.h>
#include <Font.h>
#include <ScrollView.h>
#include <StatusBar.h>
#include <StringView.h>
#include <TextView.h>
#include "CLVEasyItem.h"
#include "ColumnListView.h"
#include "globals.h"
#include "smsinboxview.h"
#include <stdio.h>
const uint32 SMSLIST_INV = 'SI00';
const uint32 SMSLIST_SEL = 'SI01';
const uint32 SMSREFRESH = 'SI02';
const uint32 SMSDELETE = 'SI03';
const uint32 SMSNEW = 'SI04';
smsInboxView::smsInboxView(BRect r, const char *slot) : mobileView(r, "smsInboxView") {
caption->SetText(_("SMS Inbox"));
memSlot = slot;
BFont font(be_plain_font);
float maxw, totalw = 0;
BRect r = this->MyBounds();
r.InsetBy(10,15);
r.right -= B_V_SCROLL_BAR_WIDTH;
r.bottom = r.top + r.Height()/2 - 50;
// add column list
CLVContainerView *containerView;
list = new ColumnListView(r, &containerView, NULL, B_FOLLOW_TOP_BOTTOM|B_FOLLOW_LEFT_RIGHT,
B_WILL_DRAW|B_FRAME_EVENTS|B_NAVIGABLE, B_SINGLE_SELECTION_LIST, false, true, true, true,
B_FANCY_BORDER);
maxw = font.StringWidth("XX"); totalw += maxw;
list->AddColumn(new CLVColumn("#", maxw, CLV_TELL_ITEMS_WIDTH|CLV_SORT_KEYABLE));
maxw = font.StringWidth("+999999999") + 20; totalw += maxw;
list->AddColumn(new CLVColumn(_("Sender"), maxw, CLV_TELL_ITEMS_WIDTH|CLV_HEADER_TRUNCATE|CLV_SORT_KEYABLE));
maxw = font.StringWidth("8888/88/88, 88:88") + 20; totalw += maxw;
list->AddColumn(new CLVColumn(_("Date"), maxw, CLV_TELL_ITEMS_WIDTH|CLV_HEADER_TRUNCATE|CLV_SORT_KEYABLE));
list->AddColumn(new CLVColumn(_("Text"), r.right-B_V_SCROLL_BAR_WIDTH-4-totalw, CLV_TELL_ITEMS_WIDTH|CLV_HEADER_TRUNCATE|CLV_SORT_KEYABLE));
list->SetSortFunction(CLVEasyItem::CompareItems);
this->AddChild(containerView);
list->SetInvocationMessage(new BMessage(SMSLIST_INV));
list->SetSelectionMessage(new BMessage(SMSLIST_SEL));
r.right += 16;
r.OffsetBy(0,r.Height()+25);
BBox *box;
this->AddChild(box = new BBox(r,"smsPrvBox"));
box->SetResizingMode(B_FOLLOW_LEFT_RIGHT|B_FOLLOW_BOTTOM);
BRect s = box->Bounds(); s.InsetBy(10,10); s.right -= B_V_SCROLL_BAR_WIDTH;
BRect t; t.top = t.left = 0; t.right = s.Width(); t.bottom = s.Height();
prv = new BTextView(s, "smsPrv", t, B_FOLLOW_LEFT_RIGHT|B_FOLLOW_BOTTOM);
prv->MakeEditable(false);
prv->SetStylable(true);
box->AddChild(new BScrollView("smsPrvScroll",prv,B_FOLLOW_LEFT_RIGHT|B_FOLLOW_BOTTOM,0,false,true));
r.OffsetBy(0,r.Height()+5);
r.bottom = r.top + font.Size()*2;
this->AddChild(progress = new BStatusBar(r, "smsStatusBar"));
progress->SetResizingMode(B_FOLLOW_LEFT_RIGHT|B_FOLLOW_BOTTOM);
progress->SetMaxValue(100);
progress->Hide();
r = this->MyBounds();
r.InsetBy(20,20);
s = r; s.top = s.bottom - font.Size()*2; s.right = s.left + font.StringWidth("MMMMMMMMMM")+40;
this->AddChild(refresh = new BButton(s, "smsRefresh", _("Refresh"), new BMessage(SMSREFRESH), B_FOLLOW_LEFT|B_FOLLOW_BOTTOM));
t = r; t.top = s.top; t.bottom = s.bottom; t.right = r.right; t.left = t.right - (font.StringWidth("MMMMMMMMMM")+40);
this->AddChild(del = new BButton(t, "smsDelete", _("Delete"), new BMessage(SMSDELETE), B_FOLLOW_RIGHT|B_FOLLOW_BOTTOM));
}
void smsInboxView::clearList(void) {
// clear list
if (list->CountItems()>0) {
CLVEasyItem *anItem;
for (int i=0; (anItem=(smsInboxListItem*)list->ItemAt(i)); i++)
delete anItem;
if (!list->IsEmpty())
list->MakeEmpty();
}
}
void smsInboxView::fillList(void) {
BString right;
struct memSlotSMS *sl;
struct SMS *sms;
int i, msgnum;
float delta;
clearList();
progress->Reset();
progress->Show();
progress->Update(0, _("Checking number of messages..."));
msgnum = gsm->changeSMSMemSlot(memSlot.String());
sl = gsm->getSMSSlot(memSlot.String());
if (msgnum > 0) {
right = ""; right << msgnum;
delta = 100/msgnum;
gsm->getSMSList(memSlot.String());
int j = sl->msg->CountItems();
for (i=0;i<j;i++) {
sms = (struct SMS*)sl->msg->ItemAt(i);
gsm->getSMSContent(sms);
list->AddItem(new smsInboxListItem(sms));
progress->Update(delta, "0", right.String());
}
}
progress->Hide();
gsm->changeSMSMemSlot("MT"); // XXX configurable?
}
void smsInboxView::updatePreview(struct SMS *sms) {
BString tmp, tmp2;
int textlen;
static BFont font(be_plain_font);
static BFont bfont(be_bold_font);
static rgb_color *red = NULL, *blue = NULL, *green = NULL, *black = NULL;
if (!red) {
red = new rgb_color; red->red = 255; red->blue = red->green = 0;
blue = new rgb_color; blue->blue = 255; blue->red = blue->green = 0;
green = new rgb_color; green->green = 255; green->red = green->blue = 0;
black = new rgb_color; black->red = black->green = black->blue = 0;
}
switch (sms->type) {
// case GSM::STO_SENT:
// tmp = _("Message sent");
// tmp2 = _("To:");
// break;
// case GSM::STO_UNSENT:
// tmp = _("Message not yet sent");
// tmp2 = _("To:");
// break;
case GSM::REC_READ:
tmp = _("Message received");
tmp2 = _("From");
break;
case GSM::REC_UNREAD:
tmp = _("Message unread");
tmp2 = _("From:");
break;
default:
tmp = _("Message");
break;
}
tmp += "\n"; tmp += tmp2; tmp += " ";
prv->SetText("");
textlen = 0;
bfont.SetSize(14.0);
prv->SetFontAndColor(&bfont,B_FONT_ALL,blue);
prv->Insert(textlen,tmp.String(),tmp.Length());
textlen += tmp.Length();
prv->SetFontAndColor(&bfont,B_FONT_ALL,red);
prv->Insert(textlen,sms->number.String(),sms->number.Length());
textlen += sms->number.Length();
prv->Insert(textlen,"\n",1);
textlen++;
if (sms->date.Length() > 0) {
prv->SetFontAndColor(&bfont,B_FONT_ALL,blue);
tmp = _("Date:"); tmp += " ";
prv->Insert(textlen,tmp.String(),tmp.Length());
textlen += tmp.Length();
prv->SetFontAndColor(&bfont,B_FONT_ALL,red);
prv->Insert(textlen,sms->date.String(),sms->date.Length());
textlen += sms->date.Length();
}
prv->Insert(textlen,"\n\n",2);
textlen += 2;
font.SetSize(12.0);
prv->SetFontAndColor(&font,B_FONT_ALL,black);
prv->Insert(textlen,sms->msg.String(),sms->msg.Length());
textlen += sms->msg.Length();
prv->Insert(textlen,"\n",1);
}
#include <Window.h>
void smsInboxView::Show(void) {
printf("show!\n");
BView::Show();
if (list->CountItems()==0) {
BView::Flush();
BView::Sync();
this->Window()->Flush();
this->Window()->Sync();
fillList();
}
}
void smsInboxView::MessageReceived(BMessage *Message) {
switch (Message->what) {
case SMSREFRESH:
fillList();
break;
case SMSDELETE:
{ int i = list->CurrentSelection(0);
if (i>=0) {
BAlert *ask = new BAlert(APP_NAME, _("Do you really want to delete this message?"), _("Yes"), _("No"), NULL, B_WIDTH_AS_USUAL, B_WARNING_ALERT);
if (ask->Go() == 0) {
struct SMS *sms = ((smsInboxListItem*)list->ItemAt(list->CurrentSelection(0)))->Msg();
if (gsm->removeSMS(sms) == 0)
list->RemoveItem(i);
}
}
break;
}
case SMSLIST_INV:
case SMSLIST_SEL:
{ int i = list->CurrentSelection(0);
if (i>=0) {
struct SMS *sms = ((smsInboxListItem*)list->ItemAt(list->CurrentSelection(0)))->Msg();
if (sms)
updatePreview(sms);
} else {
prv->SetText("");
}
break;
}
default:
break;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2015 Rony Shapiro <ronys@users.sourceforge.net>.
* 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
*/
/*
* This routine processes Filter XML using the STANDARD and UNMODIFIED
* Xerces library V3.1.1 released on April 27, 2010
*
* See http://xerces.apache.org/xerces-c/
*
* Note: This is a cross-platform library and can be linked in as a
* Static library or used as a dynamic library e.g. DLL in Windows.
* To use the static version, the following pre-processor statement
* must be defined: XERCES_STATIC_LIBRARY
*
*/
/*
* NOTE: Xerces characters are ALWAYS in UTF-16 (may or may not be wchar_t
* depending on platform).
* Non-unicode builds will need convert any results from parsing the XML
* document from UTF-16 to ASCII.
*/
#include "../XMLDefs.h" // Required if testing "USE_XML_LIBRARY"
#if USE_XML_LIBRARY == XERCES
// PWS includes
#include "XFilterXMLProcessor.h"
#include "XSecMemMgr.h"
#include "../../StringX.h"
#include "../../core.h"
#include "./XMLChConverter.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <map>
#include <algorithm>
// Xerces includes
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
#include <xercesc/framework/XMLGrammarDescription.hpp>
#if defined(XERCES_NEW_IOSTREAMS)
#include <fstream>
#else
#include <fstream.h>
#endif
XFilterXMLProcessor::XFilterXMLProcessor(PWSFilters &mapfilters, const FilterPool fpool,
Asker *pAsker)
: m_pAsker(pAsker), m_MapFilters(mapfilters), m_FPool(fpool)
{
}
XFilterXMLProcessor::~XFilterXMLProcessor()
{
}
bool XFilterXMLProcessor::Process(const bool &bvalidation,
const StringX &strXMLData,
const stringT &strXMLFileName,
const stringT &strXSDFileName)
{
USES_XMLCH_STR
bool bErrorOccurred = false;
stringT cs_validation;
LoadAString(cs_validation, IDSC_XMLVALIDATION);
stringT cs_import;
LoadAString(cs_import, IDSC_XMLIMPORT);
stringT strResultText(_T(""));
m_bValidation = bvalidation; // Validate or Import
XSecMemMgr sec_mm;
// Initialize the XML4C2 system
try
{
XMLPlatformUtils::Initialize(XMLUni::fgXercescDefaultLocale, 0, 0, &sec_mm);
}
catch (const XMLException& toCatch)
{
m_strXMLErrors = stringT(_X2ST(toCatch.getMessage()));
return false;
}
// Create a SAX2 parser object.
SAX2XMLReader* pSAX2Parser = XMLReaderFactory::createXMLReader(&sec_mm);
// Set non-default features
pSAX2Parser->setFeature(XMLUni::fgSAX2CoreNameSpacePrefixes, true);
pSAX2Parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
pSAX2Parser->setFeature(XMLUni::fgXercesSchemaFullChecking, true);
pSAX2Parser->setFeature(XMLUni::fgXercesLoadExternalDTD, false);
pSAX2Parser->setFeature(XMLUni::fgXercesSkipDTDValidation, true);
// Set properties
pSAX2Parser->setProperty(XMLUni::fgXercesSchemaExternalNoNameSpaceSchemaLocation,
const_cast<void*>(reinterpret_cast<const void*>(strXSDFileName.c_str())));
pSAX2Parser->setProperty(XMLUni::fgXercesScannerName,
const_cast<void*>(reinterpret_cast<const void*>(XMLUni::fgSGXMLScanner)));
pSAX2Parser->setInputBufferSize(4096);
// Create SAX handler object and install it on the pSAX2Parser, as the
// document and error pSAX2Handler.
XFilterSAX2Handlers * pSAX2Handler = new XFilterSAX2Handlers;
pSAX2Parser->setContentHandler(pSAX2Handler);
pSAX2Parser->setErrorHandler(pSAX2Handler);
// Workaround/bypass until Xerces supports retrieving version from the
// <xs:schema ...> statement!
// Set 'dummy' schema version to arbitrary value > 1
pSAX2Handler->SetSchemaVersion(99);
pSAX2Handler->SetVariables(m_pAsker, &m_MapFilters, m_FPool, m_bValidation);
try
{
// Let's begin the parsing now
if (!strXMLFileName.empty()) {
pSAX2Parser->parse(_W2X(strXMLFileName.c_str()));
} else {
const char *szID = "database_filters";
const char *buffer = XMLString::transcode(_W2X(strXMLData.c_str()));
//2nd parameter must be number of bytes, so we use a length for char* repr
MemBufInputSource* memBufIS = new MemBufInputSource(
reinterpret_cast<const XMLByte *>(buffer),
XMLString::stringLen(buffer),
szID, false);
pSAX2Parser->parse(*memBufIS);
delete memBufIS;
}
}
catch (const OutOfMemoryException&)
{
LoadAString(strResultText, IDCS_XERCESOUTOFMEMORY);
bErrorOccurred = true;
}
catch (const XMLException& e)
{
strResultText = stringT(_X2ST(e.getMessage()));
bErrorOccurred = true;
}
catch (...)
{
LoadAString(strResultText, IDCS_XERCESEXCEPTION);
bErrorOccurred = true;
}
if (pSAX2Handler->getIfErrors() || bErrorOccurred) {
bErrorOccurred = true;
strResultText = pSAX2Handler->getValidationResult();
Format(m_strXMLErrors, IDSC_XERCESPARSEERROR,
m_bValidation ? cs_validation.c_str() : cs_import.c_str(),
strResultText.c_str());
} else {
m_strXMLErrors = strResultText;
}
// Delete the pSAX2Parser itself. Must be done prior to calling Terminate, below.
delete pSAX2Parser;
delete pSAX2Handler;
USES_XMLCH_STR_END
// And call the termination method
XMLPlatformUtils::Terminate();
return !bErrorOccurred;
}
#endif /* USE_XML_LIBRARY == XERCES */
<commit_msg>Fix schema loading when using Xerces<commit_after>/*
* Copyright (c) 2003-2015 Rony Shapiro <ronys@users.sourceforge.net>.
* 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
*/
/*
* This routine processes Filter XML using the STANDARD and UNMODIFIED
* Xerces library V3.1.1 released on April 27, 2010
*
* See http://xerces.apache.org/xerces-c/
*
* Note: This is a cross-platform library and can be linked in as a
* Static library or used as a dynamic library e.g. DLL in Windows.
* To use the static version, the following pre-processor statement
* must be defined: XERCES_STATIC_LIBRARY
*
*/
/*
* NOTE: Xerces characters are ALWAYS in UTF-16 (may or may not be wchar_t
* depending on platform).
* Non-unicode builds will need convert any results from parsing the XML
* document from UTF-16 to ASCII.
*/
#include "../XMLDefs.h" // Required if testing "USE_XML_LIBRARY"
#if USE_XML_LIBRARY == XERCES
// PWS includes
#include "XFilterXMLProcessor.h"
#include "XSecMemMgr.h"
#include "../../StringX.h"
#include "../../core.h"
#include "./XMLChConverter.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <map>
#include <algorithm>
// Xerces includes
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
#include <xercesc/framework/XMLGrammarDescription.hpp>
#if defined(XERCES_NEW_IOSTREAMS)
#include <fstream>
#else
#include <fstream.h>
#endif
XFilterXMLProcessor::XFilterXMLProcessor(PWSFilters &mapfilters, const FilterPool fpool,
Asker *pAsker)
: m_pAsker(pAsker), m_MapFilters(mapfilters), m_FPool(fpool)
{
}
XFilterXMLProcessor::~XFilterXMLProcessor()
{
}
bool XFilterXMLProcessor::Process(const bool &bvalidation,
const StringX &strXMLData,
const stringT &strXMLFileName,
const stringT &strXSDFileName)
{
USES_XMLCH_STR
bool bErrorOccurred = false;
stringT cs_validation;
LoadAString(cs_validation, IDSC_XMLVALIDATION);
stringT cs_import;
LoadAString(cs_import, IDSC_XMLIMPORT);
stringT strResultText(_T(""));
m_bValidation = bvalidation; // Validate or Import
XSecMemMgr sec_mm;
// Initialize the XML4C2 system
try
{
XMLPlatformUtils::Initialize(XMLUni::fgXercescDefaultLocale, 0, 0, &sec_mm);
}
catch (const XMLException& toCatch)
{
m_strXMLErrors = stringT(_X2ST(toCatch.getMessage()));
return false;
}
// Create a SAX2 parser object.
SAX2XMLReader* pSAX2Parser = XMLReaderFactory::createXMLReader(&sec_mm);
// Set non-default features
pSAX2Parser->setFeature(XMLUni::fgSAX2CoreNameSpacePrefixes, true);
pSAX2Parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
pSAX2Parser->setFeature(XMLUni::fgXercesSchemaFullChecking, true);
pSAX2Parser->setFeature(XMLUni::fgXercesLoadExternalDTD, false);
pSAX2Parser->setFeature(XMLUni::fgXercesSkipDTDValidation, true);
// Set properties
pSAX2Parser->setProperty(XMLUni::fgXercesSchemaExternalNoNameSpaceSchemaLocation,
_W2X(strXSDFileName.c_str()));
pSAX2Parser->setProperty(XMLUni::fgXercesScannerName,
const_cast<XMLCh*>(XMLUni::fgSGXMLScanner));
pSAX2Parser->setInputBufferSize(4096);
// Create SAX handler object and install it on the pSAX2Parser, as the
// document and error pSAX2Handler.
XFilterSAX2Handlers * pSAX2Handler = new XFilterSAX2Handlers;
pSAX2Parser->setContentHandler(pSAX2Handler);
pSAX2Parser->setErrorHandler(pSAX2Handler);
// Workaround/bypass until Xerces supports retrieving version from the
// <xs:schema ...> statement!
// Set 'dummy' schema version to arbitrary value > 1
pSAX2Handler->SetSchemaVersion(99);
pSAX2Handler->SetVariables(m_pAsker, &m_MapFilters, m_FPool, m_bValidation);
try
{
// Let's begin the parsing now
if (!strXMLFileName.empty()) {
pSAX2Parser->parse(_W2X(strXMLFileName.c_str()));
} else {
const char *szID = "database_filters";
const char *buffer = XMLString::transcode(_W2X(strXMLData.c_str()));
//2nd parameter must be number of bytes, so we use a length for char* repr
MemBufInputSource* memBufIS = new MemBufInputSource(
reinterpret_cast<const XMLByte *>(buffer),
XMLString::stringLen(buffer),
szID, false);
pSAX2Parser->parse(*memBufIS);
delete memBufIS;
}
}
catch (const OutOfMemoryException&)
{
LoadAString(strResultText, IDCS_XERCESOUTOFMEMORY);
bErrorOccurred = true;
}
catch (const XMLException& e)
{
strResultText = stringT(_X2ST(e.getMessage()));
bErrorOccurred = true;
}
catch (...)
{
LoadAString(strResultText, IDCS_XERCESEXCEPTION);
bErrorOccurred = true;
}
if (pSAX2Handler->getIfErrors() || bErrorOccurred) {
bErrorOccurred = true;
strResultText = pSAX2Handler->getValidationResult();
Format(m_strXMLErrors, IDSC_XERCESPARSEERROR,
m_bValidation ? cs_validation.c_str() : cs_import.c_str(),
strResultText.c_str());
} else {
m_strXMLErrors = strResultText;
}
// Delete the pSAX2Parser itself. Must be done prior to calling Terminate, below.
delete pSAX2Parser;
delete pSAX2Handler;
USES_XMLCH_STR_END
// And call the termination method
XMLPlatformUtils::Terminate();
return !bErrorOccurred;
}
#endif /* USE_XML_LIBRARY == XERCES */
<|endoftext|> |
<commit_before>/*
* SessionTutorial.cpp
*
* Copyright (C) 2009-19 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionTutorial.hpp"
#include <shared_core/json/Json.hpp>
#include <core/Exec.hpp>
#include <core/text/TemplateFilter.hpp>
#include <core/YamlUtil.hpp>
#include <r/RExec.hpp>
#include <r/RJson.hpp>
#include <r/RSexp.hpp>
#include <session/projects/SessionProjects.hpp>
#include <session/SessionPackageProvidedExtension.hpp>
#include <session/SessionModuleContext.hpp>
const char * const kTutorialLocation = "/tutorial";
const char * const kTutorialClientEventIndexingCompleted = "indexing_completed";
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace tutorial {
namespace {
FilePath tutorialResourcePath(const std::string& fileName = std::string())
{
return module_context::scopedScratchPath()
.completePath("tutorial/" + fileName);
}
struct TutorialInfo
{
std::string name;
std::string file;
std::string title;
std::string description;
};
using TutorialIndex = std::map<std::string, std::vector<TutorialInfo>>;
TutorialIndex& tutorialIndex()
{
static TutorialIndex instance;
return instance;
}
void enqueueTutorialClientEvent(const std::string& type,
const json::Value& data)
{
using namespace module_context;
json::Object eventJson;
eventJson["type"] = type;
eventJson["data"] = data;
ClientEvent event(client_events::kTutorialCommand, eventJson);
enqueClientEvent(event);
}
class TutorialWorker : public ppe::Worker
{
private:
void onIndexingStarted() override
{
index_.clear();
}
void onIndexingCompleted(core::json::Object* pPayload) override
{
tutorialIndex() = index_;
enqueueTutorialClientEvent(
kTutorialClientEventIndexingCompleted,
json::Value());
}
void onWork(const std::string& pkgName,
const core::FilePath& resourcePath) override
{
r::sexp::Protect protect;
SEXP tutorialsSEXP;
Error error = r::exec::RFunction(".rs.tutorial.findTutorials")
.addParam(resourcePath.getAbsolutePath())
.call(&tutorialsSEXP, &protect);
if (error)
{
LOG_ERROR(error);
return;
}
json::Value tutorialsJson;
error = r::json::jsonValueFromList(tutorialsSEXP, &tutorialsJson);
if (error)
{
LOG_ERROR(error);
return;
}
if (!tutorialsJson.isArray())
{
Error error(json::errc::ParamTypeMismatch, ERROR_LOCATION);
LOG_ERROR(error);
}
for (auto tutorialJson : tutorialsJson.getArray())
{
if (!tutorialJson.isObject())
{
Error error(json::errc::ParamTypeMismatch, ERROR_LOCATION);
LOG_ERROR(error);
}
TutorialInfo info;
error = json::readObject(tutorialJson.getObject(),
"name", &info.name,
"file", &info.file,
"title", &info.title,
"description", &info.description);
if (error)
{
LOG_ERROR(error);
return;
}
index_[pkgName].push_back(info);
}
}
private:
TutorialIndex index_;
};
boost::shared_ptr<TutorialWorker>& tutorialWorker()
{
static boost::shared_ptr<TutorialWorker> instance(new TutorialWorker);
return instance;
}
FilePath resourcesPath()
{
return options().rResourcesPath().completePath("tutorial_resources");
}
void handleTutorialRunRequest(const http::Request& request,
http::Response* pResponse)
{
std::string package = request.queryParamValue("package");
std::string name = request.queryParamValue("name");
// TODO: Check tutorial pre-requisites first!
Error error = r::exec::RFunction(".rs.tutorial.runTutorial")
.addParam(name)
.addParam(package)
.call();
if (error)
{
LOG_ERROR(error);
pResponse->setStatusCode(http::status::NotFound);
}
pResponse->setStatusCode(http::status::Ok);
}
void handleTutorialHomeRequest(const http::Request& request,
http::Response* pResponse)
{
using namespace string_utils;
std::stringstream ss;
if (tutorialIndex().empty())
{
ss << "<p>No tutorials are currently available.</p>";
if (!module_context::isPackageInstalled("learnr"))
{
ss << "<p>Please install the learnr package to enable tutorials for RStudio.</p>";
}
else
{
ss << "<p>Please wait while RStudio finishes indexing...</p>";
}
}
for (auto entry : tutorialIndex())
{
std::string pkgName = entry.first;
std::vector<TutorialInfo> tutorials = entry.second;
if (tutorials.empty())
continue;
for (auto tutorial : tutorials)
{
ss << "<div>";
ss << "<div class=\"rstudio-tutorials-label-container\">";
ss << "<span class=\"rstudio-tutorials-label\">"
<< htmlEscape(tutorial.title)
<< "</span>";
ss << "<span class=\"rstudio-tutorials-run-container\">"
<< "<button class=\"rstudio-tutorials-run-button\" onclick=\"window.parent.tutorialRun('" << htmlEscape(tutorial.name) << "', '" << htmlEscape(pkgName) << "')\">"
<< "<span class=\"rstudio-tutorials-run-button-label\">Start Tutorial</span>"
<< "<span class=\"rstudio-tutorials-run-button-icon\">\u25b6</span>"
<< "</button>"
<< "</span>";
ss << "</div>";
if (tutorial.description.empty())
{
ss << "<div class=\"rstudio-tutorials-description rstudio-tutorials-description-empty\">"
<< "[No description available.]"
<< "</div>";
}
else
{
ss << "<div class=\"rstudio-tutorials-description\">"
<< tutorial.description
<< "</div>";
}
ss << "</div>";
ss << "<hr class=\"rstudio-tutorials-separator\">";
}
}
std::map<std::string, std::string> vars;
std::string tutorialsHtml = ss.str();
vars["tutorials"] = tutorialsHtml;
FilePath homePath = resourcesPath().completePath("index.html");
pResponse->setFile(homePath, request, text::TemplateFilter(vars));
}
void handleTutorialFileRequest(const http::Request& request,
http::Response* pResponse)
{
FilePath resourcesPath =
options().rResourcesPath().completePath("tutorial_resources");
std::string path = http::util::pathAfterPrefix(request, "/tutorial/");
if (path.empty())
{
pResponse->setStatusCode(http::status::NotFound);
return;
}
pResponse->setCacheableFile(resourcesPath.completePath(path), request);
}
void handleTutorialRequest(const http::Request& request,
http::Response* pResponse)
{
std::string path = http::util::pathAfterPrefix(request, kTutorialLocation);
if (path == "/run")
handleTutorialRunRequest(request, pResponse);
else if (path == "/home")
handleTutorialHomeRequest(request, pResponse);
else if (boost::algorithm::ends_with(path, ".png"))
handleTutorialFileRequest(request, pResponse);
else
{
LOG_ERROR_MESSAGE("Unhandled tutorial URI '" + path + "'");
pResponse->setStatusCode(http::status::NotFound);
}
}
void onDeferredInit(bool newSession)
{
static bool s_launched = false;
if (s_launched)
return;
using namespace projects;
if (!projectContext().hasProject())
return;
std::string defaultTutorial = projectContext().config().defaultTutorial;
if (defaultTutorial.empty())
return;
std::vector<std::string> parts = core::algorithm::split(defaultTutorial, "::");
if (parts.size() != 2)
{
LOG_WARNING_MESSAGE("Unexpected DefaultTutorial field: " + defaultTutorial);
return;
}
json::Object data;
data["package"] = parts[0];
data["name"] = parts[1];
ClientEvent event(client_events::kTutorialLaunch, data);
module_context::enqueClientEvent(event);
s_launched = true;
}
void onSuspend(const r::session::RSuspendOptions& suspendOptions,
Settings* pSettings)
{
Error error = r::exec::RFunction(".rs.tutorial.onSuspend")
.addParam(tutorialResourcePath("tutorial-state").getAbsolutePath())
.call();
if (error)
LOG_ERROR(error);
}
void onResume(const Settings& settings)
{
Error error = r::exec::RFunction(".rs.tutorial.onResume")
.addParam(tutorialResourcePath("tutorial-state").getAbsolutePath())
.call();
if (error)
LOG_ERROR(error);
}
} // end anonymous namespace
Error initialize()
{
using namespace module_context;
ppe::indexer().addWorker(tutorialWorker());
events().onDeferredInit.connect(onDeferredInit);
addSuspendHandler(SuspendHandler(onSuspend, onResume));
Error error = tutorialResourcePath().ensureDirectory();
if (error)
LOG_ERROR(error);
using boost::bind;
ExecBlock initBlock;
initBlock.addFunctions()
(bind(registerUriHandler, kTutorialLocation, handleTutorialRequest))
(bind(sourceModuleRFile, "SessionTutorial.R"));
return initBlock.execute();
}
} // end namespace tutorial
} // end namespace modules
} // end namespace session
} // end namespace rstudio
<commit_msg>render markdown included in tutorial description<commit_after>/*
* SessionTutorial.cpp
*
* Copyright (C) 2009-19 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionTutorial.hpp"
#include <shared_core/json/Json.hpp>
#include <core/Exec.hpp>
#include <core/markdown/Markdown.hpp>
#include <core/text/TemplateFilter.hpp>
#include <core/YamlUtil.hpp>
#include <r/RExec.hpp>
#include <r/RJson.hpp>
#include <r/RSexp.hpp>
#include <session/projects/SessionProjects.hpp>
#include <session/SessionPackageProvidedExtension.hpp>
#include <session/SessionModuleContext.hpp>
const char * const kTutorialLocation = "/tutorial";
const char * const kTutorialClientEventIndexingCompleted = "indexing_completed";
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace tutorial {
namespace {
FilePath tutorialResourcePath(const std::string& fileName = std::string())
{
return module_context::scopedScratchPath()
.completePath("tutorial/" + fileName);
}
struct TutorialInfo
{
std::string name;
std::string file;
std::string title;
std::string description;
};
using TutorialIndex = std::map<std::string, std::vector<TutorialInfo>>;
TutorialIndex& tutorialIndex()
{
static TutorialIndex instance;
return instance;
}
void enqueueTutorialClientEvent(const std::string& type,
const json::Value& data)
{
using namespace module_context;
json::Object eventJson;
eventJson["type"] = type;
eventJson["data"] = data;
ClientEvent event(client_events::kTutorialCommand, eventJson);
enqueClientEvent(event);
}
class TutorialWorker : public ppe::Worker
{
private:
void onIndexingStarted() override
{
index_.clear();
}
void onIndexingCompleted(core::json::Object* pPayload) override
{
tutorialIndex() = index_;
enqueueTutorialClientEvent(
kTutorialClientEventIndexingCompleted,
json::Value());
}
void onWork(const std::string& pkgName,
const core::FilePath& resourcePath) override
{
r::sexp::Protect protect;
SEXP tutorialsSEXP;
Error error = r::exec::RFunction(".rs.tutorial.findTutorials")
.addParam(resourcePath.getAbsolutePath())
.call(&tutorialsSEXP, &protect);
if (error)
{
LOG_ERROR(error);
return;
}
json::Value tutorialsJson;
error = r::json::jsonValueFromList(tutorialsSEXP, &tutorialsJson);
if (error)
{
LOG_ERROR(error);
return;
}
if (!tutorialsJson.isArray())
{
Error error(json::errc::ParamTypeMismatch, ERROR_LOCATION);
LOG_ERROR(error);
}
for (auto tutorialJson : tutorialsJson.getArray())
{
if (!tutorialJson.isObject())
{
Error error(json::errc::ParamTypeMismatch, ERROR_LOCATION);
LOG_ERROR(error);
}
TutorialInfo info;
error = json::readObject(tutorialJson.getObject(),
"name", &info.name,
"file", &info.file,
"title", &info.title,
"description", &info.description);
if (error)
{
LOG_ERROR(error);
return;
}
index_[pkgName].push_back(info);
}
}
private:
TutorialIndex index_;
};
boost::shared_ptr<TutorialWorker>& tutorialWorker()
{
static boost::shared_ptr<TutorialWorker> instance(new TutorialWorker);
return instance;
}
FilePath resourcesPath()
{
return options().rResourcesPath().completePath("tutorial_resources");
}
void handleTutorialRunRequest(const http::Request& request,
http::Response* pResponse)
{
std::string package = request.queryParamValue("package");
std::string name = request.queryParamValue("name");
// TODO: Check tutorial pre-requisites first!
Error error = r::exec::RFunction(".rs.tutorial.runTutorial")
.addParam(name)
.addParam(package)
.call();
if (error)
{
LOG_ERROR(error);
pResponse->setStatusCode(http::status::NotFound);
}
pResponse->setStatusCode(http::status::Ok);
}
void handleTutorialHomeRequest(const http::Request& request,
http::Response* pResponse)
{
using namespace string_utils;
std::stringstream ss;
if (tutorialIndex().empty())
{
ss << "<p>No tutorials are currently available.</p>";
if (!module_context::isPackageInstalled("learnr"))
{
ss << "<p>Please install the learnr package to enable tutorials for RStudio.</p>";
}
else
{
ss << "<p>Please wait while RStudio finishes indexing...</p>";
}
}
for (auto entry : tutorialIndex())
{
std::string pkgName = entry.first;
std::vector<TutorialInfo> tutorials = entry.second;
if (tutorials.empty())
continue;
for (auto tutorial : tutorials)
{
ss << "<div>";
ss << "<div class=\"rstudio-tutorials-label-container\">";
ss << "<span class=\"rstudio-tutorials-label\">"
<< htmlEscape(tutorial.title)
<< "</span>";
ss << "<span class=\"rstudio-tutorials-run-container\">"
<< "<button class=\"rstudio-tutorials-run-button\" onclick=\"window.parent.tutorialRun('" << htmlEscape(tutorial.name) << "', '" << htmlEscape(pkgName) << "')\">"
<< "<span class=\"rstudio-tutorials-run-button-label\">Start Tutorial</span>"
<< "<span class=\"rstudio-tutorials-run-button-icon\">\u25b6</span>"
<< "</button>"
<< "</span>";
ss << "</div>";
if (tutorial.description.empty())
{
ss << "<div class=\"rstudio-tutorials-description rstudio-tutorials-description-empty\">"
<< "[No description available.]"
<< "</div>";
}
else
{
std::string descriptionHtml;
Error error = core::markdown::markdownToHTML(
tutorial.description,
core::markdown::Extensions(),
core::markdown::HTMLOptions(),
&descriptionHtml);
if (error)
{
LOG_ERROR(error);
descriptionHtml = tutorial.description;
}
ss << "<div class=\"rstudio-tutorials-description\">"
<< descriptionHtml
<< "</div>";
}
ss << "</div>";
ss << "<hr class=\"rstudio-tutorials-separator\">";
}
}
std::map<std::string, std::string> vars;
std::string tutorialsHtml = ss.str();
vars["tutorials"] = tutorialsHtml;
FilePath homePath = resourcesPath().completePath("index.html");
pResponse->setFile(homePath, request, text::TemplateFilter(vars));
}
void handleTutorialFileRequest(const http::Request& request,
http::Response* pResponse)
{
FilePath resourcesPath =
options().rResourcesPath().completePath("tutorial_resources");
std::string path = http::util::pathAfterPrefix(request, "/tutorial/");
if (path.empty())
{
pResponse->setStatusCode(http::status::NotFound);
return;
}
pResponse->setCacheableFile(resourcesPath.completePath(path), request);
}
void handleTutorialRequest(const http::Request& request,
http::Response* pResponse)
{
std::string path = http::util::pathAfterPrefix(request, kTutorialLocation);
if (path == "/run")
handleTutorialRunRequest(request, pResponse);
else if (path == "/home")
handleTutorialHomeRequest(request, pResponse);
else if (boost::algorithm::ends_with(path, ".png"))
handleTutorialFileRequest(request, pResponse);
else
{
LOG_ERROR_MESSAGE("Unhandled tutorial URI '" + path + "'");
pResponse->setStatusCode(http::status::NotFound);
}
}
void onDeferredInit(bool newSession)
{
static bool s_launched = false;
if (s_launched)
return;
using namespace projects;
if (!projectContext().hasProject())
return;
std::string defaultTutorial = projectContext().config().defaultTutorial;
if (defaultTutorial.empty())
return;
std::vector<std::string> parts = core::algorithm::split(defaultTutorial, "::");
if (parts.size() != 2)
{
LOG_WARNING_MESSAGE("Unexpected DefaultTutorial field: " + defaultTutorial);
return;
}
json::Object data;
data["package"] = parts[0];
data["name"] = parts[1];
ClientEvent event(client_events::kTutorialLaunch, data);
module_context::enqueClientEvent(event);
s_launched = true;
}
void onSuspend(const r::session::RSuspendOptions& suspendOptions,
Settings* pSettings)
{
Error error = r::exec::RFunction(".rs.tutorial.onSuspend")
.addParam(tutorialResourcePath("tutorial-state").getAbsolutePath())
.call();
if (error)
LOG_ERROR(error);
}
void onResume(const Settings& settings)
{
Error error = r::exec::RFunction(".rs.tutorial.onResume")
.addParam(tutorialResourcePath("tutorial-state").getAbsolutePath())
.call();
if (error)
LOG_ERROR(error);
}
} // end anonymous namespace
Error initialize()
{
using namespace module_context;
ppe::indexer().addWorker(tutorialWorker());
events().onDeferredInit.connect(onDeferredInit);
addSuspendHandler(SuspendHandler(onSuspend, onResume));
Error error = tutorialResourcePath().ensureDirectory();
if (error)
LOG_ERROR(error);
using boost::bind;
ExecBlock initBlock;
initBlock.addFunctions()
(bind(registerUriHandler, kTutorialLocation, handleTutorialRequest))
(bind(sourceModuleRFile, "SessionTutorial.R"));
return initBlock.execute();
}
} // end namespace tutorial
} // end namespace modules
} // end namespace session
} // end namespace rstudio
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQuick.Dialogs module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qquickplatformmessagedialog_p.h"
#include "qquickitem.h"
#include <private/qguiapplication_p.h>
#include <QWindow>
#include <QQuickView>
#include <QQuickWindow>
QT_BEGIN_NAMESPACE
/*!
\qmltype MessageDialog
\instantiates QQuickPlatformMessageDialog
\inqmlmodule QtQuick.Dialogs 1
\ingroup dialogs
\brief Dialog component for displaying popup messages.
\since 5.2
The most basic use case for a MessageDialog is a popup alert. It also
allows the user to respond in various ways depending on which buttons are
enabled. The dialog is initially invisible. You need to set the properties
as desired first, then set \l visible to \c true or call \l open().
Here is a minimal example to show an alert and exit after the user
responds:
\qml
import QtQuick 2.2
import QtQuick.Dialogs 1.1
MessageDialog {
id: messageDialog
title: "May I have your attention please"
text: "It's so cool that you are using Qt Quick."
onAccepted: {
console.log("And of course you could only agree.")
Qt.quit()
}
Component.onCompleted: visible = true
}
\endqml
There are several possible handlers depending on which \l standardButtons
the dialog has and the \l {QMessageBox::ButtonRole} {ButtonRole} of each.
For example, the \l {rejected} {onRejected} handler will be called if the
user presses a \gui Cancel, \gui Close or \gui Abort button.
A MessageDialog window is automatically transient for its parent window. So
whether you declare the dialog inside an \l Item or inside a \l Window, the
dialog will appear centered over the window containing the item, or over
the Window that you declared.
The implementation of MessageDialog will be a platform message dialog if
possible. If that isn't possible, then it will try to instantiate a
\l QMessageBox. If that also isn't possible, then it will fall back to a QML
implementation, \c DefaultMessageDialog.qml. In that case you can customize
the appearance by editing this file. \c DefaultMessageDialog.qml contains a
\l Rectangle to hold the dialog's contents, because certain embedded systems
do not support multiple top-level windows. When the dialog becomes visible,
it will automatically be wrapped in a \l Window if possible, or simply
reparented on top of the main window if there can only be one window.
*/
/*!
\qmlsignal MessageDialog::accepted()
This handler is called when the user has pressed any button which has the
\l {QMessageBox::AcceptRole} {AcceptRole}: \gui OK, \gui Open, \gui Save,
\gui {Save All}, \gui Retry or \gui Ignore.
*/
/*!
\qmlsignal MessageDialog::rejected()
This handler is called when the user has dismissed the dialog, by closing
the dialog window, by pressing a \gui Cancel, \gui Close or \gui Abort
button on the dialog, or by pressing the back button or the escape key.
*/
/*!
\qmlsignal MessageDialog::discard()
This handler is called when the user has pressed the \gui Discard button.
*/
/*!
\qmlsignal MessageDialog::help()
This handler is called when the user has pressed the \gui Help button.
Depending on platform, the dialog may not be automatically dismissed
because the help that your application provides may need to be relevant to
the text shown in this dialog in order to assist the user in making a
decision. However on other platforms it's not possible to show a dialog and
a help window at the same time. If you want to be sure that the dialog will
close, you can set \l visible to \c false in your handler.
*/
/*!
\qmlsignal MessageDialog::yes()
This handler is called when the user has pressed any button which has
the \l {QMessageBox::YesRole} {YesRole}: \gui Yes or \gui {Yes to All}.
*/
/*!
\qmlsignal MessageDialog::no()
This handler is called when the user has pressed any button which has
the \l {QMessageBox::NoRole} {NoRole}: \gui No or \gui {No to All}.
*/
/*!
\qmlsignal MessageDialog::apply()
This handler is called when the user has pressed the \gui Apply button.
*/
/*!
\qmlsignal MessageDialog::reset()
This handler is called when the user has pressed any button which has
the \l {QMessageBox::ResetRole} {ResetRole}: \gui Reset or \gui {Restore Defaults}.
*/
/*!
\class QQuickPlatformMessageDialog
\inmodule QtQuick.Dialogs
\internal
\brief The QQuickPlatformMessageDialog class provides a message dialog
The dialog is implemented via the QPlatformMessageDialogHelper when possible;
otherwise it falls back to a QMessageBox or a QML implementation.
\since 5.2
*/
/*!
Constructs a file dialog with parent window \a parent.
*/
QQuickPlatformMessageDialog::QQuickPlatformMessageDialog(QObject *parent) :
QQuickAbstractMessageDialog(parent)
{
}
/*!
Destroys the file dialog.
*/
QQuickPlatformMessageDialog::~QQuickPlatformMessageDialog()
{
if (m_dlgHelper)
m_dlgHelper->hide();
delete m_dlgHelper;
}
QPlatformMessageDialogHelper *QQuickPlatformMessageDialog::helper()
{
QQuickItem *parentItem = qobject_cast<QQuickItem *>(parent());
if (parentItem)
m_parentWindow = parentItem->window();
if ( !m_dlgHelper && QGuiApplicationPrivate::platformTheme()->
usePlatformNativeDialog(QPlatformTheme::MessageDialog) ) {
m_dlgHelper = static_cast<QPlatformMessageDialogHelper *>(QGuiApplicationPrivate::platformTheme()
->createPlatformDialogHelper(QPlatformTheme::MessageDialog));
if (!m_dlgHelper)
return m_dlgHelper;
// accept() shouldn't be emitted. reject() happens only if the dialog is
// dismissed by closing the window rather than by one of its button widgets.
connect(m_dlgHelper, SIGNAL(accept()), this, SLOT(accept()));
connect(m_dlgHelper, SIGNAL(reject()), this, SLOT(reject()));
connect(m_dlgHelper, SIGNAL(clicked(QMessageDialogOptions::StandardButton,QMessageDialogOptions::ButtonRole)),
this, SLOT(click(QMessageDialogOptions::StandardButton,QMessageDialogOptions::ButtonRole)));
}
return m_dlgHelper;
}
/*!
\qmlproperty bool MessageDialog::visible
This property holds whether the dialog is visible. By default this is
\c false.
\sa modality
*/
/*!
\qmlproperty Qt::WindowModality MessageDialog::modality
Whether the dialog should be shown modal with respect to the window
containing the dialog's parent Item, modal with respect to the whole
application, or non-modal.
By default it is \c Qt.WindowModal.
Modality does not mean that there are any blocking calls to wait for the
dialog to be accepted or rejected; it's only that the user will be
prevented from interacting with the parent window and/or the application
windows until the dialog is dismissed.
*/
/*!
\qmlmethod void MessageDialog::open()
Shows the dialog to the user. It is equivalent to setting \l visible to
\c true.
*/
/*!
\qmlmethod void MessageDialog::close()
Closes the dialog.
*/
/*!
\qmlproperty string MessageDialog::title
The title of the dialog window.
*/
/*!
\qmlproperty string MessageDialog::text
The primary text to be displayed.
*/
/*!
\qmlproperty string MessageDialog::informativeText
The informative text that provides a fuller description for the message.
Informative text can be used to supplement the \c text to give more
information to the user. Depending on the platform, it may appear in a
smaller font below the text, or simply appended to the text.
\sa {MessageDialog::text}{text}
*/
/*!
\qmlproperty string MessageDialog::detailedText
The text to be displayed in the details area, which is hidden by default.
The user will then be able to press the \gui {Show Details...} button to
make it visible.
\sa {MessageDialog::text}{text}
*/
/*!
\enum QQuickStandardIcon::Icon
This enum specifies a standard icon to be used on a dialog.
*/
/*!
\qmlproperty QQuickStandardIcon::Icon MessageDialog::icon
The icon of the message box can be specified with one of these values:
\table
\row
\li no icon
\li \l StandardIcon.NoIcon
\li For an unadorned text alert.
\row
\li \inlineimage ../images/question.png "Question icon"
\li \l StandardIcon.Question
\li For asking a question during normal operations.
\row
\li \image information.png
\li \l StandardIcon.Information
\li For reporting information about normal operations.
\row
\li \image warning.png
\li \l StandardIcon.Warning
\li For reporting non-critical errors.
\row
\li \image critical.png
\li \l StandardIcon.Critical
\li For reporting critical errors.
\endtable
The default is \c StandardIcon.NoIcon.
The enum values are the same as in \l QMessageBox::Icon.
*/
// TODO after QTBUG-35019 is fixed: fix links to this module's enums
// rather than linking to those in QMessageBox
/*!
\enum QQuickStandardButton::StandardButton
This enum specifies a button with a standard label to be used on a dialog.
*/
/*!
\qmlproperty StandardButtons MessageDialog::standardButtons
The MessageDialog has a row of buttons along the bottom, each of which has
a \l {QMessageBox::ButtonRole} {ButtonRole} that determines which signal
will be emitted when the button is pressed. You can also find out which
specific button was pressed after the fact via the \l clickedButton
property. You can control which buttons are available by setting
standardButtons to a bitwise-or combination of the following flags:
\table
\row \li StandardButton.Ok \li An \gui OK button defined with the \l {QMessageBox::AcceptRole} {AcceptRole}.
\row \li StandardButton.Open \li An \gui Open button defined with the \l {QMessageBox::AcceptRole} {AcceptRole}.
\row \li StandardButton.Save \li A \gui Save button defined with the \l {QMessageBox::AcceptRole} {AcceptRole}.
\row \li StandardButton.Cancel \li A \gui Cancel button defined with the \l {QMessageBox::RejectRole} {RejectRole}.
\row \li StandardButton.Close \li A \gui Close button defined with the \l {QMessageBox::RejectRole} {RejectRole}.
\row \li StandardButton.Discard \li A \gui Discard or \gui {Don't Save} button, depending on the platform,
defined with the \l {QMessageBox::DestructiveRole} {DestructiveRole}.
\row \li StandardButton.Apply \li An \gui Apply button defined with the \l {QMessageBox::ApplyRole} {ApplyRole}.
\row \li StandardButton.Reset \li A \gui Reset button defined with the \l {QMessageBox::ResetRole} {ResetRole}.
\row \li StandardButton.RestoreDefaults \li A \gui {Restore Defaults} button defined with the \l {QMessageBox::ResetRole} {ResetRole}.
\row \li StandardButton.Help \li A \gui Help button defined with the \l {QMessageBox::HelpRole} {HelpRole}.
\row \li StandardButton.SaveAll \li A \gui {Save All} button defined with the \l {QMessageBox::AcceptRole} {AcceptRole}.
\row \li StandardButton.Yes \li A \gui Yes button defined with the \l {QMessageBox::YesRole} {YesRole}.
\row \li StandardButton.YesToAll \li A \gui {Yes to All} button defined with the \l {QMessageBox::YesRole} {YesRole}.
\row \li StandardButton.No \li A \gui No button defined with the \l {QMessageBox::NoRole} {NoRole}.
\row \li StandardButton.NoToAll \li A \gui {No to All} button defined with the \l {QMessageBox::NoRole} {NoRole}.
\row \li StandardButton.Abort \li An \gui Abort button defined with the \l {QMessageBox::RejectRole} {RejectRole}.
\row \li StandardButton.Retry \li A \gui Retry button defined with the \l {QMessageBox::AcceptRole} {AcceptRole}.
\row \li StandardButton.Ignore \li An \gui Ignore button defined with the \l {QMessageBox::AcceptRole} {AcceptRole}.
\endtable
For example the following dialog will ask a question with 5 possible answers:
\qml
import QtQuick 2.2
import QtQuick.Dialogs 1.1
MessageDialog {
title: "Overwrite?"
icon: StandardIcon.Question
text: "file.txt already exists. Replace?"
detailedText: "To replace a file means that its existing contents will be lost. " +
"The file that you are copying now will be copied over it instead."
standardButtons: StandardButton.Yes | StandardButton.YesToAll |
StandardButton.No | StandardButton.NoToAll | StandardButton.Abort
Component.onCompleted: visible = true
onYes: console.log("copied")
onNo: console.log("didn't copy")
onRejected: console.log("aborted")
}
\endqml
\image replacefile.png
The default is \c StandardButton.Ok.
The enum values are the same as in \l QMessageBox::StandardButtons.
*/
QT_END_NAMESPACE
<commit_msg>Native MessageDialog: connect the new version of the clicked signal<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQuick.Dialogs module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qquickplatformmessagedialog_p.h"
#include "qquickitem.h"
#include <private/qguiapplication_p.h>
#include <QWindow>
#include <QQuickView>
#include <QQuickWindow>
QT_BEGIN_NAMESPACE
/*!
\qmltype MessageDialog
\instantiates QQuickPlatformMessageDialog
\inqmlmodule QtQuick.Dialogs 1
\ingroup dialogs
\brief Dialog component for displaying popup messages.
\since 5.2
The most basic use case for a MessageDialog is a popup alert. It also
allows the user to respond in various ways depending on which buttons are
enabled. The dialog is initially invisible. You need to set the properties
as desired first, then set \l visible to \c true or call \l open().
Here is a minimal example to show an alert and exit after the user
responds:
\qml
import QtQuick 2.2
import QtQuick.Dialogs 1.1
MessageDialog {
id: messageDialog
title: "May I have your attention please"
text: "It's so cool that you are using Qt Quick."
onAccepted: {
console.log("And of course you could only agree.")
Qt.quit()
}
Component.onCompleted: visible = true
}
\endqml
There are several possible handlers depending on which \l standardButtons
the dialog has and the \l {QMessageBox::ButtonRole} {ButtonRole} of each.
For example, the \l {rejected} {onRejected} handler will be called if the
user presses a \gui Cancel, \gui Close or \gui Abort button.
A MessageDialog window is automatically transient for its parent window. So
whether you declare the dialog inside an \l Item or inside a \l Window, the
dialog will appear centered over the window containing the item, or over
the Window that you declared.
The implementation of MessageDialog will be a platform message dialog if
possible. If that isn't possible, then it will try to instantiate a
\l QMessageBox. If that also isn't possible, then it will fall back to a QML
implementation, \c DefaultMessageDialog.qml. In that case you can customize
the appearance by editing this file. \c DefaultMessageDialog.qml contains a
\l Rectangle to hold the dialog's contents, because certain embedded systems
do not support multiple top-level windows. When the dialog becomes visible,
it will automatically be wrapped in a \l Window if possible, or simply
reparented on top of the main window if there can only be one window.
*/
/*!
\qmlsignal MessageDialog::accepted()
This handler is called when the user has pressed any button which has the
\l {QMessageBox::AcceptRole} {AcceptRole}: \gui OK, \gui Open, \gui Save,
\gui {Save All}, \gui Retry or \gui Ignore.
*/
/*!
\qmlsignal MessageDialog::rejected()
This handler is called when the user has dismissed the dialog, by closing
the dialog window, by pressing a \gui Cancel, \gui Close or \gui Abort
button on the dialog, or by pressing the back button or the escape key.
*/
/*!
\qmlsignal MessageDialog::discard()
This handler is called when the user has pressed the \gui Discard button.
*/
/*!
\qmlsignal MessageDialog::help()
This handler is called when the user has pressed the \gui Help button.
Depending on platform, the dialog may not be automatically dismissed
because the help that your application provides may need to be relevant to
the text shown in this dialog in order to assist the user in making a
decision. However on other platforms it's not possible to show a dialog and
a help window at the same time. If you want to be sure that the dialog will
close, you can set \l visible to \c false in your handler.
*/
/*!
\qmlsignal MessageDialog::yes()
This handler is called when the user has pressed any button which has
the \l {QMessageBox::YesRole} {YesRole}: \gui Yes or \gui {Yes to All}.
*/
/*!
\qmlsignal MessageDialog::no()
This handler is called when the user has pressed any button which has
the \l {QMessageBox::NoRole} {NoRole}: \gui No or \gui {No to All}.
*/
/*!
\qmlsignal MessageDialog::apply()
This handler is called when the user has pressed the \gui Apply button.
*/
/*!
\qmlsignal MessageDialog::reset()
This handler is called when the user has pressed any button which has
the \l {QMessageBox::ResetRole} {ResetRole}: \gui Reset or \gui {Restore Defaults}.
*/
/*!
\class QQuickPlatformMessageDialog
\inmodule QtQuick.Dialogs
\internal
\brief The QQuickPlatformMessageDialog class provides a message dialog
The dialog is implemented via the QPlatformMessageDialogHelper when possible;
otherwise it falls back to a QMessageBox or a QML implementation.
\since 5.2
*/
/*!
Constructs a file dialog with parent window \a parent.
*/
QQuickPlatformMessageDialog::QQuickPlatformMessageDialog(QObject *parent) :
QQuickAbstractMessageDialog(parent)
{
}
/*!
Destroys the file dialog.
*/
QQuickPlatformMessageDialog::~QQuickPlatformMessageDialog()
{
if (m_dlgHelper)
m_dlgHelper->hide();
delete m_dlgHelper;
}
QPlatformMessageDialogHelper *QQuickPlatformMessageDialog::helper()
{
QQuickItem *parentItem = qobject_cast<QQuickItem *>(parent());
if (parentItem)
m_parentWindow = parentItem->window();
if ( !m_dlgHelper && QGuiApplicationPrivate::platformTheme()->
usePlatformNativeDialog(QPlatformTheme::MessageDialog) ) {
m_dlgHelper = static_cast<QPlatformMessageDialogHelper *>(QGuiApplicationPrivate::platformTheme()
->createPlatformDialogHelper(QPlatformTheme::MessageDialog));
if (!m_dlgHelper)
return m_dlgHelper;
// accept() shouldn't be emitted. reject() happens only if the dialog is
// dismissed by closing the window rather than by one of its button widgets.
connect(m_dlgHelper, SIGNAL(accept()), this, SLOT(accept()));
connect(m_dlgHelper, SIGNAL(reject()), this, SLOT(reject()));
connect(m_dlgHelper, SIGNAL(clicked(QPlatformDialogHelper::StandardButton,QPlatformDialogHelper::ButtonRole)),
this, SLOT(click(QPlatformDialogHelper::StandardButton,QPlatformDialogHelper::ButtonRole)));
}
return m_dlgHelper;
}
/*!
\qmlproperty bool MessageDialog::visible
This property holds whether the dialog is visible. By default this is
\c false.
\sa modality
*/
/*!
\qmlproperty Qt::WindowModality MessageDialog::modality
Whether the dialog should be shown modal with respect to the window
containing the dialog's parent Item, modal with respect to the whole
application, or non-modal.
By default it is \c Qt.WindowModal.
Modality does not mean that there are any blocking calls to wait for the
dialog to be accepted or rejected; it's only that the user will be
prevented from interacting with the parent window and/or the application
windows until the dialog is dismissed.
*/
/*!
\qmlmethod void MessageDialog::open()
Shows the dialog to the user. It is equivalent to setting \l visible to
\c true.
*/
/*!
\qmlmethod void MessageDialog::close()
Closes the dialog.
*/
/*!
\qmlproperty string MessageDialog::title
The title of the dialog window.
*/
/*!
\qmlproperty string MessageDialog::text
The primary text to be displayed.
*/
/*!
\qmlproperty string MessageDialog::informativeText
The informative text that provides a fuller description for the message.
Informative text can be used to supplement the \c text to give more
information to the user. Depending on the platform, it may appear in a
smaller font below the text, or simply appended to the text.
\sa {MessageDialog::text}{text}
*/
/*!
\qmlproperty string MessageDialog::detailedText
The text to be displayed in the details area, which is hidden by default.
The user will then be able to press the \gui {Show Details...} button to
make it visible.
\sa {MessageDialog::text}{text}
*/
/*!
\enum QQuickStandardIcon::Icon
This enum specifies a standard icon to be used on a dialog.
*/
/*!
\qmlproperty QQuickStandardIcon::Icon MessageDialog::icon
The icon of the message box can be specified with one of these values:
\table
\row
\li no icon
\li \l StandardIcon.NoIcon
\li For an unadorned text alert.
\row
\li \inlineimage ../images/question.png "Question icon"
\li \l StandardIcon.Question
\li For asking a question during normal operations.
\row
\li \image information.png
\li \l StandardIcon.Information
\li For reporting information about normal operations.
\row
\li \image warning.png
\li \l StandardIcon.Warning
\li For reporting non-critical errors.
\row
\li \image critical.png
\li \l StandardIcon.Critical
\li For reporting critical errors.
\endtable
The default is \c StandardIcon.NoIcon.
The enum values are the same as in \l QMessageBox::Icon.
*/
// TODO after QTBUG-35019 is fixed: fix links to this module's enums
// rather than linking to those in QMessageBox
/*!
\enum QQuickStandardButton::StandardButton
This enum specifies a button with a standard label to be used on a dialog.
*/
/*!
\qmlproperty StandardButtons MessageDialog::standardButtons
The MessageDialog has a row of buttons along the bottom, each of which has
a \l {QMessageBox::ButtonRole} {ButtonRole} that determines which signal
will be emitted when the button is pressed. You can also find out which
specific button was pressed after the fact via the \l clickedButton
property. You can control which buttons are available by setting
standardButtons to a bitwise-or combination of the following flags:
\table
\row \li StandardButton.Ok \li An \gui OK button defined with the \l {QMessageBox::AcceptRole} {AcceptRole}.
\row \li StandardButton.Open \li An \gui Open button defined with the \l {QMessageBox::AcceptRole} {AcceptRole}.
\row \li StandardButton.Save \li A \gui Save button defined with the \l {QMessageBox::AcceptRole} {AcceptRole}.
\row \li StandardButton.Cancel \li A \gui Cancel button defined with the \l {QMessageBox::RejectRole} {RejectRole}.
\row \li StandardButton.Close \li A \gui Close button defined with the \l {QMessageBox::RejectRole} {RejectRole}.
\row \li StandardButton.Discard \li A \gui Discard or \gui {Don't Save} button, depending on the platform,
defined with the \l {QMessageBox::DestructiveRole} {DestructiveRole}.
\row \li StandardButton.Apply \li An \gui Apply button defined with the \l {QMessageBox::ApplyRole} {ApplyRole}.
\row \li StandardButton.Reset \li A \gui Reset button defined with the \l {QMessageBox::ResetRole} {ResetRole}.
\row \li StandardButton.RestoreDefaults \li A \gui {Restore Defaults} button defined with the \l {QMessageBox::ResetRole} {ResetRole}.
\row \li StandardButton.Help \li A \gui Help button defined with the \l {QMessageBox::HelpRole} {HelpRole}.
\row \li StandardButton.SaveAll \li A \gui {Save All} button defined with the \l {QMessageBox::AcceptRole} {AcceptRole}.
\row \li StandardButton.Yes \li A \gui Yes button defined with the \l {QMessageBox::YesRole} {YesRole}.
\row \li StandardButton.YesToAll \li A \gui {Yes to All} button defined with the \l {QMessageBox::YesRole} {YesRole}.
\row \li StandardButton.No \li A \gui No button defined with the \l {QMessageBox::NoRole} {NoRole}.
\row \li StandardButton.NoToAll \li A \gui {No to All} button defined with the \l {QMessageBox::NoRole} {NoRole}.
\row \li StandardButton.Abort \li An \gui Abort button defined with the \l {QMessageBox::RejectRole} {RejectRole}.
\row \li StandardButton.Retry \li A \gui Retry button defined with the \l {QMessageBox::AcceptRole} {AcceptRole}.
\row \li StandardButton.Ignore \li An \gui Ignore button defined with the \l {QMessageBox::AcceptRole} {AcceptRole}.
\endtable
For example the following dialog will ask a question with 5 possible answers:
\qml
import QtQuick 2.2
import QtQuick.Dialogs 1.1
MessageDialog {
title: "Overwrite?"
icon: StandardIcon.Question
text: "file.txt already exists. Replace?"
detailedText: "To replace a file means that its existing contents will be lost. " +
"The file that you are copying now will be copied over it instead."
standardButtons: StandardButton.Yes | StandardButton.YesToAll |
StandardButton.No | StandardButton.NoToAll | StandardButton.Abort
Component.onCompleted: visible = true
onYes: console.log("copied")
onNo: console.log("didn't copy")
onRejected: console.log("aborted")
}
\endqml
\image replacefile.png
The default is \c StandardButton.Ok.
The enum values are the same as in \l QMessageBox::StandardButtons.
*/
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
#include <sstream>
// StdAir
#include <stdair/basic/BasConst_General.hpp>
#include <stdair/basic/BasConst_Inventory.hpp>
#include <stdair/basic/RandomGeneration.hpp>
#include <stdair/bom/BookingClass.hpp>
namespace stdair {
// ////////////////////////////////////////////////////////////////////
BookingClass::BookingClass() : _key (DEFAULT_CLASS_CODE), _parent (NULL) {
assert (false);
}
// ////////////////////////////////////////////////////////////////////
BookingClass::BookingClass (const BookingClass&)
: _key (DEFAULT_CLASS_CODE), _parent (NULL) {
assert (false);
}
// ////////////////////////////////////////////////////////////////////
BookingClass::BookingClass (const Key_T& iKey)
: _key (iKey), _parent (NULL), _cumulatedProtection (0.0),
_protection (0.0), _cumulatedBookingLimit (0.0), _au (0.0), _nego (0.0),
_noShowPercentage (0.0), _cancellationPercentage (0.0),
_nbOfBookings (0.0), _groupNbOfBookings (0.0),
_groupPendingNbOfBookings (0.0), _staffNbOfBookings (0.0),
_wlNbOfBookings (0.0), _nbOfCancellations (0.), _etb (0.0),
_netClassAvailability (0.0), _segmentAvailability (0.0),
_netRevenueAvailability (0.0), _yield (0.0), _mean (0.0), _stdDev (0.0) {
}
// ////////////////////////////////////////////////////////////////////
BookingClass::~BookingClass() {
}
// ////////////////////////////////////////////////////////////////////
std::string BookingClass::toString() const {
std::ostringstream oStr;
oStr << describeKey();
return oStr.str();
}
// ////////////////////////////////////////////////////////////////////
void BookingClass::sell (const NbOfBookings_T& iNbOfBookings) {
_nbOfBookings += iNbOfBookings;
}
// ////////////////////////////////////////////////////////////////////
void BookingClass::cancel (const NbOfBookings_T& iNbOfCancellations) {
_nbOfBookings -= iNbOfCancellations;
_nbOfCancellations += iNbOfCancellations;
}
// ////////////////////////////////////////////////////////////////////
void BookingClass::generateDemandSamples (const int& K) {
_generatedDemandVector.clear();
if (_stdDev > 0) {
RandomGeneration lGenerator (DEFAULT_RANDOM_SEED);
for (int i = 0; i < K; ++i) {
RealNumber_T lDemandSample = lGenerator.generateNormal (_mean, _stdDev);
_generatedDemandVector.push_back (lDemandSample);
}
}
}
// ////////////////////////////////////////////////////////////////////
void BookingClass::generateDemandSamples (const int& K,
const RandomSeed_T& iSeed) {
_generatedDemandVector.clear();
if (_stdDev > 0) {
RandomGeneration lGenerator (iSeed);
for (int i = 0; i < K; ++i) {
RealNumber_T lDemandSample = lGenerator.generateNormal (_mean, _stdDev);
_generatedDemandVector.push_back (lDemandSample);
}
}
}
}
<commit_msg>[Dev] Added the missing initialization of the sub class code in Booking Class constructor.<commit_after>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
#include <sstream>
// StdAir
#include <stdair/basic/BasConst_General.hpp>
#include <stdair/basic/BasConst_Inventory.hpp>
#include <stdair/basic/RandomGeneration.hpp>
#include <stdair/bom/BookingClass.hpp>
namespace stdair {
// ////////////////////////////////////////////////////////////////////
BookingClass::BookingClass() : _key (DEFAULT_CLASS_CODE), _parent (NULL) {
assert (false);
}
// ////////////////////////////////////////////////////////////////////
BookingClass::BookingClass (const BookingClass&)
: _key (DEFAULT_CLASS_CODE), _parent (NULL) {
assert (false);
}
// ////////////////////////////////////////////////////////////////////
BookingClass::BookingClass (const Key_T& iKey)
: _key (iKey), _parent (NULL), _subclassCode(0), _cumulatedProtection (0.0),
_protection (0.0), _cumulatedBookingLimit (0.0), _au (0.0), _nego (0.0),
_noShowPercentage (0.0), _cancellationPercentage (0.0),
_nbOfBookings (0.0), _groupNbOfBookings (0.0),
_groupPendingNbOfBookings (0.0), _staffNbOfBookings (0.0),
_wlNbOfBookings (0.0), _nbOfCancellations (0.), _etb (0.0),
_netClassAvailability (0.0), _segmentAvailability (0.0),
_netRevenueAvailability (0.0), _yield (0.0), _mean (0.0), _stdDev (0.0) {
}
// ////////////////////////////////////////////////////////////////////
BookingClass::~BookingClass() {
}
// ////////////////////////////////////////////////////////////////////
std::string BookingClass::toString() const {
std::ostringstream oStr;
oStr << describeKey();
return oStr.str();
}
// ////////////////////////////////////////////////////////////////////
void BookingClass::sell (const NbOfBookings_T& iNbOfBookings) {
_nbOfBookings += iNbOfBookings;
}
// ////////////////////////////////////////////////////////////////////
void BookingClass::cancel (const NbOfBookings_T& iNbOfCancellations) {
_nbOfBookings -= iNbOfCancellations;
_nbOfCancellations += iNbOfCancellations;
}
// ////////////////////////////////////////////////////////////////////
void BookingClass::generateDemandSamples (const int& K) {
_generatedDemandVector.clear();
if (_stdDev > 0) {
RandomGeneration lGenerator (DEFAULT_RANDOM_SEED);
for (int i = 0; i < K; ++i) {
RealNumber_T lDemandSample = lGenerator.generateNormal (_mean, _stdDev);
_generatedDemandVector.push_back (lDemandSample);
}
}
}
// ////////////////////////////////////////////////////////////////////
void BookingClass::generateDemandSamples (const int& K,
const RandomSeed_T& iSeed) {
_generatedDemandVector.clear();
if (_stdDev > 0) {
RandomGeneration lGenerator (iSeed);
for (int i = 0; i < K; ++i) {
RealNumber_T lDemandSample = lGenerator.generateNormal (_mean, _stdDev);
_generatedDemandVector.push_back (lDemandSample);
}
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "types.hh"
#include <iostream>
#include <algorithm>
#include <vector>
#include <boost/range/iterator_range.hpp>
#include "utils/serialization.hh"
#include "unimplemented.hh"
// value_traits is meant to abstract away whether we are working on 'bytes'
// elements or 'bytes_opt' elements. We don't support optional values, but
// there are some generic layers which use this code which provide us with
// data in that format. In order to avoid allocation and rewriting that data
// into a new vector just to throw it away soon after that, we accept that
// format too.
template <typename T>
struct value_traits {
static const T& unwrap(const T& t) { return t; }
};
template<>
struct value_traits<bytes_opt> {
static const bytes& unwrap(const bytes_opt& t) {
assert(t);
return *t;
}
};
enum class allow_prefixes { no, yes };
template<allow_prefixes AllowPrefixes = allow_prefixes::no>
class compound_type final {
private:
const std::vector<data_type> _types;
const bool _byte_order_equal;
const bool _byte_order_comparable;
const bool _is_reversed;
public:
static constexpr bool is_prefixable = AllowPrefixes == allow_prefixes::yes;
using prefix_type = compound_type<allow_prefixes::yes>;
using value_type = std::vector<bytes>;
compound_type(std::vector<data_type> types)
: _types(std::move(types))
, _byte_order_equal(std::all_of(_types.begin(), _types.end(), [] (auto t) {
return t->is_byte_order_equal();
}))
, _byte_order_comparable(_types.size() == 1 && _types[0]->is_byte_order_comparable())
, _is_reversed(_types.size() == 1 && _types[0]->is_reversed())
{ }
compound_type(compound_type&&) = default;
auto const& types() const {
return _types;
}
bool is_singular() const {
return _types.size() == 1;
}
prefix_type as_prefix() {
return prefix_type(_types);
}
/*
* Format:
* <len(value1)><value1><len(value2)><value2>...<len(value_n-1)><value_n-1>(len(value_n))?<value_n>
*
* For non-prefixable compounds, the value corresponding to the last component of types doesn't
* have its length encoded, its length is deduced from the input range.
*
* serialize_value() and serialize_optionals() for single element rely on the fact that for a single-element
* compounds their serialized form is equal to the serialized form of the component.
*/
template<typename Wrapped>
void serialize_value(const std::vector<Wrapped>& values, bytes::iterator& out) {
if (AllowPrefixes == allow_prefixes::yes) {
assert(values.size() <= _types.size());
} else {
assert(values.size() == _types.size());
}
size_t n_left = _types.size();
for (auto&& wrapped : values) {
auto&& val = value_traits<Wrapped>::unwrap(wrapped);
assert(val.size() <= std::numeric_limits<uint16_t>::max());
if (--n_left || AllowPrefixes == allow_prefixes::yes) {
write<uint16_t>(out, uint16_t(val.size()));
}
out = std::copy(val.begin(), val.end(), out);
}
}
template <typename Wrapped>
size_t serialized_size(const std::vector<Wrapped>& values) {
size_t len = 0;
size_t n_left = _types.size();
for (auto&& wrapped : values) {
auto&& val = value_traits<Wrapped>::unwrap(wrapped);
assert(val.size() <= std::numeric_limits<uint16_t>::max());
if (--n_left || AllowPrefixes == allow_prefixes::yes) {
len += sizeof(uint16_t);
}
len += val.size();
}
return len;
}
bytes serialize_single(bytes&& v) {
if (AllowPrefixes == allow_prefixes::no) {
assert(_types.size() == 1);
return std::move(v);
} else {
// FIXME: Optimize
std::vector<bytes> vec;
vec.reserve(1);
vec.emplace_back(std::move(v));
return ::serialize_value(*this, vec);
}
}
bytes serialize_value(const std::vector<bytes>& values) {
return ::serialize_value(*this, values);
}
bytes serialize_value(std::vector<bytes>&& values) {
if (AllowPrefixes == allow_prefixes::no && _types.size() == 1 && values.size() == 1) {
return std::move(values[0]);
}
return ::serialize_value(*this, values);
}
bytes serialize_optionals(const std::vector<bytes_opt>& values) {
return ::serialize_value(*this, values);
}
bytes serialize_optionals(std::vector<bytes_opt>&& values) {
if (AllowPrefixes == allow_prefixes::no && _types.size() == 1 && values.size() == 1) {
assert(values[0]);
return std::move(*values[0]);
}
return ::serialize_value(*this, values);
}
bytes serialize_value_deep(const std::vector<data_value>& values) {
// TODO: Optimize
std::vector<bytes> partial;
partial.reserve(values.size());
auto i = _types.begin();
for (auto&& component : values) {
assert(i != _types.end());
partial.push_back((*i++)->decompose(component));
}
return serialize_value(partial);
}
bytes decompose_value(const value_type& values) {
return ::serialize_value(*this, values);
}
class iterator : public std::iterator<std::input_iterator_tag, bytes_view> {
private:
ssize_t _types_left;
bytes_view _v;
value_type _current;
private:
void read_current() {
if (_types_left == 0) {
if (!_v.empty()) {
throw marshal_exception();
}
_v = bytes_view(nullptr, 0);
return;
}
--_types_left;
uint16_t len;
if (_types_left == 0 && AllowPrefixes == allow_prefixes::no) {
len = _v.size();
} else {
if (_v.empty()) {
if (AllowPrefixes == allow_prefixes::yes) {
_types_left = 0;
_v = bytes_view(nullptr, 0);
return;
} else {
throw marshal_exception();
}
}
len = read_simple<uint16_t>(_v);
if (_v.size() < len) {
throw marshal_exception();
}
}
_current = bytes_view(_v.begin(), len);
_v.remove_prefix(len);
}
public:
struct end_iterator_tag {};
iterator(const compound_type& t, const bytes_view& v) : _types_left(t._types.size()), _v(v) {
read_current();
}
iterator(end_iterator_tag, const bytes_view& v) : _types_left(0), _v(nullptr, 0) {}
iterator& operator++() {
read_current();
return *this;
}
iterator operator++(int) {
iterator i(*this);
++(*this);
return i;
}
const value_type& operator*() const { return _current; }
const value_type* operator->() const { return &_current; }
bool operator!=(const iterator& i) const { return _v.begin() != i._v.begin() || _types_left != i._types_left; }
bool operator==(const iterator& i) const { return _v.begin() == i._v.begin() && _types_left == i._types_left; }
};
iterator begin(const bytes_view& v) const {
return iterator(*this, v);
}
iterator end(const bytes_view& v) const {
return iterator(typename iterator::end_iterator_tag(), v);
}
boost::iterator_range<iterator> components(const bytes_view& v) const {
return { begin(v), end(v) };
}
auto iter_items(const bytes_view& v) {
return boost::iterator_range<iterator>(begin(v), end(v));
}
value_type deserialize_value(bytes_view v) {
std::vector<bytes> result;
result.reserve(_types.size());
std::transform(begin(v), end(v), std::back_inserter(result), [] (auto&& v) {
return bytes(v.begin(), v.end());
});
return result;
}
bool less(bytes_view b1, bytes_view b2) {
return compare(b1, b2) < 0;
}
size_t hash(bytes_view v) {
if (_byte_order_equal) {
return std::hash<bytes_view>()(v);
}
auto t = _types.begin();
size_t h = 0;
for (auto&& value : iter_items(v)) {
h ^= (*t)->hash(value);
++t;
}
return h;
}
int compare(bytes_view b1, bytes_view b2) {
if (_byte_order_comparable) {
if (_is_reversed) {
return compare_unsigned(b2, b1);
} else {
return compare_unsigned(b1, b2);
}
}
return lexicographical_tri_compare(_types.begin(), _types.end(),
begin(b1), end(b1), begin(b2), end(b2), [] (auto&& type, auto&& v1, auto&& v2) {
return type->compare(v1, v2);
});
}
bytes from_string(sstring_view s) {
throw std::runtime_error("not implemented");
}
sstring to_string(const bytes& b) {
throw std::runtime_error("not implemented");
}
// Retruns true iff given prefix has no missing components
bool is_full(bytes_view v) const {
assert(AllowPrefixes == allow_prefixes::yes);
return std::distance(begin(v), end(v)) == (ssize_t)_types.size();
}
void validate(bytes_view v) {
// FIXME: implement
warn(unimplemented::cause::VALIDATION);
}
bool equal(bytes_view v1, bytes_view v2) {
if (_byte_order_equal) {
return compare_unsigned(v1, v2) == 0;
}
// FIXME: call equal() on each component
return compare(v1, v2) == 0;
}
};
using compound_prefix = compound_type<allow_prefixes::yes>;
<commit_msg>compound: fix compare() of prefixable types<commit_after>/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "types.hh"
#include <iostream>
#include <algorithm>
#include <vector>
#include <boost/range/iterator_range.hpp>
#include "utils/serialization.hh"
#include "unimplemented.hh"
// value_traits is meant to abstract away whether we are working on 'bytes'
// elements or 'bytes_opt' elements. We don't support optional values, but
// there are some generic layers which use this code which provide us with
// data in that format. In order to avoid allocation and rewriting that data
// into a new vector just to throw it away soon after that, we accept that
// format too.
template <typename T>
struct value_traits {
static const T& unwrap(const T& t) { return t; }
};
template<>
struct value_traits<bytes_opt> {
static const bytes& unwrap(const bytes_opt& t) {
assert(t);
return *t;
}
};
enum class allow_prefixes { no, yes };
template<allow_prefixes AllowPrefixes = allow_prefixes::no>
class compound_type final {
private:
const std::vector<data_type> _types;
const bool _byte_order_equal;
const bool _byte_order_comparable;
const bool _is_reversed;
public:
static constexpr bool is_prefixable = AllowPrefixes == allow_prefixes::yes;
using prefix_type = compound_type<allow_prefixes::yes>;
using value_type = std::vector<bytes>;
compound_type(std::vector<data_type> types)
: _types(std::move(types))
, _byte_order_equal(std::all_of(_types.begin(), _types.end(), [] (auto t) {
return t->is_byte_order_equal();
}))
, _byte_order_comparable(!is_prefixable && _types.size() == 1 && _types[0]->is_byte_order_comparable())
, _is_reversed(_types.size() == 1 && _types[0]->is_reversed())
{ }
compound_type(compound_type&&) = default;
auto const& types() const {
return _types;
}
bool is_singular() const {
return _types.size() == 1;
}
prefix_type as_prefix() {
return prefix_type(_types);
}
/*
* Format:
* <len(value1)><value1><len(value2)><value2>...<len(value_n-1)><value_n-1>(len(value_n))?<value_n>
*
* For non-prefixable compounds, the value corresponding to the last component of types doesn't
* have its length encoded, its length is deduced from the input range.
*
* serialize_value() and serialize_optionals() for single element rely on the fact that for a single-element
* compounds their serialized form is equal to the serialized form of the component.
*/
template<typename Wrapped>
void serialize_value(const std::vector<Wrapped>& values, bytes::iterator& out) {
if (AllowPrefixes == allow_prefixes::yes) {
assert(values.size() <= _types.size());
} else {
assert(values.size() == _types.size());
}
size_t n_left = _types.size();
for (auto&& wrapped : values) {
auto&& val = value_traits<Wrapped>::unwrap(wrapped);
assert(val.size() <= std::numeric_limits<uint16_t>::max());
if (--n_left || AllowPrefixes == allow_prefixes::yes) {
write<uint16_t>(out, uint16_t(val.size()));
}
out = std::copy(val.begin(), val.end(), out);
}
}
template <typename Wrapped>
size_t serialized_size(const std::vector<Wrapped>& values) {
size_t len = 0;
size_t n_left = _types.size();
for (auto&& wrapped : values) {
auto&& val = value_traits<Wrapped>::unwrap(wrapped);
assert(val.size() <= std::numeric_limits<uint16_t>::max());
if (--n_left || AllowPrefixes == allow_prefixes::yes) {
len += sizeof(uint16_t);
}
len += val.size();
}
return len;
}
bytes serialize_single(bytes&& v) {
if (AllowPrefixes == allow_prefixes::no) {
assert(_types.size() == 1);
return std::move(v);
} else {
// FIXME: Optimize
std::vector<bytes> vec;
vec.reserve(1);
vec.emplace_back(std::move(v));
return ::serialize_value(*this, vec);
}
}
bytes serialize_value(const std::vector<bytes>& values) {
return ::serialize_value(*this, values);
}
bytes serialize_value(std::vector<bytes>&& values) {
if (AllowPrefixes == allow_prefixes::no && _types.size() == 1 && values.size() == 1) {
return std::move(values[0]);
}
return ::serialize_value(*this, values);
}
bytes serialize_optionals(const std::vector<bytes_opt>& values) {
return ::serialize_value(*this, values);
}
bytes serialize_optionals(std::vector<bytes_opt>&& values) {
if (AllowPrefixes == allow_prefixes::no && _types.size() == 1 && values.size() == 1) {
assert(values[0]);
return std::move(*values[0]);
}
return ::serialize_value(*this, values);
}
bytes serialize_value_deep(const std::vector<data_value>& values) {
// TODO: Optimize
std::vector<bytes> partial;
partial.reserve(values.size());
auto i = _types.begin();
for (auto&& component : values) {
assert(i != _types.end());
partial.push_back((*i++)->decompose(component));
}
return serialize_value(partial);
}
bytes decompose_value(const value_type& values) {
return ::serialize_value(*this, values);
}
class iterator : public std::iterator<std::input_iterator_tag, bytes_view> {
private:
ssize_t _types_left;
bytes_view _v;
value_type _current;
private:
void read_current() {
if (_types_left == 0) {
if (!_v.empty()) {
throw marshal_exception();
}
_v = bytes_view(nullptr, 0);
return;
}
--_types_left;
uint16_t len;
if (_types_left == 0 && AllowPrefixes == allow_prefixes::no) {
len = _v.size();
} else {
if (_v.empty()) {
if (AllowPrefixes == allow_prefixes::yes) {
_types_left = 0;
_v = bytes_view(nullptr, 0);
return;
} else {
throw marshal_exception();
}
}
len = read_simple<uint16_t>(_v);
if (_v.size() < len) {
throw marshal_exception();
}
}
_current = bytes_view(_v.begin(), len);
_v.remove_prefix(len);
}
public:
struct end_iterator_tag {};
iterator(const compound_type& t, const bytes_view& v) : _types_left(t._types.size()), _v(v) {
read_current();
}
iterator(end_iterator_tag, const bytes_view& v) : _types_left(0), _v(nullptr, 0) {}
iterator& operator++() {
read_current();
return *this;
}
iterator operator++(int) {
iterator i(*this);
++(*this);
return i;
}
const value_type& operator*() const { return _current; }
const value_type* operator->() const { return &_current; }
bool operator!=(const iterator& i) const { return _v.begin() != i._v.begin() || _types_left != i._types_left; }
bool operator==(const iterator& i) const { return _v.begin() == i._v.begin() && _types_left == i._types_left; }
};
iterator begin(const bytes_view& v) const {
return iterator(*this, v);
}
iterator end(const bytes_view& v) const {
return iterator(typename iterator::end_iterator_tag(), v);
}
boost::iterator_range<iterator> components(const bytes_view& v) const {
return { begin(v), end(v) };
}
auto iter_items(const bytes_view& v) {
return boost::iterator_range<iterator>(begin(v), end(v));
}
value_type deserialize_value(bytes_view v) {
std::vector<bytes> result;
result.reserve(_types.size());
std::transform(begin(v), end(v), std::back_inserter(result), [] (auto&& v) {
return bytes(v.begin(), v.end());
});
return result;
}
bool less(bytes_view b1, bytes_view b2) {
return compare(b1, b2) < 0;
}
size_t hash(bytes_view v) {
if (_byte_order_equal) {
return std::hash<bytes_view>()(v);
}
auto t = _types.begin();
size_t h = 0;
for (auto&& value : iter_items(v)) {
h ^= (*t)->hash(value);
++t;
}
return h;
}
int compare(bytes_view b1, bytes_view b2) {
if (_byte_order_comparable) {
if (_is_reversed) {
return compare_unsigned(b2, b1);
} else {
return compare_unsigned(b1, b2);
}
}
return lexicographical_tri_compare(_types.begin(), _types.end(),
begin(b1), end(b1), begin(b2), end(b2), [] (auto&& type, auto&& v1, auto&& v2) {
return type->compare(v1, v2);
});
}
bytes from_string(sstring_view s) {
throw std::runtime_error("not implemented");
}
sstring to_string(const bytes& b) {
throw std::runtime_error("not implemented");
}
// Retruns true iff given prefix has no missing components
bool is_full(bytes_view v) const {
assert(AllowPrefixes == allow_prefixes::yes);
return std::distance(begin(v), end(v)) == (ssize_t)_types.size();
}
void validate(bytes_view v) {
// FIXME: implement
warn(unimplemented::cause::VALIDATION);
}
bool equal(bytes_view v1, bytes_view v2) {
if (_byte_order_equal) {
return compare_unsigned(v1, v2) == 0;
}
// FIXME: call equal() on each component
return compare(v1, v2) == 0;
}
};
using compound_prefix = compound_type<allow_prefixes::yes>;
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "util/coding.h"
namespace leveldb {
// TED::如果系统本身就是little endian,直接用memcpy.
// TED:: memcpy本身实现依赖于系统字节序??
// TED::否则手动little endian 赋值
// TED:: why not use loop??
void EncodeFixed32(char* buf, uint32_t value) {
if (port::kLittleEndian) {
memcpy(buf, &value, sizeof(value));
} else {
buf[0] = value & 0xff;
buf[1] = (value >> 8) & 0xff;
buf[2] = (value >> 16) & 0xff;
buf[3] = (value >> 24) & 0xff;
}
}
void EncodeFixed64(char* buf, uint64_t value) {
if (port::kLittleEndian) {
memcpy(buf, &value, sizeof(value));
} else {
buf[0] = value & 0xff;
buf[1] = (value >> 8) & 0xff;
buf[2] = (value >> 16) & 0xff;
buf[3] = (value >> 24) & 0xff;
buf[4] = (value >> 32) & 0xff;
buf[5] = (value >> 40) & 0xff;
buf[6] = (value >> 48) & 0xff;
buf[7] = (value >> 56) & 0xff;
}
}
void PutFixed32(std::string* dst, uint32_t value) {
char buf[sizeof(value)];
EncodeFixed32(buf, value);
dst->append(buf, sizeof(buf));
}
void PutFixed64(std::string* dst, uint64_t value) {
char buf[sizeof(value)];
EncodeFixed64(buf, value);
dst->append(buf, sizeof(buf));
}
// TED:: 将输入整形数据,按7位进行分割。7位一组。除了最后一组,前面的组最高位都设置为1.
// TED:: why not use loop to split?? performance??
char* EncodeVarint32(char* dst, uint32_t v) {
// Operate on characters as unsigneds
unsigned char* ptr = reinterpret_cast<unsigned char*>(dst);
static const int B = 128;
if (v < (1<<7)) {
*(ptr++) = v;
} else if (v < (1<<14)) {
*(ptr++) = v | B;
*(ptr++) = v>>7;
} else if (v < (1<<21)) {
*(ptr++) = v | B;
*(ptr++) = (v>>7) | B;
*(ptr++) = v>>14;
} else if (v < (1<<28)) {
*(ptr++) = v | B;
*(ptr++) = (v>>7) | B;
*(ptr++) = (v>>14) | B;
*(ptr++) = v>>21;
} else {
*(ptr++) = v | B;
*(ptr++) = (v>>7) | B;
*(ptr++) = (v>>14) | B;
*(ptr++) = (v>>21) | B;
*(ptr++) = v>>28;
}
return reinterpret_cast<char*>(ptr);
}
void PutVarint32(std::string* dst, uint32_t v) {
// TED:: 32bit/7bit ~= 4.57
char buf[5];
char* ptr = EncodeVarint32(buf, v);
dst->append(buf, ptr - buf);
}
// TED:: 同EncodeVarint32,但是使用了循环,简洁。
// TED:: 注意reinterpret_cast和static_cast的使用
char* EncodeVarint64(char* dst, uint64_t v) {
static const int B = 128;
unsigned char* ptr = reinterpret_cast<unsigned char*>(dst);
// TED:: 只要>=1000_0000(2^7=128)说明超过7位,可继续拆分。
while (v >= B) {
*(ptr++) = (v & (B-1)) | B;
v >>= 7;
}
// TED:: 不要忘了还剩下一个7位
*(ptr++) = static_cast<unsigned char>(v);
return reinterpret_cast<char*>(ptr);
}
void PutVarint64(std::string* dst, uint64_t v) {
// TED:: 64bit/7bit ~= 9.14
char buf[10];
char* ptr = EncodeVarint64(buf, v);
dst->append(buf, ptr - buf);
}
// TED:: |--length (varint32 type)--|---actual value(string)|
void PutLengthPrefixedSlice(std::string* dst, const Slice& value) {
PutVarint32(dst, value.size());
dst->append(value.data(), value.size());
}
// TED:: 查看可以拆分成多少个7bit segment.
int VarintLength(uint64_t v) {
int len = 1;
while (v >= 128) {
v >>= 7;
len++;
}
return len;
}
const char* GetVarint32PtrFallback(const char* p,
const char* limit,
uint32_t* value) {
uint32_t result = 0;
for (uint32_t shift = 0; shift <= 28 && p < limit; shift += 7) {
uint32_t byte = *(reinterpret_cast<const unsigned char*>(p));
p++;
if (byte & 128) {
// More bytes are present
result |= ((byte & 127) << shift);
} else {
result |= (byte << shift);
*value = result;
return reinterpret_cast<const char*>(p);
}
}
return NULL;
}
bool GetVarint32(Slice* input, uint32_t* value) {
const char* p = input->data();
const char* limit = p + input->size();
const char* q = GetVarint32Ptr(p, limit, value);
if (q == NULL) {
return false;
} else {
*input = Slice(q, limit - q);
return true;
}
}
const char* GetVarint64Ptr(const char* p, const char* limit, uint64_t* value) {
uint64_t result = 0;
for (uint32_t shift = 0; shift <= 63 && p < limit; shift += 7) {
uint64_t byte = *(reinterpret_cast<const unsigned char*>(p));
p++;
if (byte & 128) {
// More bytes are present
result |= ((byte & 127) << shift);
} else {
result |= (byte << shift);
*value = result;
return reinterpret_cast<const char*>(p);
}
}
return NULL;
}
bool GetVarint64(Slice* input, uint64_t* value) {
const char* p = input->data();
const char* limit = p + input->size();
const char* q = GetVarint64Ptr(p, limit, value);
if (q == NULL) {
return false;
} else {
*input = Slice(q, limit - q);
return true;
}
}
const char* GetLengthPrefixedSlice(const char* p, const char* limit,
Slice* result) {
uint32_t len;
p = GetVarint32Ptr(p, limit, &len);
if (p == NULL) return NULL;
if (p + len > limit) return NULL;
*result = Slice(p, len);
return p + len;
}
bool GetLengthPrefixedSlice(Slice* input, Slice* result) {
uint32_t len;
if (GetVarint32(input, &len) &&
input->size() >= len) {
*result = Slice(input->data(), len);
input->remove_prefix(len);
return true;
} else {
return false;
}
}
} // namespace leveldb
<commit_msg>update coding.cc<commit_after>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "util/coding.h"
namespace leveldb {
// TED::如果系统本身就是little endian,直接用memcpy.
// TED:: memcpy本身实现依赖于系统字节序??
// TED::否则手动little endian 赋值
// TED:: why not use loop??
void EncodeFixed32(char* buf, uint32_t value) {
if (port::kLittleEndian) {
memcpy(buf, &value, sizeof(value));
} else {
buf[0] = value & 0xff;
buf[1] = (value >> 8) & 0xff;
buf[2] = (value >> 16) & 0xff;
buf[3] = (value >> 24) & 0xff;
}
}
void EncodeFixed64(char* buf, uint64_t value) {
if (port::kLittleEndian) {
memcpy(buf, &value, sizeof(value));
} else {
buf[0] = value & 0xff;
buf[1] = (value >> 8) & 0xff;
buf[2] = (value >> 16) & 0xff;
buf[3] = (value >> 24) & 0xff;
buf[4] = (value >> 32) & 0xff;
buf[5] = (value >> 40) & 0xff;
buf[6] = (value >> 48) & 0xff;
buf[7] = (value >> 56) & 0xff;
}
}
void PutFixed32(std::string* dst, uint32_t value) {
char buf[sizeof(value)];
EncodeFixed32(buf, value);
dst->append(buf, sizeof(buf));
}
void PutFixed64(std::string* dst, uint64_t value) {
char buf[sizeof(value)];
EncodeFixed64(buf, value);
dst->append(buf, sizeof(buf));
}
// TED:: 将输入整形数据,按7位进行分割。7位一组。除了最后一组,前面的组最高位都设置为1.
// TED:: why not use loop to split?? performance??
char* EncodeVarint32(char* dst, uint32_t v) {
// Operate on characters as unsigneds
unsigned char* ptr = reinterpret_cast<unsigned char*>(dst);
static const int B = 128;
if (v < (1<<7)) {
*(ptr++) = v;
} else if (v < (1<<14)) {
*(ptr++) = v | B;
*(ptr++) = v>>7;
} else if (v < (1<<21)) {
*(ptr++) = v | B;
*(ptr++) = (v>>7) | B;
*(ptr++) = v>>14;
} else if (v < (1<<28)) {
*(ptr++) = v | B;
*(ptr++) = (v>>7) | B;
*(ptr++) = (v>>14) | B;
*(ptr++) = v>>21;
} else {
*(ptr++) = v | B;
*(ptr++) = (v>>7) | B;
*(ptr++) = (v>>14) | B;
*(ptr++) = (v>>21) | B;
*(ptr++) = v>>28;
}
return reinterpret_cast<char*>(ptr);
}
void PutVarint32(std::string* dst, uint32_t v) {
// TED:: 32bit/7bit ~= 4.57
char buf[5];
char* ptr = EncodeVarint32(buf, v);
dst->append(buf, ptr - buf);
}
// TED:: 同EncodeVarint32,但是使用了循环,简洁。
// TED:: 注意reinterpret_cast和static_cast的使用
char* EncodeVarint64(char* dst, uint64_t v) {
static const int B = 128;
unsigned char* ptr = reinterpret_cast<unsigned char*>(dst);
// TED:: 只要>=1000_0000(2^7=128)说明超过7位,可继续拆分。
while (v >= B) {
*(ptr++) = (v & (B-1)) | B;
v >>= 7;
}
// TED:: 不要忘了还剩下一个7位
*(ptr++) = static_cast<unsigned char>(v);
return reinterpret_cast<char*>(ptr);
}
void PutVarint64(std::string* dst, uint64_t v) {
// TED:: 64bit/7bit ~= 9.14
char buf[10];
char* ptr = EncodeVarint64(buf, v);
dst->append(buf, ptr - buf);
}
// TED:: |--length (varint32 type)--|---actual value(string)|
void PutLengthPrefixedSlice(std::string* dst, const Slice& value) {
PutVarint32(dst, value.size());
dst->append(value.data(), value.size());
}
// TED:: 查看可以拆分成多少个7bit segment.
int VarintLength(uint64_t v) {
int len = 1;
while (v >= 128) {
v >>= 7;
len++;
}
return len;
}
const char* GetVarint32PtrFallback(const char* p,
const char* limit,
uint32_t* value) {
uint32_t result = 0;
// TED:: 仅需注意是little endian字节序
// TED:: 32bit/7bit ~= 4.57, 即编码字符串中存在5段分割
// TED:: 7 * (5 - 1) = 28 因为从0计数,且全闭合。
for (uint32_t shift = 0; shift <= 28 && p < limit; shift += 7) {
uint32_t byte = *(reinterpret_cast<const unsigned char*>(p));
p++;
// TED:: 看最高位是否为1
if (byte & 128) {
// More bytes are present
result |= ((byte & 127) << shift);
} else {
result |= (byte << shift);
*value = result;
return reinterpret_cast<const char*>(p);
}
}
return NULL;
}
bool GetVarint32(Slice* input, uint32_t* value) {
const char* p = input->data();
const char* limit = p + input->size();
const char* q = GetVarint32Ptr(p, limit, value);
if (q == NULL) {
return false;
} else {
// TED:: 此处即为coding.h中原注释写的advance the slice past the parsed value
*input = Slice(q, limit - q);
return true;
}
}
// TED:: 为何GetVarint64Ptr不能像GetVarint32Ptr一样设为inline
const char* GetVarint64Ptr(const char* p, const char* limit, uint64_t* value) {
uint64_t result = 0;
// TED:: 64bit/7bit ~= 9.14, 即编码字符串中存在10段分割
// TED:: 7 * (10 - 1) = 63 因为从0计数,且全闭合。
for (uint32_t shift = 0; shift <= 63 && p < limit; shift += 7) {
uint64_t byte = *(reinterpret_cast<const unsigned char*>(p));
p++;
if (byte & 128) {
// More bytes are present
result |= ((byte & 127) << shift);
} else {
result |= (byte << shift);
*value = result;
return reinterpret_cast<const char*>(p);
}
}
return NULL;
}
bool GetVarint64(Slice* input, uint64_t* value) {
const char* p = input->data();
const char* limit = p + input->size();
const char* q = GetVarint64Ptr(p, limit, value);
if (q == NULL) {
return false;
} else {
*input = Slice(q, limit - q);
return true;
}
}
// TED:: Get_LengthPrefixed_Slice
const char* GetLengthPrefixedSlice(const char* p, const char* limit,
Slice* result) {
uint32_t len;
p = GetVarint32Ptr(p, limit, &len);
if (p == NULL) return NULL;
if (p + len > limit) return NULL;
*result = Slice(p, len);
return p + len;
}
bool GetLengthPrefixedSlice(Slice* input, Slice* result) {
uint32_t len;
if (GetVarint32(input, &len) &&
input->size() >= len) {
*result = Slice(input->data(), len);
input->remove_prefix(len);
return true;
} else {
return false;
}
}
} // namespace leveldb
<|endoftext|> |
<commit_before>// (C) 2014 Arek Olek
#pragma once
#include <algorithm>
#include <functional>
#include <vector>
#include <boost/iterator/counting_iterator.hpp>
#include "range.hpp"
auto range_iterator = boost::make_counting_iterator<int>;
template <class Input, class Output>
void copy_edges(const Input& in, Output& out) {
for(auto e : range(edges(in)))
add_edge(source(e, in), target(e, in), out);
}
template<class Graph, class Generator>
void add_spider(Graph& G, unsigned legs, Generator generator) {
unsigned n = num_vertices(G);
unsigned cutoff = n / legs;
std::vector<int> path(range_iterator(0), range_iterator(n));
std::shuffle(path.begin(), path.end(), generator);
for(unsigned i = 0; i < n-1; ++i)
add_edge(path[i % cutoff == 0 ? 0 : i], path[i+1], G);
}
template<class Graph, class Generator>
void add_edges_uniform(Graph& G, double p, Generator generator) {
std::bernoulli_distribution distribution(p);
auto trial = std::bind(distribution, generator);
unsigned n = num_vertices(G);
for(unsigned i = 0; i < n; ++i)
for(unsigned j = i + 1; j < n; ++j)
if(trial())
add_edge(i, j, G);
}
<commit_msg>refactor move code to function<commit_after>// (C) 2014 Arek Olek
#pragma once
#include <algorithm>
#include <functional>
#include <vector>
#include <boost/iterator/counting_iterator.hpp>
#include "range.hpp"
template <class Input, class Output>
void copy_edges(const Input& in, Output& out) {
for(auto e : range(edges(in)))
add_edge(source(e, in), target(e, in), out);
}
template<class Graph, class Generator>
void add_spider(Graph& G, unsigned legs, Generator generator) {
unsigned n = num_vertices(G);
unsigned cutoff = n / legs;
auto range_iterator = boost::make_counting_iterator<int>;
std::vector<int> path(range_iterator(0), range_iterator(n));
std::shuffle(path.begin(), path.end(), generator);
for(unsigned i = 0; i < n-1; ++i)
add_edge(path[i % cutoff == 0 ? 0 : i], path[i+1], G);
}
template<class Graph, class Generator>
void add_edges_uniform(Graph& G, double p, Generator generator) {
std::bernoulli_distribution distribution(p);
auto trial = std::bind(distribution, generator);
unsigned n = num_vertices(G);
for(unsigned i = 0; i < n; ++i)
for(unsigned j = i + 1; j < n; ++j)
if(trial())
add_edge(i, j, G);
}
<|endoftext|> |
<commit_before>Int_t loadlibs ()
{
// Macro which loads the libraries needed for simulation and reconstruction
// Possible usage: In a Root session (no AliRoot) one does
// root [0] .x loadlibs.C
// root [1] gAlice = new AliRun("gAlice","test")
// root [2] AliSimulation sim
// root [3] sim.Run()
// root [4] AliReconstruction rec
// root [5] rec.Run()
Int_t ret=-1;
if ( gSystem->Load("libPhysics") < 0 ) return ret; ret--;
if ( gSystem->Load("libMinuit") < 0 ) return ret; ret--;
if ( gSystem->Load("libProof") < 0 ) return ret; ret--;
if ( gSystem->Load("libmicrocern") < 0 ) return ret; ret--;
if ( gSystem->Load("liblhapdf") < 0 ) return ret; ret--;
if ( gSystem->Load("libpythia6") < 0 ) return ret; ret--;
if ( gSystem->Load("libEG") < 0 ) return ret; ret--;
if ( gSystem->Load("libGeom") < 0 ) return ret; ret--;
if ( gSystem->Load("libVMC") < 0 ) return ret; ret--;
if ( gSystem->Load("libEGPythia6") < 0 ) return ret; ret--;
if ( gSystem->Load("libSTEERBase") < 0 ) return ret; ret--;
if ( gSystem->Load("libESD") < 0 ) return ret; ret--;
if ( gSystem->Load("libCDB") < 0 ) return ret; ret--;
if ( gSystem->Load("libRAWDatabase") < 0 ) return ret; ret--;
if ( gSystem->Load("libRAWDatarec") < 0 ) return ret; ret--;
if ( gSystem->Load("libAOD") < 0 ) return ret; ret--;
if ( gSystem->Load("libANALYSIS") < 0 ) return ret; ret--;
if ( gSystem->Load("libSTEER") < 0 ) return ret; ret--;
if ( gSystem->Load("libRAWDatasim") < 0 ) return ret; ret--;
if ( gSystem->Load("libFASTSIM") < 0 ) return ret; ret--;
if ( gSystem->Load("libEVGEN") < 0 ) return ret; ret--;
if ( gSystem->Load("libAliPythia6") < 0 ) return ret; ret--;
if ( gSystem->Load("libSTAT") < 0 ) return ret; ret--;
if ( gSystem->Load("libhijing") < 0 ) return ret; ret--;
if ( gSystem->Load("libTHijing") < 0 ) return ret; ret--;// AliGenHijingEventHeader needed by libZDCsim.so
if ( gSystem->Load("libSTRUCT") < 0 ) return ret; ret--;
if ( gSystem->Load("libPHOSUtils") < 0 ) return ret; ret--;
if ( gSystem->Load("libPHOSbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libPHOSsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libPHOSrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONcore") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONmapping") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONgeometry") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONcalib") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONraw") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONtrigger") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONevaluation") < 0 ) return ret; ret--;
if ( gSystem->Load("libFMDbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libFMDsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libFMDrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libPMDbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libPMDsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libPMDrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libHMPIDbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libHMPIDsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libHMPIDrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libT0base") < 0 ) return ret; ret--;
if ( gSystem->Load("libT0sim") < 0 ) return ret; ret--;
if ( gSystem->Load("libT0rec") < 0 ) return ret; ret--;
if ( gSystem->Load("libZDCbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libZDCsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libZDCrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libACORDEbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libACORDErec") < 0 ) return ret; ret--;
if ( gSystem->Load("libACORDEsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libVZERObase") < 0 ) return ret; ret--;
if ( gSystem->Load("libVZEROrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libVZEROsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libEMCALraw") < 0 ) return ret; ret--;
if ( gSystem->Load("libEMCALUtils") < 0 ) return ret; ret--;
if ( gSystem->Load("libEMCALbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libEMCALsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libEMCALrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libTPCbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libTPCrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libTPCsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libITSbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libITSsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libITSrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libTRDbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libTRDsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libTRDrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libTOFbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libTOFsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libTOFrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libHLTbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libHLTinterface") < 0 ) return ret; ret--;
if ( gSystem->Load("libHLTsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libHLTrec") < 0 ) return ret; ret--;
#ifdef MFT_UPGRADE
if ( gSystem->Load("libMFTbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libMFTrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libMFTsim") < 0 ) return ret; ret--;
#endif
return 0;
}
<commit_msg>Adding libGui needed by libCDB<commit_after>Int_t loadlibs ()
{
// Macro which loads the libraries needed for simulation and reconstruction
// Possible usage: In a Root session (no AliRoot) one does
// root [0] .x loadlibs.C
// root [1] gAlice = new AliRun("gAlice","test")
// root [2] AliSimulation sim
// root [3] sim.Run()
// root [4] AliReconstruction rec
// root [5] rec.Run()
Int_t ret=-1;
if ( gSystem->Load("libPhysics") < 0 ) return ret; ret--;
if ( gSystem->Load("libMinuit") < 0 ) return ret; ret--;
if ( gSystem->Load("libProof") < 0 ) return ret; ret--;
if ( gSystem->Load("libmicrocern") < 0 ) return ret; ret--;
if ( gSystem->Load("liblhapdf") < 0 ) return ret; ret--;
if ( gSystem->Load("libpythia6") < 0 ) return ret; ret--;
if ( gSystem->Load("libEG") < 0 ) return ret; ret--;
if ( gSystem->Load("libGeom") < 0 ) return ret; ret--;
if ( gSystem->Load("libVMC") < 0 ) return ret; ret--;
if ( gSystem->Load("libEGPythia6") < 0 ) return ret; ret--;
if ( gSystem->Load("libSTEERBase") < 0 ) return ret; ret--;
if ( gSystem->Load("libESD") < 0 ) return ret; ret--;
if ( gSystem->Load("libGui") < 0 ) return ret; ret--;
if ( gSystem->Load("libCDB") < 0 ) return ret; ret--;
if ( gSystem->Load("libRAWDatabase") < 0 ) return ret; ret--;
if ( gSystem->Load("libRAWDatarec") < 0 ) return ret; ret--;
if ( gSystem->Load("libAOD") < 0 ) return ret; ret--;
if ( gSystem->Load("libANALYSIS") < 0 ) return ret; ret--;
if ( gSystem->Load("libSTEER") < 0 ) return ret; ret--;
if ( gSystem->Load("libRAWDatasim") < 0 ) return ret; ret--;
if ( gSystem->Load("libFASTSIM") < 0 ) return ret; ret--;
if ( gSystem->Load("libEVGEN") < 0 ) return ret; ret--;
if ( gSystem->Load("libAliPythia6") < 0 ) return ret; ret--;
if ( gSystem->Load("libSTAT") < 0 ) return ret; ret--;
if ( gSystem->Load("libhijing") < 0 ) return ret; ret--;
if ( gSystem->Load("libTHijing") < 0 ) return ret; ret--;// AliGenHijingEventHeader needed by libZDCsim.so
if ( gSystem->Load("libSTRUCT") < 0 ) return ret; ret--;
if ( gSystem->Load("libPHOSUtils") < 0 ) return ret; ret--;
if ( gSystem->Load("libPHOSbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libPHOSsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libPHOSrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONcore") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONmapping") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONgeometry") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONcalib") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONraw") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONtrigger") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libMUONevaluation") < 0 ) return ret; ret--;
if ( gSystem->Load("libFMDbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libFMDsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libFMDrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libPMDbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libPMDsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libPMDrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libHMPIDbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libHMPIDsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libHMPIDrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libT0base") < 0 ) return ret; ret--;
if ( gSystem->Load("libT0sim") < 0 ) return ret; ret--;
if ( gSystem->Load("libT0rec") < 0 ) return ret; ret--;
if ( gSystem->Load("libZDCbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libZDCsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libZDCrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libACORDEbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libACORDErec") < 0 ) return ret; ret--;
if ( gSystem->Load("libACORDEsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libVZERObase") < 0 ) return ret; ret--;
if ( gSystem->Load("libVZEROrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libVZEROsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libEMCALraw") < 0 ) return ret; ret--;
if ( gSystem->Load("libEMCALUtils") < 0 ) return ret; ret--;
if ( gSystem->Load("libEMCALbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libEMCALsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libEMCALrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libTPCbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libTPCrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libTPCsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libITSbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libITSsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libITSrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libTRDbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libTRDsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libTRDrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libTOFbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libTOFsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libTOFrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libHLTbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libHLTinterface") < 0 ) return ret; ret--;
if ( gSystem->Load("libHLTsim") < 0 ) return ret; ret--;
if ( gSystem->Load("libHLTrec") < 0 ) return ret; ret--;
#ifdef MFT_UPGRADE
if ( gSystem->Load("libMFTbase") < 0 ) return ret; ret--;
if ( gSystem->Load("libMFTrec") < 0 ) return ret; ret--;
if ( gSystem->Load("libMFTsim") < 0 ) return ret; ret--;
#endif
return 0;
}
<|endoftext|> |
<commit_before>void loadlibs ()
{
gSystem->Load("libPhysics");
gSystem->Load("libMinuit");
// Uncomment the following line for macosx
// Waiting for a better solution
// gSystem->Load("libg2c_sh");
gSystem->Load("libmicrocern");
gSystem->Load("libpdf");
gSystem->Load("libpythia6");
gSystem->Load("libEG");
gSystem->Load("libGeom");
gSystem->Load("libVMC");
gSystem->Load("libEGPythia6");
gSystem->Load("libRAW");
gSystem->Load("libSTEER");
gSystem->Load("libEVGEN");
gSystem->Load("libFASTSIM");
gSystem->Load("libAliPythia6");
gSystem->Load("libSTRUCT");
gSystem->Load("libPHOS");
gSystem->Load("libMUON");
gSystem->Load("libFMDbase");
gSystem->Load("libFMDsim");
gSystem->Load("libFMDrec");
gSystem->Load("libPMD");
gSystem->Load("libRICH");
gSystem->Load("libSTARTbase");
gSystem->Load("libSTARTsim");
gSystem->Load("libSTARTrec");
gSystem->Load("libZDC");
gSystem->Load("libCRT");
gSystem->Load("libVZERObase");
gSystem->Load("libVZEROsim");
gSystem->Load("libVZEROrec");
gSystem->Load("libEMCAL");
gSystem->Load("libCONTAINERS");
// The following lines have to be commented on Darwin
// for the moment due to cross dependencies
gSystem->Load("libTPCbase");
gSystem->Load("libTPCrec");
gSystem->Load("libTPCsim");
gSystem->Load("libTPCfast");
gSystem->Load("libITS");
gSystem->Load("libTRDbase");
gSystem->Load("libTRDsim");
gSystem->Load("libTRDrec");
gSystem->Load("libTRDfast");
gSystem->Load("libTOF");
}
<commit_msg>Corrected list of libraries<commit_after>void loadlibs ()
{
gSystem->Load("libPhysics");
gSystem->Load("libMinuit");
// Uncomment the following line for macosx
// Waiting for a better solution
// gSystem->Load("libg2c_sh");
gSystem->Load("libmicrocern");
gSystem->Load("libpdf");
gSystem->Load("libpythia6");
gSystem->Load("libEG");
gSystem->Load("libGeom");
gSystem->Load("libVMC");
gSystem->Load("libEGPythia6");
gSystem->Load("libRAW");
gSystem->Load("libSTEER");
gSystem->Load("libEVGEN");
gSystem->Load("libFASTSIM");
gSystem->Load("libAliPythia6");
gSystem->Load("libSTRUCT");
gSystem->Load("libPHOS");
gSystem->Load("libMUON");
gSystem->Load("libFMDbase");
gSystem->Load("libFMDsim");
gSystem->Load("libFMDrec");
gSystem->Load("libPMDbase");
gSystem->Load("libPMDsim");
gSystem->Load("libPMDrec");
gSystem->Load("libRICH");
gSystem->Load("libSTARTbase");
gSystem->Load("libSTARTsim");
gSystem->Load("libSTARTrec");
gSystem->Load("libZDC");
gSystem->Load("libCRT");
gSystem->Load("libVZERObase");
gSystem->Load("libVZEROsim");
gSystem->Load("libVZEROrec");
gSystem->Load("libEMCAL");
gSystem->Load("libCONTAINERS");
// The following lines have to be commented on Darwin
// for the moment due to cross dependencies
gSystem->Load("libTPCbase");
gSystem->Load("libTPCrec");
gSystem->Load("libTPCsim");
gSystem->Load("libTPCfast");
gSystem->Load("libITS");
gSystem->Load("libTRDbase");
gSystem->Load("libTRDsim");
gSystem->Load("libTRDrec");
gSystem->Load("libTRDfast");
gSystem->Load("libTOF");
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hlmarkwn.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 23:24:29 $
*
* 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 _SVX_BKWND_HYPERLINK_HXX
#define _SVX_BKWND_HYPERLINK_HXX
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _SV_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _SVTREEBOX_HXX
#include <svtools/svtreebx.hxx>
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif
#include "hlmarkwn_def.hxx" //ADD CHINA001
class SvxHyperlinkTabPageBase;
//CHINA001 #define LERR_NOERROR 0
//CHINA001 #define LERR_NOENTRIES 1
//CHINA001 #define LERR_DOCNOTOPEN 2
//########################################################################
//# #
//# Tree-Window #
//# #
//########################################################################
class SvxHlinkDlgMarkWnd;
class SvxHlmarkTreeLBox : public SvTreeListBox
{
private:
SvxHlinkDlgMarkWnd* mpParentWnd;
public:
SvxHlmarkTreeLBox( Window* pParent, const ResId& rResId );
virtual void Paint( const Rectangle& rRect );
};
//########################################################################
//# #
//# Window-Class #
//# #
//########################################################################
class SvxHlinkDlgMarkWnd : public ModalDialog //FloatingWindow
{
private:
friend class SvxHlmarkTreeLBox;
PushButton maBtApply;
PushButton maBtClose;
//SvTreeListBox maLbTree;
SvxHlmarkTreeLBox maLbTree;
BOOL mbUserMoved;
BOOL mbFirst;
SvxHyperlinkTabPageBase* mpParent;
String maStrLastURL;
USHORT mnError;
protected:
BOOL RefreshFromDoc( ::rtl::OUString aURL );
SvLBoxEntry* FindEntry ( String aStrName );
void ClearTree();
int FillTree( ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > xLinks, SvLBoxEntry* pParentEntry =NULL );
virtual void Move ();
DECL_LINK (ClickApplyHdl_Impl, void * );
DECL_LINK (ClickCloseHdl_Impl, void * );
public:
SvxHlinkDlgMarkWnd (SvxHyperlinkTabPageBase *pParent);
~SvxHlinkDlgMarkWnd();
const BOOL MoveTo ( Point aNewPos );
void RefreshTree ( String aStrURL );
void SelectEntry ( String aStrMark );
const BOOL ConnectToDialog( BOOL bDoit = TRUE );
USHORT SetError( USHORT nError);
};
#endif // _SVX_BKWND_HYPERLINK_HXX
<commit_msg>INTEGRATION: CWS warnings01 (1.5.222); FILE MERGED 2006/04/20 14:49:53 cl 1.5.222.1: warning free code changes<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hlmarkwn.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2006-06-19 16:08:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SVX_BKWND_HYPERLINK_HXX
#define _SVX_BKWND_HYPERLINK_HXX
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _SV_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _SVTREEBOX_HXX
#include <svtools/svtreebx.hxx>
#endif
#include "hlmarkwn_def.hxx" //ADD CHINA001
class SvxHyperlinkTabPageBase;
//########################################################################
//# #
//# Tree-Window #
//# #
//########################################################################
class SvxHlinkDlgMarkWnd;
class SvxHlmarkTreeLBox : public SvTreeListBox
{
private:
SvxHlinkDlgMarkWnd* mpParentWnd;
public:
SvxHlmarkTreeLBox( Window* pParent, const ResId& rResId );
virtual void Paint( const Rectangle& rRect );
};
//########################################################################
//# #
//# Window-Class #
//# #
//########################################################################
class SvxHlinkDlgMarkWnd : public ModalDialog //FloatingWindow
{
private:
friend class SvxHlmarkTreeLBox;
PushButton maBtApply;
PushButton maBtClose;
//SvTreeListBox maLbTree;
SvxHlmarkTreeLBox maLbTree;
BOOL mbUserMoved;
BOOL mbFirst;
SvxHyperlinkTabPageBase* mpParent;
String maStrLastURL;
USHORT mnError;
protected:
BOOL RefreshFromDoc( ::rtl::OUString aURL );
SvLBoxEntry* FindEntry ( String aStrName );
void ClearTree();
int FillTree( ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > xLinks, SvLBoxEntry* pParentEntry =NULL );
virtual void Move ();
DECL_LINK (ClickApplyHdl_Impl, void * );
DECL_LINK (ClickCloseHdl_Impl, void * );
public:
SvxHlinkDlgMarkWnd (SvxHyperlinkTabPageBase *pParent);
~SvxHlinkDlgMarkWnd();
const BOOL MoveTo ( Point aNewPos );
void RefreshTree ( String aStrURL );
void SelectEntry ( String aStrMark );
const BOOL ConnectToDialog( BOOL bDoit = TRUE );
USHORT SetError( USHORT nError);
};
#endif // _SVX_BKWND_HYPERLINK_HXX
<|endoftext|> |
<commit_before>
#include "jnif.h"
static jmethodID m_eobject__testTuple;
static jclass etuple_class;
static jmethodID m_etuple__make;
static jmethodID m_etuple__set;
static jmethodID m_etuple__elm;
static jmethodID m_etuple__arity;
static jmethodID m_object__toString;
extern int enif_is_tuple (ErlNifEnv* ee, ERL_NIF_TERM term)
{
if ( ee->je->CallObjectMethod(E2J(term), m_eobject__testTuple) == NULL) {
return NIF_FALSE;
} else {
return NIF_TRUE;
}
}
extern int enif_get_tuple (ErlNifEnv* ee, ERL_NIF_TERM tpl, int* arity, ERL_NIF_TERM** array)
{
JNIEnv *je = ee->je;
jobject tup = je->CallObjectMethod(E2J(tpl), m_eobject__testTuple);
if (tup == NULL)
return NIF_FALSE;
int count = *arity = je->CallIntMethod(tup, m_etuple__arity);
if (count == 0) { return NIF_TRUE; }
// ok ... check arity
if (array == NULL)
return NIF_TRUE;
*array = (ERL_NIF_TERM*)malloc( sizeof(ERL_NIF_TERM) * count );
for (int i = 0; i < count; i++) {
(*array)[i] = jnif_retain(ee, je->CallObjectMethod( tup, m_etuple__elm, i+1) );
}
// TODO: free *array in environment
return NIF_TRUE;
}
extern ERL_NIF_TERM enif_make_tuple (ErlNifEnv* ee, unsigned cnt, ...)
{
ERL_NIF_TERM args[cnt];
if (cnt > 0) {
va_list vl;
va_start(vl,cnt);
for (int i = 0; i < cnt; i++)
{
args[i] = va_arg(vl,ERL_NIF_TERM);
}
va_end(vl);
}
jobject tup;
tup = ee->je->CallStaticObjectMethod(etuple_class, m_etuple__make, cnt);
for (int i = 0; i < cnt; i++) {
ee->je->CallVoidMethod(tup, m_etuple__set, (jint)(i+1), (jobject)E2J(args[i]));
}
#ifdef DEBUG
jstring str = (jstring) ee->je->CallObjectMethod(tup, m_object__toString);
const char *path = str == NULL ? NULL : ee->je->GetStringUTFChars(str, NULL);
fprintf(stderr, "created: %s\n", path);
ee->je->ReleaseStringUTFChars(str, path);
#endif
return jnif_retain(ee, tup);
}
void initialize_jnif_tuple(JavaVM* vm, JNIEnv *je)
{
jclass eobject_class = je->FindClass("erjang/EObject");
m_eobject__testTuple = je->GetMethodID(eobject_class,
"testTuple",
"()Lerjang/ETuple;");
etuple_class = je->FindClass("erjang/ETuple");
etuple_class = (jclass) je->NewGlobalRef(etuple_class);
m_etuple__make = je->GetStaticMethodID(etuple_class,
"make",
"(I)Lerjang/ETuple;");
m_etuple__set = je->GetMethodID(etuple_class,
"set",
"(ILerjang/EObject;)V");
m_etuple__elm = je->GetMethodID(etuple_class,
"elm",
"(I)Lerjang/EObject;");
m_etuple__arity = je->GetMethodID(etuple_class,
"arity",
"()I");
jclass object_class = je->FindClass("java/lang/String");
m_object__toString = je->GetMethodID(object_class,
"toString",
"()Ljava/lang/String;");
}
<commit_msg>Fix enif_get_tuple declaration<commit_after>
#include "jnif.h"
static jmethodID m_eobject__testTuple;
static jclass etuple_class;
static jmethodID m_etuple__make;
static jmethodID m_etuple__set;
static jmethodID m_etuple__elm;
static jmethodID m_etuple__arity;
static jmethodID m_object__toString;
extern int enif_is_tuple (ErlNifEnv* ee, ERL_NIF_TERM term)
{
if ( ee->je->CallObjectMethod(E2J(term), m_eobject__testTuple) == NULL) {
return NIF_FALSE;
} else {
return NIF_TRUE;
}
}
int enif_get_tuple(ErlNifEnv* ee, ERL_NIF_TERM tpl, int* arity, const ERL_NIF_TERM** a0)
{
JNIEnv *je = ee->je;
jobject tup = je->CallObjectMethod(E2J(tpl), m_eobject__testTuple);
if (tup == NULL)
return NIF_FALSE;
int count = *arity = je->CallIntMethod(tup, m_etuple__arity);
if (count == 0) { return NIF_TRUE; }
ERL_NIF_TERM** array = (ERL_NIF_TERM**) a0;
// ok ... check arity
if (array == NULL)
return NIF_TRUE;
*array = (ERL_NIF_TERM*)malloc( sizeof(ERL_NIF_TERM) * count );
for (int i = 0; i < count; i++) {
(*array)[i] = jnif_retain(ee, je->CallObjectMethod( tup, m_etuple__elm, i+1) );
}
// TODO: free *array in environment
return NIF_TRUE;
}
extern ERL_NIF_TERM enif_make_tuple (ErlNifEnv* ee, unsigned cnt, ...)
{
ERL_NIF_TERM args[cnt];
if (cnt > 0) {
va_list vl;
va_start(vl,cnt);
for (int i = 0; i < cnt; i++)
{
args[i] = va_arg(vl,ERL_NIF_TERM);
}
va_end(vl);
}
jobject tup;
tup = ee->je->CallStaticObjectMethod(etuple_class, m_etuple__make, cnt);
for (int i = 0; i < cnt; i++) {
ee->je->CallVoidMethod(tup, m_etuple__set, (jint)(i+1), (jobject)E2J(args[i]));
}
#ifdef DEBUG
jstring str = (jstring) ee->je->CallObjectMethod(tup, m_object__toString);
const char *path = str == NULL ? NULL : ee->je->GetStringUTFChars(str, NULL);
fprintf(stderr, "created: %s\n", path);
ee->je->ReleaseStringUTFChars(str, path);
#endif
return jnif_retain(ee, tup);
}
void initialize_jnif_tuple(JavaVM* vm, JNIEnv *je)
{
jclass eobject_class = je->FindClass("erjang/EObject");
m_eobject__testTuple = je->GetMethodID(eobject_class,
"testTuple",
"()Lerjang/ETuple;");
etuple_class = je->FindClass("erjang/ETuple");
etuple_class = (jclass) je->NewGlobalRef(etuple_class);
m_etuple__make = je->GetStaticMethodID(etuple_class,
"make",
"(I)Lerjang/ETuple;");
m_etuple__set = je->GetMethodID(etuple_class,
"set",
"(ILerjang/EObject;)V");
m_etuple__elm = je->GetMethodID(etuple_class,
"elm",
"(I)Lerjang/EObject;");
m_etuple__arity = je->GetMethodID(etuple_class,
"arity",
"()I");
jclass object_class = je->FindClass("java/lang/String");
m_object__toString = je->GetMethodID(object_class,
"toString",
"()Ljava/lang/String;");
}
<|endoftext|> |
<commit_before>#include "cross_mwm_router.hpp"
#include "cross_mwm_road_graph.hpp"
#include "base/astar_algorithm.hpp"
#include "base/timer.hpp"
namespace routing
{
namespace
{
/// Function to run AStar Algorithm from the base.
IRouter::ResultCode CalculateRoute(BorderCross const & startPos, BorderCross const & finalPos,
CrossMwmGraph const & roadGraph, vector<BorderCross> & route,
my::Cancellable const & cancellable,
TRoutingVisualizerFn const & routingVisualizer)
{
using TAlgorithm = AStarAlgorithm<CrossMwmGraph>;
TAlgorithm::TOnVisitedVertexCallback onVisitedVertex = nullptr;
if (routingVisualizer)
{
onVisitedVertex = [&routingVisualizer](BorderCross const & cross)
{
routingVisualizer(cross.fromNode.point);
};
}
my::HighResTimer timer(true);
TAlgorithm::Result const result = TAlgorithm().FindPath(roadGraph, startPos, finalPos, route, cancellable, onVisitedVertex);
LOG(LINFO, ("Duration of the cross MWM path finding", timer.ElapsedNano()));
switch (result)
{
case TAlgorithm::Result::OK:
ASSERT_EQUAL(route.front(), startPos, ());
ASSERT_EQUAL(route.back(), finalPos, ());
return IRouter::NoError;
case TAlgorithm::Result::NoPath:
return IRouter::RouteNotFound;
case TAlgorithm::Result::Cancelled:
return IRouter::Cancelled;
}
return IRouter::RouteNotFound;
}
} // namespace
IRouter::ResultCode CalculateCrossMwmPath(TRoutingNodes const & startGraphNodes,
TRoutingNodes const & finalGraphNodes,
RoutingIndexManager & indexManager,
my::Cancellable const & cancellable,
TRoutingVisualizerFn const & routingVisualizer,
TCheckedPath & route)
{
CrossMwmGraph roadGraph(indexManager);
FeatureGraphNode startGraphNode, finalGraphNode;
CrossNode startNode, finalNode;
// Finding start node.
IRouter::ResultCode code = IRouter::StartPointNotFound;
for (FeatureGraphNode const & start : startGraphNodes)
{
startNode = CrossNode(start.node.forward_node_id, start.mwmName, start.segmentPoint);
code = roadGraph.SetStartNode(startNode);
if (code == IRouter::NoError)
{
startGraphNode = start;
break;
}
}
if (code != IRouter::NoError)
return IRouter::StartPointNotFound;
// Finding final node.
code = IRouter::EndPointNotFound;
for (FeatureGraphNode const & final : finalGraphNodes)
{
finalNode = CrossNode(final.node.reverse_node_id, final.mwmName, final.segmentPoint);
code = roadGraph.SetFinalNode(finalNode);
if (code == IRouter::NoError)
{
finalGraphNode = final;
break;
}
}
if (code != IRouter::NoError)
return IRouter::EndPointNotFound;
// Finding path through maps.
vector<BorderCross> tempRoad;
code = CalculateRoute({startNode, startNode}, {finalNode, finalNode}, roadGraph, tempRoad,
cancellable, routingVisualizer);
if (code != IRouter::NoError)
return code;
// Final path conversion to output type.
for (size_t i = 0; i < tempRoad.size() - 1; ++i)
{
route.emplace_back(tempRoad[i].toNode.node, tempRoad[i + 1].fromNode.node,
tempRoad[i].toNode.mwmName);
}
if (!route.empty())
{
route.front().startNode = startGraphNode;
route.back().finalNode = finalGraphNode;
return IRouter::NoError;
}
return IRouter::RouteNotFound;
}
} // namespace routing
<commit_msg>Point on out node cross mwm fix.<commit_after>#include "cross_mwm_router.hpp"
#include "cross_mwm_road_graph.hpp"
#include "base/astar_algorithm.hpp"
#include "base/timer.hpp"
namespace routing
{
namespace
{
/// Function to run AStar Algorithm from the base.
IRouter::ResultCode CalculateRoute(BorderCross const & startPos, BorderCross const & finalPos,
CrossMwmGraph const & roadGraph, vector<BorderCross> & route,
my::Cancellable const & cancellable,
TRoutingVisualizerFn const & routingVisualizer)
{
using TAlgorithm = AStarAlgorithm<CrossMwmGraph>;
TAlgorithm::TOnVisitedVertexCallback onVisitedVertex = nullptr;
if (routingVisualizer)
{
onVisitedVertex = [&routingVisualizer](BorderCross const & cross)
{
routingVisualizer(cross.fromNode.point);
};
}
my::HighResTimer timer(true);
TAlgorithm::Result const result = TAlgorithm().FindPath(roadGraph, startPos, finalPos, route, cancellable, onVisitedVertex);
LOG(LINFO, ("Duration of the cross MWM path finding", timer.ElapsedNano()));
switch (result)
{
case TAlgorithm::Result::OK:
ASSERT_EQUAL(route.front(), startPos, ());
ASSERT_EQUAL(route.back(), finalPos, ());
return IRouter::NoError;
case TAlgorithm::Result::NoPath:
return IRouter::RouteNotFound;
case TAlgorithm::Result::Cancelled:
return IRouter::Cancelled;
}
return IRouter::RouteNotFound;
}
} // namespace
IRouter::ResultCode CalculateCrossMwmPath(TRoutingNodes const & startGraphNodes,
TRoutingNodes const & finalGraphNodes,
RoutingIndexManager & indexManager,
my::Cancellable const & cancellable,
TRoutingVisualizerFn const & routingVisualizer,
TCheckedPath & route)
{
CrossMwmGraph roadGraph(indexManager);
FeatureGraphNode startGraphNode, finalGraphNode;
CrossNode startNode, finalNode;
// Finding start node.
IRouter::ResultCode code = IRouter::StartPointNotFound;
for (FeatureGraphNode const & start : startGraphNodes)
{
startNode = CrossNode(start.node.forward_node_id, start.mwmName, start.segmentPoint);
code = roadGraph.SetStartNode(startNode);
if (code == IRouter::NoError)
{
startGraphNode = start;
break;
}
}
if (code != IRouter::NoError)
return IRouter::StartPointNotFound;
// Finding final node.
code = IRouter::EndPointNotFound;
for (FeatureGraphNode const & final : finalGraphNodes)
{
finalNode = CrossNode(final.node.reverse_node_id, final.mwmName, final.segmentPoint);
code = roadGraph.SetFinalNode(finalNode);
if (code == IRouter::NoError)
{
finalGraphNode = final;
break;
}
}
if (code != IRouter::NoError)
return IRouter::EndPointNotFound;
// Finding path through maps.
vector<BorderCross> tempRoad;
code = CalculateRoute({startNode, startNode}, {finalNode, finalNode}, roadGraph, tempRoad,
cancellable, routingVisualizer);
if (code != IRouter::NoError)
return code;
// Final path conversion to output type.
for (size_t i = 0; i < tempRoad.size() - 1; ++i)
{
route.emplace_back(tempRoad[i].toNode.node, tempRoad[i + 1].fromNode.node,
tempRoad[i].toNode.mwmName);
}
if (!route.empty())
{
route.front().startNode = startGraphNode;
// Stop point lays on out edge, and we have no virtual edge to unpack.
if (route.back().startNode.mwmName != finalGraphNode.mwmName)
route.emplace_back(RoutePathCross(tempRoad.back().toNode.node, tempRoad.back().toNode.node, tempRoad.back().toNode.mwmName));
route.back().finalNode = finalGraphNode;
return IRouter::NoError;
}
return IRouter::RouteNotFound;
}
} // namespace routing
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: rschash.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2005-01-03 17:31:09 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _RSCHASH_HXX
#include <rschash.hxx>
#endif
using namespace rtl;
AtomContainer::AtomContainer()
{
m_aStringToID[ OString() ] = 0;
m_aIDToString[ 0 ] = OString();
m_nNextID = 1;
}
AtomContainer::~AtomContainer()
{
}
Atom AtomContainer::getID( const OString& rStr, bool bOnlyIfExists )
{
OString aKey = rStr.toAsciiLowerCase();
std::hash_map< OString, Atom, OStringHash >::const_iterator it =
m_aStringToID.find( aKey );
if( it != m_aStringToID.end() )
return it->second;
if( bOnlyIfExists )
return InvalidAtom;
Atom aRet = m_nNextID;
m_aStringToID[ aKey ] = m_nNextID;
m_aIDToString[ m_nNextID ] = rStr;
m_nNextID++;
return aRet;
}
const OString& AtomContainer::getString( Atom nAtom )
{
std::hash_map< Atom, OString >::const_iterator it =
m_aIDToString.find( nAtom );
return (it != m_aIDToString.end()) ? it->second : m_aIDToString[0];
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.18); FILE MERGED 2005/09/05 18:47:04 rt 1.4.18.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rschash.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 14:01:43 $
*
* 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 _RSCHASH_HXX
#include <rschash.hxx>
#endif
using namespace rtl;
AtomContainer::AtomContainer()
{
m_aStringToID[ OString() ] = 0;
m_aIDToString[ 0 ] = OString();
m_nNextID = 1;
}
AtomContainer::~AtomContainer()
{
}
Atom AtomContainer::getID( const OString& rStr, bool bOnlyIfExists )
{
OString aKey = rStr.toAsciiLowerCase();
std::hash_map< OString, Atom, OStringHash >::const_iterator it =
m_aStringToID.find( aKey );
if( it != m_aStringToID.end() )
return it->second;
if( bOnlyIfExists )
return InvalidAtom;
Atom aRet = m_nNextID;
m_aStringToID[ aKey ] = m_nNextID;
m_aIDToString[ m_nNextID ] = rStr;
m_nNextID++;
return aRet;
}
const OString& AtomContainer::getString( Atom nAtom )
{
std::hash_map< Atom, OString >::const_iterator it =
m_aIDToString.find( nAtom );
return (it != m_aIDToString.end()) ? it->second : m_aIDToString[0];
}
<|endoftext|> |
<commit_before>/*
* This file is part of the Camera Streaming Daemon
*
* Copyright (C) 2017 Intel Corporation. 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 <fcntl.h>
#include <gst/app/gstappsrc.h>
#include <librealsense/rs.h>
#include <sstream>
#include <sys/ioctl.h>
#include <unistd.h>
#include "log.h"
#include "samples/stream_realsense.h"
#define WIDTH (640)
#define HEIGHT (480)
#define SIZE (WIDTH * HEIGHT * 3)
#define ONE_METER (999)
struct rgb {
unsigned char r;
unsigned char g;
unsigned char b;
};
static void cb_need_data(GstAppSrc *appsrc, guint unused_size, gpointer user_data)
{
GstFlowReturn ret;
rs_device *dev = (rs_device *)user_data;
rs_wait_for_frames(dev, NULL);
uint16_t *depth = (uint16_t *)rs_get_frame_data(dev, RS_STREAM_DEPTH, NULL);
struct rgb *rgb = (struct rgb *)rs_get_frame_data(dev, RS_STREAM_COLOR, NULL);
if (!rgb) {
log_error("Realsense error");
return;
}
GstBuffer *buffer
= gst_buffer_new_wrapped_full((GstMemoryFlags)0, rgb, SIZE, 0, SIZE, NULL, NULL);
for (int i = 0, end = WIDTH * HEIGHT; i < end; ++i) {
rgb[i].r = depth[i] * 60 / ONE_METER;
rgb[i].g /= 4;
rgb[i].b /= 4;
}
g_signal_emit_by_name(appsrc, "push-buffer", buffer, &ret);
}
static void cb_enough_data(GstAppSrc *src, gpointer user_data)
{
}
static gboolean cb_seek_data(GstAppSrc *src, guint64 offset, gpointer user_data)
{
return TRUE;
}
StreamRealSense::StreamRealSense()
: Stream()
{
}
const std::string StreamRealSense::get_path() const
{
return "/RealSense";
}
const std::string StreamRealSense::get_name() const
{
return "RealSense Sample Stream";
}
const std::vector<Stream::PixelFormat> &StreamRealSense::get_formats() const
{
static std::vector<Stream::PixelFormat> formats;
return formats;
}
GstElement *
StreamRealSense::create_gstreamer_pipeline(std::map<std::string, std::string> ¶ms) const
{
/* librealsense */
rs_error *e = 0;
rs_context *ctx = rs_create_context(RS_API_VERSION, &e);
if (e) {
log_error("rs_error was raised when calling %s(%s): %s", rs_get_failed_function(e),
rs_get_failed_args(e), rs_get_error_message(e));
log_error("Current librealsense api version %d", rs_get_api_version(NULL));
log_error("Compiled for librealsense api version %d", RS_API_VERSION);
return nullptr;
}
rs_device *dev = rs_get_device(ctx, 0, NULL);
if (!dev) {
log_error("Unable to access realsense device");
return nullptr;
}
/* Configure all streams to run at VGA resolution at 60 frames per second */
rs_enable_stream(dev, RS_STREAM_DEPTH, WIDTH, HEIGHT, RS_FORMAT_Z16, 60, NULL);
rs_enable_stream(dev, RS_STREAM_COLOR, WIDTH, HEIGHT, RS_FORMAT_RGB8, 60, NULL);
rs_start_device(dev, NULL);
/* gstreamer */
GError *error = nullptr;
GstElement *pipeline;
pipeline = gst_parse_launch("appsrc name=mysource ! videoconvert ! "
"video/x-raw,width=640,height=480,format=NV12 ! vaapih264enc ! "
"rtph264pay name=pay0",
&error);
if (!pipeline) {
log_error("Error processing pipeline for RealSense stream device: %s\n",
error ? error->message : "unknown error");
g_clear_error(&error);
return nullptr;
}
GstElement *appsrc = gst_bin_get_by_name(GST_BIN(pipeline), "mysource");
/* setup */
gst_app_src_set_caps(GST_APP_SRC(appsrc),
gst_caps_new_simple("video/x-raw", "format", G_TYPE_STRING, "RGB", "width",
G_TYPE_INT, WIDTH, "height", G_TYPE_INT, HEIGHT,
NULL));
/* setup appsrc */
g_object_set(G_OBJECT(appsrc), "is-live", TRUE, "format", GST_FORMAT_TIME, NULL);
/* connect signals */
GstAppSrcCallbacks cbs;
cbs.need_data = cb_need_data;
cbs.enough_data = cb_enough_data;
cbs.seek_data = cb_seek_data;
gst_app_src_set_callbacks(GST_APP_SRC_CAST(appsrc), &cbs, dev, NULL);
g_object_set_data(G_OBJECT(pipeline), "rs_context", ctx);
return pipeline;
}
void StreamRealSense::finalize_gstreamer_pipeline(GstElement *pipeline)
{
rs_context *ctx = (rs_context *)g_object_get_data(G_OBJECT(pipeline), "rs_context");
if (!ctx) {
log_error("Media not created by stream_realsense is being cleared with stream_realsense");
return;
}
rs_delete_context(ctx, NULL);
}
<commit_msg>Improve visualization of RealSense stream<commit_after>/*
* This file is part of the Camera Streaming Daemon
*
* Copyright (C) 2017 Intel Corporation. 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 <assert.h>
#include <fcntl.h>
#include <gst/app/gstappsrc.h>
#include <librealsense/rs.h>
#include <sstream>
#include <sys/ioctl.h>
#include <unistd.h>
#include "log.h"
#include "samples/stream_realsense.h"
#define WIDTH (640)
#define HEIGHT (480)
#define SIZE (WIDTH * HEIGHT * 3)
#define ONE_METER (999)
struct rgb {
uint8_t r;
uint8_t g;
uint8_t b;
};
struct Context {
rs_device *dev;
rs_context *rs_ctx;
struct rgb rgb_data[];
};
static void rainbow_scale(double value, uint8_t rgb[])
{
rgb[0] = rgb[1] = rgb[2] = 0;
if (value <= 0.0)
return;
if (value < 0.25) { // RED to YELLOW
rgb[0] = 255;
rgb[1] = (uint8_t)255 * (value / 0.25);
} else if (value < 0.5) { // YELLOW to GREEN
rgb[0] = (uint8_t)255 * (1 - ((value - 0.25) / 0.25));
rgb[1] = 255;
} else if (value < 0.75) { // GREEN to CYAN
rgb[1] = 255;
rgb[2] = (uint8_t)255 * (value - 0.5 / 0.25);
} else if (value < 1.0) { // CYAN to BLUE
rgb[1] = (uint8_t)255 * (1 - ((value - 0.75) / 0.25));
rgb[2] = 255;
} else { // BLUE
rgb[2] = 255;
}
}
static void cb_need_data(GstAppSrc *appsrc, guint unused_size, gpointer user_data)
{
GstFlowReturn ret;
Context *ctx = (Context *)user_data;
rs_wait_for_frames(ctx->dev, NULL);
uint16_t *depth = (uint16_t *)rs_get_frame_data(ctx->dev, RS_STREAM_DEPTH, NULL);
if (!depth) {
log_error("No depth data. Not building frame");
return;
}
GstBuffer *buffer
= gst_buffer_new_wrapped_full((GstMemoryFlags)0, ctx->rgb_data, SIZE, 0, SIZE, NULL, NULL);
assert(buffer);
for (int i = 0, end = WIDTH * HEIGHT; i < end; ++i) {
uint8_t rainbow[3];
rainbow_scale((double)depth[i] * 0.001, rainbow);
ctx->rgb_data[i].r = rainbow[0];
ctx->rgb_data[i].g = rainbow[1];
ctx->rgb_data[i].b = rainbow[2];
}
g_signal_emit_by_name(appsrc, "push-buffer", buffer, &ret);
}
static void cb_enough_data(GstAppSrc *src, gpointer user_data)
{
}
static gboolean cb_seek_data(GstAppSrc *src, guint64 offset, gpointer user_data)
{
return TRUE;
}
StreamRealSense::StreamRealSense()
: Stream()
{
}
const std::string StreamRealSense::get_path() const
{
return "/RealSense";
}
const std::string StreamRealSense::get_name() const
{
return "RealSense Sample Stream";
}
const std::vector<Stream::PixelFormat> &StreamRealSense::get_formats() const
{
static std::vector<Stream::PixelFormat> formats;
return formats;
}
GstElement *
StreamRealSense::create_gstreamer_pipeline(std::map<std::string, std::string> ¶ms) const
{
Context *ctx = (Context *)malloc(sizeof(Context) + SIZE);
assert(ctx);
/* librealsense */
rs_error *e = 0;
ctx->rs_ctx = rs_create_context(RS_API_VERSION, &e);
if (e) {
log_error("rs_error was raised when calling %s(%s): %s", rs_get_failed_function(e),
rs_get_failed_args(e), rs_get_error_message(e));
log_error("Current librealsense api version %d", rs_get_api_version(NULL));
log_error("Compiled for librealsense api version %d", RS_API_VERSION);
return nullptr;
}
ctx->dev = rs_get_device(ctx->rs_ctx, 0, NULL);
if (!ctx->dev) {
log_error("Unable to access realsense device");
return nullptr;
}
/* Configure all streams to run at VGA resolution at 60 frames per second */
rs_enable_stream(ctx->dev, RS_STREAM_DEPTH, WIDTH, HEIGHT, RS_FORMAT_Z16, 60, NULL);
rs_start_device(ctx->dev, NULL);
/* gstreamer */
GError *error = nullptr;
GstElement *pipeline;
pipeline = gst_parse_launch("appsrc name=mysource ! videoconvert ! "
"video/x-raw,width=640,height=480,format=NV12 ! vaapih264enc ! "
"rtph264pay name=pay0",
&error);
if (!pipeline) {
log_error("Error processing pipeline for RealSense stream device: %s\n",
error ? error->message : "unknown error");
g_clear_error(&error);
return nullptr;
}
GstElement *appsrc = gst_bin_get_by_name(GST_BIN(pipeline), "mysource");
/* setup */
gst_app_src_set_caps(GST_APP_SRC(appsrc),
gst_caps_new_simple("video/x-raw", "format", G_TYPE_STRING, "RGB", "width",
G_TYPE_INT, WIDTH, "height", G_TYPE_INT, HEIGHT,
NULL));
/* setup appsrc */
g_object_set(G_OBJECT(appsrc), "is-live", TRUE, "format", GST_FORMAT_TIME, NULL);
/* connect signals */
GstAppSrcCallbacks cbs;
cbs.need_data = cb_need_data;
cbs.enough_data = cb_enough_data;
cbs.seek_data = cb_seek_data;
gst_app_src_set_callbacks(GST_APP_SRC_CAST(appsrc), &cbs, ctx, NULL);
g_object_set_data(G_OBJECT(pipeline), "context", ctx);
return pipeline;
}
void StreamRealSense::finalize_gstreamer_pipeline(GstElement *pipeline)
{
Context *ctx = (Context *)g_object_get_data(G_OBJECT(pipeline), "context");
if (!ctx) {
log_error("Media not created by stream_realsense is being cleared with stream_realsense");
return;
}
rs_delete_context(ctx->rs_ctx, NULL);
free(ctx);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: docfunc.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: rt $ $Date: 2006-05-05 09:44:58 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_DOCFUNC_HXX
#define SC_DOCFUNC_HXX
#ifndef _LINK_HXX //autogen
#include <tools/link.hxx>
#endif
#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
#ifndef SC_POSTIT_HXX
#include "postit.hxx"
#endif
class ScEditEngineDefaulter;
class SfxUndoAction;
class ScAddress;
class ScDocShell;
class ScMarkData;
class ScPatternAttr;
class ScRange;
class ScRangeName;
class ScBaseCell;
struct ScTabOpParam;
// ---------------------------------------------------------------------------
class ScDocFunc
{
private:
ScDocShell& rDocShell;
BOOL AdjustRowHeight( const ScRange& rRange, BOOL bPaint = TRUE );
void CreateOneName( ScRangeName& rList,
SCCOL nPosX, SCROW nPosY, SCTAB nTab,
SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
BOOL& rCancel, BOOL bApi );
void NotifyInputHandler( const ScAddress& rPos );
public:
ScDocFunc( ScDocShell& rDocSh ): rDocShell(rDocSh) {}
~ScDocFunc() {}
DECL_LINK( NotifyDrawUndo, SfxUndoAction* );
BOOL DetectiveAddPred(const ScAddress& rPos);
BOOL DetectiveDelPred(const ScAddress& rPos);
BOOL DetectiveAddSucc(const ScAddress& rPos);
BOOL DetectiveDelSucc(const ScAddress& rPos);
BOOL DetectiveAddError(const ScAddress& rPos);
BOOL DetectiveMarkInvalid(SCTAB nTab);
BOOL DetectiveDelAll(SCTAB nTab);
BOOL DetectiveRefresh(BOOL bAutomatic = FALSE);
BOOL DeleteContents( const ScMarkData& rMark, USHORT nFlags,
BOOL bRecord, BOOL bApi );
BOOL TransliterateText( const ScMarkData& rMark, sal_Int32 nType,
BOOL bRecord, BOOL bApi );
BOOL SetNormalString( const ScAddress& rPos, const String& rText, BOOL bApi );
BOOL PutCell( const ScAddress& rPos, ScBaseCell* pNewCell, BOOL bApi );
BOOL PutData( const ScAddress& rPos, ScEditEngineDefaulter& rEngine,
BOOL bInterpret, BOOL bApi );
BOOL SetCellText( const ScAddress& rPos, const String& rText,
BOOL bInterpret, BOOL bEnglish, BOOL bApi );
// creates a new cell for use with PutCell
ScBaseCell* InterpretEnglishString( const ScAddress& rPos, const String& rText );
BOOL SetNoteText( const ScAddress& rPos, const String& rText, BOOL bApi );
BOOL ApplyAttributes( const ScMarkData& rMark, const ScPatternAttr& rPattern,
BOOL bRecord, BOOL bApi );
BOOL ApplyStyle( const ScMarkData& rMark, const String& rStyleName,
BOOL bRecord, BOOL bApi );
BOOL InsertCells( const ScRange& rRange, InsCellCmd eCmd, BOOL bRecord, BOOL bApi,
BOOL bPartOfPaste = FALSE );
BOOL DeleteCells( const ScRange& rRange, DelCellCmd eCmd, BOOL bRecord, BOOL bApi );
BOOL MoveBlock( const ScRange& rSource, const ScAddress& rDestPos,
BOOL bCut, BOOL bRecord, BOOL bPaint, BOOL bApi );
BOOL InsertTable( SCTAB nTab, const String& rName, BOOL bRecord, BOOL bApi );
BOOL RenameTable( SCTAB nTab, const String& rName, BOOL bRecord, BOOL bApi );
BOOL DeleteTable( SCTAB nTab, BOOL bRecord, BOOL bApi );
BOOL SetTableVisible( SCTAB nTab, BOOL bVisible, BOOL bApi );
BOOL SetLayoutRTL( SCTAB nTab, BOOL bRTL, BOOL bApi );
BOOL SetWidthOrHeight( BOOL bWidth, SCCOLROW nRangeCnt, SCCOLROW* pRanges,
SCTAB nTab, ScSizeMode eMode, USHORT nSizeTwips,
BOOL bRecord, BOOL bApi );
BOOL InsertPageBreak( BOOL bColumn, const ScAddress& rPos,
BOOL bRecord, BOOL bSetModified, BOOL bApi );
BOOL RemovePageBreak( BOOL bColumn, const ScAddress& rPos,
BOOL bRecord, BOOL bSetModified, BOOL bApi );
BOOL Protect( SCTAB nTab, const String& rPassword, BOOL bApi );
BOOL Unprotect( SCTAB nTab, const String& rPassword, BOOL bApi );
BOOL ClearItems( const ScMarkData& rMark, const USHORT* pWhich, BOOL bApi );
BOOL ChangeIndent( const ScMarkData& rMark, BOOL bIncrement, BOOL bApi );
BOOL AutoFormat( const ScRange& rRange, const ScMarkData* pTabMark,
USHORT nFormatNo, BOOL bRecord, BOOL bApi );
BOOL EnterMatrix( const ScRange& rRange, const ScMarkData* pTabMark,
const String& rString, BOOL bApi, BOOL bEnglish );
BOOL TabOp( const ScRange& rRange, const ScMarkData* pTabMark,
const ScTabOpParam& rParam, BOOL bRecord, BOOL bApi );
BOOL FillSimple( const ScRange& rRange, const ScMarkData* pTabMark,
FillDir eDir, BOOL bRecord, BOOL bApi );
BOOL FillSeries( const ScRange& rRange, const ScMarkData* pTabMark,
FillDir eDir, FillCmd eCmd, FillDateCmd eDateCmd,
double fStart, double fStep, double fMax,
BOOL bRecord, BOOL bApi );
// FillAuto: rRange wird von Source-Range auf Dest-Range angepasst
BOOL FillAuto( ScRange& rRange, const ScMarkData* pTabMark,
FillDir eDir, ULONG nCount, BOOL bRecord, BOOL bApi );
BOOL ResizeMatrix( const ScRange& rOldRange, const ScAddress& rNewEnd, BOOL bApi );
BOOL MergeCells( const ScRange& rRange, BOOL bContents,
BOOL bRecord, BOOL bApi );
BOOL UnmergeCells( const ScRange& rRange, BOOL bRecord, BOOL bApi );
BOOL SetNote( const ScAddress& rPos, const ScPostIt& rNote, BOOL bApi );
BOOL SetNewRangeNames( ScRangeName* pNewRanges, BOOL bApi ); // takes ownership of pNewRanges
BOOL ModifyRangeNames( const ScRangeName& rNewRanges, BOOL bApi );
BOOL CreateNames( const ScRange& rRange, USHORT nFlags, BOOL bApi );
BOOL InsertNameList( const ScAddress& rStartPos, BOOL bApi );
BOOL InsertAreaLink( const String& rFile, const String& rFilter,
const String& rOptions, const String& rSource,
const ScRange& rDestRange, ULONG nRefresh,
BOOL bFitBlock, BOOL bApi );
};
#endif
<commit_msg>INTEGRATION: CWS scr1c1 (1.13.122); FILE MERGED 2006/09/07 14:20:56 jodygoldberg 1.13.122.1: Issue number: 20857 Submitted by: jodygoldberg<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: docfunc.hxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: ihi $ $Date: 2006-10-18 12:27:37 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_DOCFUNC_HXX
#define SC_DOCFUNC_HXX
#ifndef _LINK_HXX //autogen
#include <tools/link.hxx>
#endif
#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
#ifndef SC_POSTIT_HXX
#include "postit.hxx"
#endif
class ScEditEngineDefaulter;
class SfxUndoAction;
class ScAddress;
class ScDocShell;
class ScMarkData;
class ScPatternAttr;
class ScRange;
class ScRangeName;
class ScBaseCell;
struct ScTabOpParam;
// ---------------------------------------------------------------------------
class ScDocFunc
{
private:
ScDocShell& rDocShell;
BOOL AdjustRowHeight( const ScRange& rRange, BOOL bPaint = TRUE );
void CreateOneName( ScRangeName& rList,
SCCOL nPosX, SCROW nPosY, SCTAB nTab,
SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
BOOL& rCancel, BOOL bApi );
void NotifyInputHandler( const ScAddress& rPos );
public:
ScDocFunc( ScDocShell& rDocSh ): rDocShell(rDocSh) {}
~ScDocFunc() {}
DECL_LINK( NotifyDrawUndo, SfxUndoAction* );
BOOL DetectiveAddPred(const ScAddress& rPos);
BOOL DetectiveDelPred(const ScAddress& rPos);
BOOL DetectiveAddSucc(const ScAddress& rPos);
BOOL DetectiveDelSucc(const ScAddress& rPos);
BOOL DetectiveAddError(const ScAddress& rPos);
BOOL DetectiveMarkInvalid(SCTAB nTab);
BOOL DetectiveDelAll(SCTAB nTab);
BOOL DetectiveRefresh(BOOL bAutomatic = FALSE);
BOOL DeleteContents( const ScMarkData& rMark, USHORT nFlags,
BOOL bRecord, BOOL bApi );
BOOL TransliterateText( const ScMarkData& rMark, sal_Int32 nType,
BOOL bRecord, BOOL bApi );
BOOL SetNormalString( const ScAddress& rPos, const String& rText, BOOL bApi );
BOOL PutCell( const ScAddress& rPos, ScBaseCell* pNewCell, BOOL bApi );
BOOL PutData( const ScAddress& rPos, ScEditEngineDefaulter& rEngine,
BOOL bInterpret, BOOL bApi );
BOOL SetCellText( const ScAddress& rPos, const String& rText,
BOOL bInterpret, BOOL bEnglish, BOOL bApi );
// creates a new cell for use with PutCell
ScBaseCell* InterpretEnglishString( const ScAddress& rPos, const String& rText );
BOOL SetNoteText( const ScAddress& rPos, const String& rText, BOOL bApi );
BOOL ApplyAttributes( const ScMarkData& rMark, const ScPatternAttr& rPattern,
BOOL bRecord, BOOL bApi );
BOOL ApplyStyle( const ScMarkData& rMark, const String& rStyleName,
BOOL bRecord, BOOL bApi );
BOOL InsertCells( const ScRange& rRange, InsCellCmd eCmd, BOOL bRecord, BOOL bApi,
BOOL bPartOfPaste = FALSE );
BOOL DeleteCells( const ScRange& rRange, DelCellCmd eCmd, BOOL bRecord, BOOL bApi );
BOOL MoveBlock( const ScRange& rSource, const ScAddress& rDestPos,
BOOL bCut, BOOL bRecord, BOOL bPaint, BOOL bApi );
BOOL InsertTable( SCTAB nTab, const String& rName, BOOL bRecord, BOOL bApi );
BOOL RenameTable( SCTAB nTab, const String& rName, BOOL bRecord, BOOL bApi );
BOOL DeleteTable( SCTAB nTab, BOOL bRecord, BOOL bApi );
BOOL SetTableVisible( SCTAB nTab, BOOL bVisible, BOOL bApi );
BOOL SetLayoutRTL( SCTAB nTab, BOOL bRTL, BOOL bApi );
BOOL SetAddressConvention( ScAddress::Convention eConv );
BOOL SetWidthOrHeight( BOOL bWidth, SCCOLROW nRangeCnt, SCCOLROW* pRanges,
SCTAB nTab, ScSizeMode eMode, USHORT nSizeTwips,
BOOL bRecord, BOOL bApi );
BOOL InsertPageBreak( BOOL bColumn, const ScAddress& rPos,
BOOL bRecord, BOOL bSetModified, BOOL bApi );
BOOL RemovePageBreak( BOOL bColumn, const ScAddress& rPos,
BOOL bRecord, BOOL bSetModified, BOOL bApi );
BOOL Protect( SCTAB nTab, const String& rPassword, BOOL bApi );
BOOL Unprotect( SCTAB nTab, const String& rPassword, BOOL bApi );
BOOL ClearItems( const ScMarkData& rMark, const USHORT* pWhich, BOOL bApi );
BOOL ChangeIndent( const ScMarkData& rMark, BOOL bIncrement, BOOL bApi );
BOOL AutoFormat( const ScRange& rRange, const ScMarkData* pTabMark,
USHORT nFormatNo, BOOL bRecord, BOOL bApi );
BOOL EnterMatrix( const ScRange& rRange, const ScMarkData* pTabMark,
const String& rString, BOOL bApi, BOOL bEnglish );
BOOL TabOp( const ScRange& rRange, const ScMarkData* pTabMark,
const ScTabOpParam& rParam, BOOL bRecord, BOOL bApi );
BOOL FillSimple( const ScRange& rRange, const ScMarkData* pTabMark,
FillDir eDir, BOOL bRecord, BOOL bApi );
BOOL FillSeries( const ScRange& rRange, const ScMarkData* pTabMark,
FillDir eDir, FillCmd eCmd, FillDateCmd eDateCmd,
double fStart, double fStep, double fMax,
BOOL bRecord, BOOL bApi );
// FillAuto: rRange wird von Source-Range auf Dest-Range angepasst
BOOL FillAuto( ScRange& rRange, const ScMarkData* pTabMark,
FillDir eDir, ULONG nCount, BOOL bRecord, BOOL bApi );
BOOL ResizeMatrix( const ScRange& rOldRange, const ScAddress& rNewEnd, BOOL bApi );
BOOL MergeCells( const ScRange& rRange, BOOL bContents,
BOOL bRecord, BOOL bApi );
BOOL UnmergeCells( const ScRange& rRange, BOOL bRecord, BOOL bApi );
BOOL SetNote( const ScAddress& rPos, const ScPostIt& rNote, BOOL bApi );
BOOL SetNewRangeNames( ScRangeName* pNewRanges, BOOL bApi ); // takes ownership of pNewRanges
BOOL ModifyRangeNames( const ScRangeName& rNewRanges, BOOL bApi );
BOOL CreateNames( const ScRange& rRange, USHORT nFlags, BOOL bApi );
BOOL InsertNameList( const ScAddress& rStartPos, BOOL bApi );
BOOL InsertAreaLink( const String& rFile, const String& rFilter,
const String& rOptions, const String& rSource,
const ScRange& rDestRange, ULONG nRefresh,
BOOL bFitBlock, BOOL bApi );
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: tabcont.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2004-06-04 11:41:24 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_TABCONT_HXX
#define SC_TABCONT_HXX
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
#ifndef _TABBAR_HXX //autogen wg. TabBar
#include <svtools/tabbar.hxx>
#endif
#ifndef _TRANSFER_HXX
#include <svtools/transfer.hxx>
#endif
class ScViewData;
// ---------------------------------------------------------------------------
// initial size
#define SC_TABBAR_DEFWIDTH 270
class ScTabControl : public TabBar, public DropTargetHelper, public DragSourceHelper
{
private:
ScViewData* pViewData;
USHORT nMouseClickPageId; /// Last page ID after mouse button down/up
USHORT nSelPageIdByMouse; /// Selected page ID, if selected with mouse
BOOL bErrorShown;
void DoDrag( const Region& rRegion );
USHORT GetMaxId() const;
SCTAB GetPrivatDropPos(const Point& rPos );
protected:
virtual void Select();
virtual void Command( const CommandEvent& rCEvt );
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void MouseButtonUp( const MouseEvent& rMEvt );
virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );
virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );
virtual void StartDrag( sal_Int8 nAction, const Point& rPosPixel );
virtual long StartRenaming();
virtual long AllowRenaming();
virtual void EndRenaming();
virtual void Mirror();
public:
ScTabControl( Window* pParent, ScViewData* pData );
~ScTabControl();
void UpdateStatus();
void ActivateView(BOOL bActivate);
void SetSheetLayoutRTL( BOOL bSheetRTL );
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.452); FILE MERGED 2005/09/05 15:05:55 rt 1.5.452.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tabcont.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:54:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_TABCONT_HXX
#define SC_TABCONT_HXX
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
#ifndef _TABBAR_HXX //autogen wg. TabBar
#include <svtools/tabbar.hxx>
#endif
#ifndef _TRANSFER_HXX
#include <svtools/transfer.hxx>
#endif
class ScViewData;
// ---------------------------------------------------------------------------
// initial size
#define SC_TABBAR_DEFWIDTH 270
class ScTabControl : public TabBar, public DropTargetHelper, public DragSourceHelper
{
private:
ScViewData* pViewData;
USHORT nMouseClickPageId; /// Last page ID after mouse button down/up
USHORT nSelPageIdByMouse; /// Selected page ID, if selected with mouse
BOOL bErrorShown;
void DoDrag( const Region& rRegion );
USHORT GetMaxId() const;
SCTAB GetPrivatDropPos(const Point& rPos );
protected:
virtual void Select();
virtual void Command( const CommandEvent& rCEvt );
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void MouseButtonUp( const MouseEvent& rMEvt );
virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );
virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );
virtual void StartDrag( sal_Int8 nAction, const Point& rPosPixel );
virtual long StartRenaming();
virtual long AllowRenaming();
virtual void EndRenaming();
virtual void Mirror();
public:
ScTabControl( Window* pParent, ScViewData* pData );
~ScTabControl();
void UpdateStatus();
void ActivateView(BOOL bActivate);
void SetSheetLayoutRTL( BOOL bSheetRTL );
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: warnbox.hxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: dr $ $Date: 2002-07-11 10:52:42 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_WARNBOX_HXX
#define SC_WARNBOX_HXX
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
// ============================================================================
/** Message box with warning image and "Do not show again" checkbox. */
class ScCbWarningBox : public WarningBox
{
public:
/** @param rMsgStr Resource ID for the message text.
@param bDefYes true = "Yes" focused, false = "No" focused. */
ScCbWarningBox( Window* pParent, const String& rMsgStr, bool bDefYes = true );
/** Opens dialog if IsDialogEnabled() returns true.
@descr If after executing the dialog the checkbox "Do not show again" is set,
the method DisableDialog() will be called. */
virtual sal_Int16 Execute();
/** Called before executing the dialog. If this method returns false, the dialog will not be opened. */
virtual bool IsDialogEnabled();
/** Called, when dialog is exited and the option "Do not show again" is set. */
virtual void DisableDialog();
};
// ----------------------------------------------------------------------------
/** Warning box for "Replace cell contents?". */
class ScReplaceWarnBox : public ScCbWarningBox
{
public:
ScReplaceWarnBox( Window* pParent );
/** Reads the configuration key "ReplaceCellsWarning". */
virtual bool IsDialogEnabled();
/** Sets the configuration key "ReplaceCellsWarning" to false. */
virtual void DisableDialog();
};
// ============================================================================
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.906); FILE MERGED 2005/09/05 15:06:07 rt 1.1.906.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: warnbox.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 22:05:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_WARNBOX_HXX
#define SC_WARNBOX_HXX
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
// ============================================================================
/** Message box with warning image and "Do not show again" checkbox. */
class ScCbWarningBox : public WarningBox
{
public:
/** @param rMsgStr Resource ID for the message text.
@param bDefYes true = "Yes" focused, false = "No" focused. */
ScCbWarningBox( Window* pParent, const String& rMsgStr, bool bDefYes = true );
/** Opens dialog if IsDialogEnabled() returns true.
@descr If after executing the dialog the checkbox "Do not show again" is set,
the method DisableDialog() will be called. */
virtual sal_Int16 Execute();
/** Called before executing the dialog. If this method returns false, the dialog will not be opened. */
virtual bool IsDialogEnabled();
/** Called, when dialog is exited and the option "Do not show again" is set. */
virtual void DisableDialog();
};
// ----------------------------------------------------------------------------
/** Warning box for "Replace cell contents?". */
class ScReplaceWarnBox : public ScCbWarningBox
{
public:
ScReplaceWarnBox( Window* pParent );
/** Reads the configuration key "ReplaceCellsWarning". */
virtual bool IsDialogEnabled();
/** Sets the configuration key "ReplaceCellsWarning" to false. */
virtual void DisableDialog();
};
// ============================================================================
#endif
<|endoftext|> |
<commit_before>/*************************************************************************/
/* texture_button.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "texture_button.h"
#include "core/typedefs.h"
#include <stdlib.h>
Size2 TextureButton::get_minimum_size() const {
Size2 rscale = Control::get_minimum_size();
if (!expand) {
if (normal.is_null()) {
if (pressed.is_null()) {
if (hover.is_null())
if (click_mask.is_null())
rscale = Size2();
else
rscale = click_mask->get_size();
else
rscale = hover->get_size();
} else
rscale = pressed->get_size();
} else
rscale = normal->get_size();
}
return rscale.abs();
}
bool TextureButton::has_point(const Point2 &p_point) const {
if (click_mask.is_valid()) {
Point2 point = p_point;
Rect2 rect = Rect2();
Size2 mask_size = click_mask->get_size();
if (_tile) {
// if the stretch mode is tile we offset the point to keep it inside the mask size
rect.size = mask_size;
if (_position_rect.has_point(point)) {
int cols = (int)Math::ceil(_position_rect.size.x / mask_size.x);
int rows = (int)Math::ceil(_position_rect.size.y / mask_size.y);
int col = (int)(point.x / mask_size.x) % cols;
int row = (int)(point.y / mask_size.y) % rows;
point.x -= mask_size.x * col;
point.y -= mask_size.y * row;
}
} else {
// we need to transform the point from our scaled / translated image back to our mask image
Point2 ofs = _position_rect.position;
Size2 scale = mask_size / _position_rect.size;
switch (stretch_mode) {
case STRETCH_KEEP_ASPECT_COVERED: {
// if the stretch mode is aspect covered the image uses a texture region so we need to take that into account
float min = MIN(scale.x, scale.y);
scale.x = min;
scale.y = min;
ofs -= _texture_region.position / min;
} break;
default: {
// FIXME: Why a switch if we only handle one enum value?
}
}
// offset and scale the new point position to adjust it to the bitmask size
point -= ofs;
point *= scale;
// finally, we need to check if the point is inside a rectangle with a position >= 0,0 and a size <= mask_size
rect.position = Point2(MAX(0, _texture_region.position.x), MAX(0, _texture_region.position.y));
rect.size = Size2(MIN(mask_size.x, _texture_region.size.x), MIN(mask_size.y, _texture_region.size.y));
}
if (!rect.has_point(point)) {
return false;
}
Point2i p = point;
return click_mask->get_bit(p);
}
return Control::has_point(p_point);
}
void TextureButton::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_DRAW: {
DrawMode draw_mode = get_draw_mode();
Ref<Texture> texdraw;
switch (draw_mode) {
case DRAW_NORMAL: {
if (normal.is_valid())
texdraw = normal;
} break;
case DRAW_HOVER_PRESSED:
case DRAW_PRESSED: {
if (pressed.is_null()) {
if (hover.is_null()) {
if (normal.is_valid())
texdraw = normal;
} else
texdraw = hover;
} else
texdraw = pressed;
} break;
case DRAW_HOVER: {
if (hover.is_null()) {
if (pressed.is_valid() && is_pressed())
texdraw = pressed;
else if (normal.is_valid())
texdraw = normal;
} else
texdraw = hover;
} break;
case DRAW_DISABLED: {
if (disabled.is_null()) {
if (normal.is_valid())
texdraw = normal;
} else
texdraw = disabled;
} break;
}
if (texdraw.is_valid()) {
Point2 ofs;
Size2 size = texdraw->get_size();
_texture_region = Rect2(Point2(), texdraw->get_size());
_tile = false;
if (expand) {
switch (stretch_mode) {
case STRETCH_KEEP:
size = texdraw->get_size();
break;
case STRETCH_SCALE:
size = get_size();
break;
case STRETCH_TILE:
size = get_size();
_tile = true;
break;
case STRETCH_KEEP_CENTERED:
ofs = (get_size() - texdraw->get_size()) / 2;
size = texdraw->get_size();
break;
case STRETCH_KEEP_ASPECT_CENTERED:
case STRETCH_KEEP_ASPECT: {
Size2 _size = get_size();
float tex_width = texdraw->get_width() * _size.height / texdraw->get_height();
float tex_height = _size.height;
if (tex_width > _size.width) {
tex_width = _size.width;
tex_height = texdraw->get_height() * tex_width / texdraw->get_width();
}
if (stretch_mode == STRETCH_KEEP_ASPECT_CENTERED) {
ofs.x = (_size.width - tex_width) / 2;
ofs.y = (_size.height - tex_height) / 2;
}
size.width = tex_width;
size.height = tex_height;
} break;
case STRETCH_KEEP_ASPECT_COVERED: {
size = get_size();
Size2 tex_size = texdraw->get_size();
Size2 scaleSize(size.width / tex_size.width, size.height / tex_size.height);
float scale = scaleSize.width > scaleSize.height ? scaleSize.width : scaleSize.height;
Size2 scaledTexSize = tex_size * scale;
Point2 ofs = ((scaledTexSize - size) / scale).abs() / 2.0f;
_texture_region = Rect2(ofs, size / scale);
} break;
}
}
_position_rect = Rect2(ofs, size);
if (_tile)
draw_texture_rect(texdraw, _position_rect, _tile);
else
draw_texture_rect_region(texdraw, _position_rect, _texture_region);
}
if (has_focus() && focused.is_valid()) {
Rect2 drect(Point2(), get_size());
draw_texture_rect(focused, drect, false);
};
} break;
}
}
void TextureButton::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_normal_texture", "texture"), &TextureButton::set_normal_texture);
ClassDB::bind_method(D_METHOD("set_pressed_texture", "texture"), &TextureButton::set_pressed_texture);
ClassDB::bind_method(D_METHOD("set_hover_texture", "texture"), &TextureButton::set_hover_texture);
ClassDB::bind_method(D_METHOD("set_disabled_texture", "texture"), &TextureButton::set_disabled_texture);
ClassDB::bind_method(D_METHOD("set_focused_texture", "texture"), &TextureButton::set_focused_texture);
ClassDB::bind_method(D_METHOD("set_click_mask", "mask"), &TextureButton::set_click_mask);
ClassDB::bind_method(D_METHOD("set_expand", "p_expand"), &TextureButton::set_expand);
ClassDB::bind_method(D_METHOD("set_stretch_mode", "p_mode"), &TextureButton::set_stretch_mode);
ClassDB::bind_method(D_METHOD("get_normal_texture"), &TextureButton::get_normal_texture);
ClassDB::bind_method(D_METHOD("get_pressed_texture"), &TextureButton::get_pressed_texture);
ClassDB::bind_method(D_METHOD("get_hover_texture"), &TextureButton::get_hover_texture);
ClassDB::bind_method(D_METHOD("get_disabled_texture"), &TextureButton::get_disabled_texture);
ClassDB::bind_method(D_METHOD("get_focused_texture"), &TextureButton::get_focused_texture);
ClassDB::bind_method(D_METHOD("get_click_mask"), &TextureButton::get_click_mask);
ClassDB::bind_method(D_METHOD("get_expand"), &TextureButton::get_expand);
ClassDB::bind_method(D_METHOD("get_stretch_mode"), &TextureButton::get_stretch_mode);
ADD_GROUP("Textures", "texture_");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_normal", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_normal_texture", "get_normal_texture");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_pressed", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_pressed_texture", "get_pressed_texture");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_hover", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_hover_texture", "get_hover_texture");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_disabled", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_disabled_texture", "get_disabled_texture");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_focused", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_focused_texture", "get_focused_texture");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_click_mask", PROPERTY_HINT_RESOURCE_TYPE, "BitMap"), "set_click_mask", "get_click_mask");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "expand", PROPERTY_HINT_RESOURCE_TYPE, "bool"), "set_expand", "get_expand");
ADD_PROPERTY(PropertyInfo(Variant::INT, "stretch_mode", PROPERTY_HINT_ENUM, "Scale,Tile,Keep,Keep Centered,Keep Aspect,Keep Aspect Centered,Keep Aspect Covered"), "set_stretch_mode", "get_stretch_mode");
BIND_ENUM_CONSTANT(STRETCH_SCALE);
BIND_ENUM_CONSTANT(STRETCH_TILE);
BIND_ENUM_CONSTANT(STRETCH_KEEP);
BIND_ENUM_CONSTANT(STRETCH_KEEP_CENTERED);
BIND_ENUM_CONSTANT(STRETCH_KEEP_ASPECT);
BIND_ENUM_CONSTANT(STRETCH_KEEP_ASPECT_CENTERED);
BIND_ENUM_CONSTANT(STRETCH_KEEP_ASPECT_COVERED);
}
void TextureButton::set_normal_texture(const Ref<Texture> &p_normal) {
normal = p_normal;
update();
minimum_size_changed();
}
void TextureButton::set_pressed_texture(const Ref<Texture> &p_pressed) {
pressed = p_pressed;
update();
}
void TextureButton::set_hover_texture(const Ref<Texture> &p_hover) {
hover = p_hover;
update();
}
void TextureButton::set_disabled_texture(const Ref<Texture> &p_disabled) {
disabled = p_disabled;
update();
}
void TextureButton::set_click_mask(const Ref<BitMap> &p_click_mask) {
click_mask = p_click_mask;
update();
}
Ref<Texture> TextureButton::get_normal_texture() const {
return normal;
}
Ref<Texture> TextureButton::get_pressed_texture() const {
return pressed;
}
Ref<Texture> TextureButton::get_hover_texture() const {
return hover;
}
Ref<Texture> TextureButton::get_disabled_texture() const {
return disabled;
}
Ref<BitMap> TextureButton::get_click_mask() const {
return click_mask;
}
Ref<Texture> TextureButton::get_focused_texture() const {
return focused;
};
void TextureButton::set_focused_texture(const Ref<Texture> &p_focused) {
focused = p_focused;
};
bool TextureButton::get_expand() const {
return expand;
}
void TextureButton::set_expand(bool p_expand) {
expand = p_expand;
minimum_size_changed();
update();
}
void TextureButton::set_stretch_mode(StretchMode p_stretch_mode) {
stretch_mode = p_stretch_mode;
update();
}
TextureButton::StretchMode TextureButton::get_stretch_mode() const {
return stretch_mode;
}
TextureButton::TextureButton() {
expand = false;
stretch_mode = STRETCH_SCALE;
_texture_region = Rect2();
_position_rect = Rect2();
_tile = false;
}
<commit_msg>Fixed TextureButton click mask when no other texture is set<commit_after>/*************************************************************************/
/* texture_button.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "texture_button.h"
#include "core/typedefs.h"
#include <stdlib.h>
Size2 TextureButton::get_minimum_size() const {
Size2 rscale = Control::get_minimum_size();
if (!expand) {
if (normal.is_null()) {
if (pressed.is_null()) {
if (hover.is_null())
if (click_mask.is_null())
rscale = Size2();
else
rscale = click_mask->get_size();
else
rscale = hover->get_size();
} else
rscale = pressed->get_size();
} else
rscale = normal->get_size();
}
return rscale.abs();
}
bool TextureButton::has_point(const Point2 &p_point) const {
if (click_mask.is_valid()) {
Point2 point = p_point;
Rect2 rect = Rect2();
Size2 mask_size = click_mask->get_size();
if (_position_rect.no_area()) {
rect.size = mask_size;
} else if (_tile) {
// if the stretch mode is tile we offset the point to keep it inside the mask size
rect.size = mask_size;
if (_position_rect.has_point(point)) {
int cols = (int)Math::ceil(_position_rect.size.x / mask_size.x);
int rows = (int)Math::ceil(_position_rect.size.y / mask_size.y);
int col = (int)(point.x / mask_size.x) % cols;
int row = (int)(point.y / mask_size.y) % rows;
point.x -= mask_size.x * col;
point.y -= mask_size.y * row;
}
} else {
// we need to transform the point from our scaled / translated image back to our mask image
Point2 ofs = _position_rect.position;
Size2 scale = mask_size / _position_rect.size;
switch (stretch_mode) {
case STRETCH_KEEP_ASPECT_COVERED: {
// if the stretch mode is aspect covered the image uses a texture region so we need to take that into account
float min = MIN(scale.x, scale.y);
scale.x = min;
scale.y = min;
ofs -= _texture_region.position / min;
} break;
default: {
// FIXME: Why a switch if we only handle one enum value?
}
}
// offset and scale the new point position to adjust it to the bitmask size
point -= ofs;
point *= scale;
// finally, we need to check if the point is inside a rectangle with a position >= 0,0 and a size <= mask_size
rect.position = Point2(MAX(0, _texture_region.position.x), MAX(0, _texture_region.position.y));
rect.size = Size2(MIN(mask_size.x, _texture_region.size.x), MIN(mask_size.y, _texture_region.size.y));
}
if (!rect.has_point(point)) {
return false;
}
Point2i p = point;
return click_mask->get_bit(p);
}
return Control::has_point(p_point);
}
void TextureButton::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_DRAW: {
DrawMode draw_mode = get_draw_mode();
Ref<Texture> texdraw;
switch (draw_mode) {
case DRAW_NORMAL: {
if (normal.is_valid())
texdraw = normal;
} break;
case DRAW_HOVER_PRESSED:
case DRAW_PRESSED: {
if (pressed.is_null()) {
if (hover.is_null()) {
if (normal.is_valid())
texdraw = normal;
} else
texdraw = hover;
} else
texdraw = pressed;
} break;
case DRAW_HOVER: {
if (hover.is_null()) {
if (pressed.is_valid() && is_pressed())
texdraw = pressed;
else if (normal.is_valid())
texdraw = normal;
} else
texdraw = hover;
} break;
case DRAW_DISABLED: {
if (disabled.is_null()) {
if (normal.is_valid())
texdraw = normal;
} else
texdraw = disabled;
} break;
}
if (texdraw.is_valid()) {
Point2 ofs;
Size2 size = texdraw->get_size();
_texture_region = Rect2(Point2(), texdraw->get_size());
_tile = false;
if (expand) {
switch (stretch_mode) {
case STRETCH_KEEP:
size = texdraw->get_size();
break;
case STRETCH_SCALE:
size = get_size();
break;
case STRETCH_TILE:
size = get_size();
_tile = true;
break;
case STRETCH_KEEP_CENTERED:
ofs = (get_size() - texdraw->get_size()) / 2;
size = texdraw->get_size();
break;
case STRETCH_KEEP_ASPECT_CENTERED:
case STRETCH_KEEP_ASPECT: {
Size2 _size = get_size();
float tex_width = texdraw->get_width() * _size.height / texdraw->get_height();
float tex_height = _size.height;
if (tex_width > _size.width) {
tex_width = _size.width;
tex_height = texdraw->get_height() * tex_width / texdraw->get_width();
}
if (stretch_mode == STRETCH_KEEP_ASPECT_CENTERED) {
ofs.x = (_size.width - tex_width) / 2;
ofs.y = (_size.height - tex_height) / 2;
}
size.width = tex_width;
size.height = tex_height;
} break;
case STRETCH_KEEP_ASPECT_COVERED: {
size = get_size();
Size2 tex_size = texdraw->get_size();
Size2 scaleSize(size.width / tex_size.width, size.height / tex_size.height);
float scale = scaleSize.width > scaleSize.height ? scaleSize.width : scaleSize.height;
Size2 scaledTexSize = tex_size * scale;
Point2 ofs = ((scaledTexSize - size) / scale).abs() / 2.0f;
_texture_region = Rect2(ofs, size / scale);
} break;
}
}
_position_rect = Rect2(ofs, size);
if (_tile)
draw_texture_rect(texdraw, _position_rect, _tile);
else
draw_texture_rect_region(texdraw, _position_rect, _texture_region);
} else {
_position_rect = Rect2();
}
if (has_focus() && focused.is_valid()) {
Rect2 drect(Point2(), get_size());
draw_texture_rect(focused, drect, false);
};
} break;
}
}
void TextureButton::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_normal_texture", "texture"), &TextureButton::set_normal_texture);
ClassDB::bind_method(D_METHOD("set_pressed_texture", "texture"), &TextureButton::set_pressed_texture);
ClassDB::bind_method(D_METHOD("set_hover_texture", "texture"), &TextureButton::set_hover_texture);
ClassDB::bind_method(D_METHOD("set_disabled_texture", "texture"), &TextureButton::set_disabled_texture);
ClassDB::bind_method(D_METHOD("set_focused_texture", "texture"), &TextureButton::set_focused_texture);
ClassDB::bind_method(D_METHOD("set_click_mask", "mask"), &TextureButton::set_click_mask);
ClassDB::bind_method(D_METHOD("set_expand", "p_expand"), &TextureButton::set_expand);
ClassDB::bind_method(D_METHOD("set_stretch_mode", "p_mode"), &TextureButton::set_stretch_mode);
ClassDB::bind_method(D_METHOD("get_normal_texture"), &TextureButton::get_normal_texture);
ClassDB::bind_method(D_METHOD("get_pressed_texture"), &TextureButton::get_pressed_texture);
ClassDB::bind_method(D_METHOD("get_hover_texture"), &TextureButton::get_hover_texture);
ClassDB::bind_method(D_METHOD("get_disabled_texture"), &TextureButton::get_disabled_texture);
ClassDB::bind_method(D_METHOD("get_focused_texture"), &TextureButton::get_focused_texture);
ClassDB::bind_method(D_METHOD("get_click_mask"), &TextureButton::get_click_mask);
ClassDB::bind_method(D_METHOD("get_expand"), &TextureButton::get_expand);
ClassDB::bind_method(D_METHOD("get_stretch_mode"), &TextureButton::get_stretch_mode);
ADD_GROUP("Textures", "texture_");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_normal", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_normal_texture", "get_normal_texture");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_pressed", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_pressed_texture", "get_pressed_texture");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_hover", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_hover_texture", "get_hover_texture");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_disabled", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_disabled_texture", "get_disabled_texture");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_focused", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_focused_texture", "get_focused_texture");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_click_mask", PROPERTY_HINT_RESOURCE_TYPE, "BitMap"), "set_click_mask", "get_click_mask");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "expand", PROPERTY_HINT_RESOURCE_TYPE, "bool"), "set_expand", "get_expand");
ADD_PROPERTY(PropertyInfo(Variant::INT, "stretch_mode", PROPERTY_HINT_ENUM, "Scale,Tile,Keep,Keep Centered,Keep Aspect,Keep Aspect Centered,Keep Aspect Covered"), "set_stretch_mode", "get_stretch_mode");
BIND_ENUM_CONSTANT(STRETCH_SCALE);
BIND_ENUM_CONSTANT(STRETCH_TILE);
BIND_ENUM_CONSTANT(STRETCH_KEEP);
BIND_ENUM_CONSTANT(STRETCH_KEEP_CENTERED);
BIND_ENUM_CONSTANT(STRETCH_KEEP_ASPECT);
BIND_ENUM_CONSTANT(STRETCH_KEEP_ASPECT_CENTERED);
BIND_ENUM_CONSTANT(STRETCH_KEEP_ASPECT_COVERED);
}
void TextureButton::set_normal_texture(const Ref<Texture> &p_normal) {
normal = p_normal;
update();
minimum_size_changed();
}
void TextureButton::set_pressed_texture(const Ref<Texture> &p_pressed) {
pressed = p_pressed;
update();
}
void TextureButton::set_hover_texture(const Ref<Texture> &p_hover) {
hover = p_hover;
update();
}
void TextureButton::set_disabled_texture(const Ref<Texture> &p_disabled) {
disabled = p_disabled;
update();
}
void TextureButton::set_click_mask(const Ref<BitMap> &p_click_mask) {
click_mask = p_click_mask;
update();
}
Ref<Texture> TextureButton::get_normal_texture() const {
return normal;
}
Ref<Texture> TextureButton::get_pressed_texture() const {
return pressed;
}
Ref<Texture> TextureButton::get_hover_texture() const {
return hover;
}
Ref<Texture> TextureButton::get_disabled_texture() const {
return disabled;
}
Ref<BitMap> TextureButton::get_click_mask() const {
return click_mask;
}
Ref<Texture> TextureButton::get_focused_texture() const {
return focused;
};
void TextureButton::set_focused_texture(const Ref<Texture> &p_focused) {
focused = p_focused;
};
bool TextureButton::get_expand() const {
return expand;
}
void TextureButton::set_expand(bool p_expand) {
expand = p_expand;
minimum_size_changed();
update();
}
void TextureButton::set_stretch_mode(StretchMode p_stretch_mode) {
stretch_mode = p_stretch_mode;
update();
}
TextureButton::StretchMode TextureButton::get_stretch_mode() const {
return stretch_mode;
}
TextureButton::TextureButton() {
expand = false;
stretch_mode = STRETCH_SCALE;
_texture_region = Rect2();
_position_rect = Rect2();
_tile = false;
}
<|endoftext|> |
<commit_before>/*
* editdlg.cpp - dialogue to create or modify an alarm message
* Program: kalarm
* (C) 2001 by David Jarvie software@astrojar.org.uk
*
* 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 "kalarm.h"
#include <qlayout.h>
#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <qbuttongroup.h>
#include <qmultilinedit.h>
#include <qlabel.h>
#include <qmsgbox.h>
#include <qvalidator.h>
#include <qwhatsthis.h>
#include <kglobal.h>
#include <klocale.h>
#include <kconfig.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include "kalarmapp.h"
#include "prefsettings.h"
#include "editdlg.h"
#include "editdlg.moc"
EditAlarmDlg::EditAlarmDlg(const QString& caption, QWidget* parent, const char* name, const MessageEvent* event)
: KDialogBase(parent, name, true, caption, Ok|Cancel, Ok, true)
{
QWidget* page = new QWidget(this);
setMainWidget(page);
QVBoxLayout* topLayout = new QVBoxLayout(page, marginHint(), spacingHint());
// Message label + multi-line editor
QLabel* lbl = new QLabel(page);
lbl->setText(i18n("Message:"));
lbl->setFixedSize(lbl->sizeHint());
topLayout->addWidget(lbl, 0, AlignLeft);
topLayout->addSpacing(fontMetrics().lineSpacing()/2 - spacingHint());
messageEdit = new QMultiLineEdit(page);
QSize size = messageEdit->sizeHint();
messageEdit->setMinimumWidth(size.width());
#warning FIXME QMultiLineEdit::setFixedVisibleLines()
//messageEdit->setFixedVisibleLines(4);
topLayout->addWidget(messageEdit, 6);
QWhatsThis::add(messageEdit,
i18n("Enter the text of the alarm message.\n"
"It may be multi-line."));
// Date label
QGridLayout* grid = new QGridLayout(1, 4);
topLayout->addLayout(grid);
lbl = new QLabel(page);
lbl->setText(i18n("Date:"));
lbl->setFixedSize(lbl->sizeHint());
grid->addWidget(lbl, 0, 0, AlignLeft);
// Date spin box
dateEdit = new DateSpinBox(page);
size = dateEdit->sizeHint();
dateEdit->setFixedSize(size);
grid->addWidget(dateEdit, 0, 1, AlignLeft);
QWhatsThis::add(dateEdit, i18n("Enter the date to schedule the alarm message."));
// Time label
lbl = new QLabel(page);
lbl->setText(i18n("Time:"));
lbl->setFixedSize(lbl->sizeHint());
grid->addWidget(lbl, 0, 2, AlignRight);
// Time spin box
timeEdit = new TimeSpinBox(page);
timeEdit->setValue(2399);
size = timeEdit->sizeHint();
timeEdit->setFixedSize(size);
timeEdit->setWrapping(true);
grid->addWidget(timeEdit, 0, 3, AlignRight);
QWhatsThis::add(timeEdit, i18n("Enter the time to schedule the alarm message."));
// Late display checkbox - default = allow late display
grid = new QGridLayout(1, 2);
topLayout->addLayout(grid);
lateCancel = new QCheckBox(page);
lateCancel->setText(i18n("Cancel if late"));
lateCancel->setFixedSize(lateCancel->sizeHint());
lateCancel->setChecked(false);
grid->addWidget(lateCancel, 0, 0, AlignLeft);
QWhatsThis::add(lateCancel,
i18n("If checked, the message will be cancelled if it\n"
"cannot be displayed within 1 minute of the specified\n"
"time. Possible reasons for non-display include your\n"
"being logged off, X not running, or the alarm daemon\n"
"not running.\n\n"
"If unchecked, the message will be displayed at the\n"
"first opportunity after the specified time, regardless\n"
"of how late it is."));
// Beep checkbox - default = no beep
beep = new QCheckBox(page);
beep->setText(i18n("Beep"));
beep->setFixedSize(beep->sizeHint());
beep->setChecked(false);
grid->addWidget(beep, 0, 1, AlignLeft);
QWhatsThis::add(beep,
i18n("If checked, a beep will sound when the message is\n"
"displayed."));
#ifdef SELECT_FONT
// Font and colour choice drop-down list
fontColour = new FontColourChooser(page, 0L, false, QStringList(), true, i18n("Font and background colour"), false);
size = fontColour->sizeHint();
fontColour->setMinimumHeight(size.height() + 4);
topLayout->addWidget(fontColour, 6);
QWhatsThis::add(fontColour,
i18n("Choose the font and background colour for the alarm message."));
#else
// Colour choice drop-down list
bgColourChoose = new ColourCombo(page);
size = bgColourChoose->sizeHint();
bgColourChoose->setMinimumHeight(size.height() + 4);
topLayout->addWidget(bgColourChoose, 6);
QWhatsThis::add(bgColourChoose,
i18n("Choose the background colour for the alarm message."));
#endif
setButtonText(Ok, i18n("&Set Alarm"));
setButtonWhatsThis(Ok, i18n("Schedule the message for display at the specified time."));
topLayout->activate();
KConfig* config = KGlobal::config();
config->setGroup(QString::fromLatin1("EditDialog"));
size = minimumSize();
QWidget* desktop = KApplication::desktop();
size.setWidth(config->readNumEntry(QString::fromLatin1("Width %1").arg(desktop->width()), size.width()));
size.setHeight(config->readNumEntry(QString::fromLatin1("Height %1").arg(desktop->height()), size.height()));
resize(size);
// Set up initial values
if (event)
{
messageEdit->insertLine(event->message());
timeEdit->setValue(event->time().hour()*60 + event->time().minute());
dateEdit->setDate(event->date());
lateCancel->setChecked(event->lateCancel());
beep->setChecked(event->beep());
#ifdef SELECT_FONT
fontColour->setColour(event->colour());
fontColour->setFont(?);
#else
bgColourChoose->setColour(event->colour());
#endif
}
else
{
QDateTime now = QDateTime::currentDateTime();
timeEdit->setValue(now.time().hour()*60 + now.time().minute());
dateEdit->setDate(now.date());
#ifdef SELECT_FONT
fontColour->setColour(theApp()->generalSettings()->defaultBgColour());
fontColour->setFont(theApp()->generalSettings()->messageFont());
#else
bgColourChoose->setColour(theApp()->generalSettings()->defaultBgColour());
#endif
}
messageEdit->setFocus();
}
EditAlarmDlg::~EditAlarmDlg()
{
}
/******************************************************************************
* Get the currently entered message data.
* The data is returned in the supplied Event instance.
*/
void EditAlarmDlg::getEvent(MessageEvent& event)
{
int flags = (lateCancel->isChecked() ? MessageEvent::LATE_CANCEL : 0)
| (beep->isChecked() ? MessageEvent::BEEP : 0);
event.set(alarmDateTime, flags, bgColourChoose->color(), alarmMessage);
}
/******************************************************************************
* Called when the window's size has changed (before it is painted).
* Sets the last column in the list view to extend at least to the right
* hand edge of the list view.
*/
void EditAlarmDlg::resizeEvent(QResizeEvent* re)
{
KConfig* config = KGlobal::config();
config->setGroup(QString::fromLatin1("EditDialog"));
config->writeEntry("Size", re->size());
QWidget* desktop = KApplication::desktop();
config->writeEntry(QString::fromLatin1("Width %1").arg(desktop->width()), re->size().width());
config->writeEntry(QString::fromLatin1("Height %1").arg(desktop->height()), re->size().height());
KDialog::resizeEvent(re);
}
void EditAlarmDlg::slotOk()
{
alarmDateTime.setTime(QTime(timeEdit->value()/60, timeEdit->value()%60));
alarmDateTime.setDate(dateEdit->getDate());
if (alarmDateTime < QDateTime::currentDateTime())
KMessageBox::sorry(this, i18n("Message time has already expired"));
else
{
alarmMessage = messageEdit->text();
alarmMessage.stripWhiteSpace();
if (alarmMessage.isEmpty())
alarmMessage = "Alarm";
accept();
}
}
void EditAlarmDlg::slotCancel()
{
reject();
}
//=============================================================================
class TimeSpinBox::TimeValidator : public QValidator
{
public:
TimeValidator(QWidget* parent, const char* name = 0L) : QValidator(parent, name) { }
virtual State validate(QString&, int&) const;
};
/******************************************************************************
* Validate the time spin box input.
* The entered time must contain a colon, but hours and/or minutes may be blank.
*/
QValidator::State TimeSpinBox::TimeValidator::validate(QString& text, int& /*cursorPos*/) const
{
QValidator::State state = QValidator::Acceptable;
QString hour;
int colon = text.find(':');
if (colon >= 0)
{
QString minute = text.mid(colon + 1).stripWhiteSpace();
if (minute.isEmpty())
state = QValidator::Intermediate;
else
{
bool ok;
if (minute.toUInt(&ok) >= 60 || !ok)
return QValidator::Invalid;
}
hour = text.left(colon).stripWhiteSpace();
}
else
{
state = QValidator::Intermediate;
hour = text;
}
if (hour.isEmpty())
return QValidator::Intermediate;
bool ok;
if (hour.toUInt(&ok) >= 24 || !ok)
return QValidator::Invalid;
return state;
}
TimeSpinBox::TimeSpinBox(QWidget* parent, const char* name)
: QSpinBox(0, 1439, 1, parent, name)
{
validator = new TimeValidator(this, "TimeSpinBox validator");
setValidator(validator);
}
QString TimeSpinBox::mapValueToText(int v)
{
QString s;
s.sprintf("%02d:%02d", v/60, v%60);
return s;
}
/******************************************************************************
* Convert the user-entered text to a value in minutes.
* The allowed format is [hour]:[minute], where hour and
* minute must be non-blank.
*/
int TimeSpinBox::mapTextToValue(bool* ok)
{
QString text = cleanText();
int colon = text.find(':');
if (colon >= 0)
{
QString hour = text.left(colon).stripWhiteSpace();
QString minute = text.mid(colon + 1).stripWhiteSpace();
if (!hour.isEmpty() && !minute.isEmpty())
{
bool okhour, okmin;
int h = hour.toUInt(&okhour);
int m = minute.toUInt(&okmin);
if (okhour && okmin && h < 24 && m < 60)
{
*ok = true;
return h * 60 + m;
}
}
}
*ok = false;
return 0;
}
QDate DateSpinBox::baseDate(2000, 1, 1);
DateSpinBox::DateSpinBox(QWidget* parent, const char* name)
: QSpinBox(0, 0, 1, parent, name)
{
QDate now = QDate::currentDate();
QDate maxDate(now.year() + 100, 12, 31);
setRange(0, baseDate.daysTo(maxDate));
}
QDate DateSpinBox::getDate()
{
return baseDate.addDays(value());
}
void DateSpinBox::setDate(const QDate& date)
{
setValue(baseDate.daysTo(date));
}
QString DateSpinBox::mapValueToText(int v)
{
QDate date = baseDate.addDays(v);
return KGlobal::locale()->formatDate(date, true);
}
/*
* Convert the user-entered text to a value in days.
* The date must be in the range
*/
int DateSpinBox::mapTextToValue(bool* ok)
{
QDate date = KGlobal::locale()->readDate(cleanText());
int days = baseDate.daysTo(date);
int minval = baseDate.daysTo(QDate::currentDate());
if (days >= minval && days <= maxValue())
{
*ok = true;
return days;
}
*ok = false;
return 0;
}
<commit_msg>*** empty log message ***<commit_after>/*
* editdlg.cpp - dialogue to create or modify an alarm message
* Program: kalarm
* (C) 2001 by David Jarvie software@astrojar.org.uk
*
* 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 "kalarm.h"
#include <qlayout.h>
#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <qbuttongroup.h>
#include <qmultilinedit.h>
#include <qlabel.h>
#include <qmsgbox.h>
#include <qvalidator.h>
#include <qwhatsthis.h>
#include <kglobal.h>
#include <klocale.h>
#include <kconfig.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include "kalarmapp.h"
#include "prefsettings.h"
#include "editdlg.h"
#include "editdlg.moc"
EditAlarmDlg::EditAlarmDlg(const QString& caption, QWidget* parent, const char* name, const MessageEvent* event)
: KDialogBase(parent, name, true, caption, Ok|Cancel, Ok, true)
{
QWidget* page = new QWidget(this);
setMainWidget(page);
QVBoxLayout* topLayout = new QVBoxLayout(page, marginHint(), spacingHint());
// Message label + multi-line editor
QLabel* lbl = new QLabel(page);
lbl->setText(i18n("Message:"));
lbl->setFixedSize(lbl->sizeHint());
topLayout->addWidget(lbl, 0, AlignLeft);
topLayout->addSpacing(fontMetrics().lineSpacing()/2 - spacingHint());
messageEdit = new QMultiLineEdit(page);
QSize size = messageEdit->sizeHint();
size.setHeight(messageEdit->fontMetrics().lineSpacing()*13/4 + 2*messageEdit->frameWidth());
messageEdit->setMinimumSize(size);
topLayout->addWidget(messageEdit, 6);
QWhatsThis::add(messageEdit,
i18n("Enter the text of the alarm message.\n"
"It may be multi-line."));
// Date label
QGridLayout* grid = new QGridLayout(1, 4);
topLayout->addLayout(grid);
lbl = new QLabel(page);
lbl->setText(i18n("Date:"));
lbl->setFixedSize(lbl->sizeHint());
grid->addWidget(lbl, 0, 0, AlignLeft);
// Date spin box
dateEdit = new DateSpinBox(page);
size = dateEdit->sizeHint();
dateEdit->setFixedSize(size);
grid->addWidget(dateEdit, 0, 1, AlignLeft);
QWhatsThis::add(dateEdit, i18n("Enter the date to schedule the alarm message."));
// Time label
lbl = new QLabel(page);
lbl->setText(i18n("Time:"));
lbl->setFixedSize(lbl->sizeHint());
grid->addWidget(lbl, 0, 2, AlignRight);
// Time spin box
timeEdit = new TimeSpinBox(page);
timeEdit->setValue(2399);
size = timeEdit->sizeHint();
timeEdit->setFixedSize(size);
timeEdit->setWrapping(true);
grid->addWidget(timeEdit, 0, 3, AlignRight);
QWhatsThis::add(timeEdit, i18n("Enter the time to schedule the alarm message."));
// Late display checkbox - default = allow late display
grid = new QGridLayout(1, 2);
topLayout->addLayout(grid);
lateCancel = new QCheckBox(page);
lateCancel->setText(i18n("Cancel if late"));
lateCancel->setFixedSize(lateCancel->sizeHint());
lateCancel->setChecked(false);
grid->addWidget(lateCancel, 0, 0, AlignLeft);
QWhatsThis::add(lateCancel,
i18n("If checked, the message will be cancelled if it\n"
"cannot be displayed within 1 minute of the specified\n"
"time. Possible reasons for non-display include your\n"
"being logged off, X not running, or the alarm daemon\n"
"not running.\n\n"
"If unchecked, the message will be displayed at the\n"
"first opportunity after the specified time, regardless\n"
"of how late it is."));
// Beep checkbox - default = no beep
beep = new QCheckBox(page);
beep->setText(i18n("Beep"));
beep->setFixedSize(beep->sizeHint());
beep->setChecked(false);
grid->addWidget(beep, 0, 1, AlignLeft);
QWhatsThis::add(beep,
i18n("If checked, a beep will sound when the message is\n"
"displayed."));
#ifdef SELECT_FONT
// Font and colour choice drop-down list
fontColour = new FontColourChooser(page, 0L, false, QStringList(), true, i18n("Font and background colour"), false);
size = fontColour->sizeHint();
fontColour->setMinimumHeight(size.height() + 4);
topLayout->addWidget(fontColour, 6);
QWhatsThis::add(fontColour,
i18n("Choose the font and background colour for the alarm message."));
#else
// Colour choice drop-down list
bgColourChoose = new ColourCombo(page);
size = bgColourChoose->sizeHint();
bgColourChoose->setMinimumHeight(size.height() + 4);
topLayout->addWidget(bgColourChoose, 6);
QWhatsThis::add(bgColourChoose,
i18n("Choose the background colour for the alarm message."));
#endif
setButtonText(Ok, i18n("&Set Alarm"));
setButtonWhatsThis(Ok, i18n("Schedule the message for display at the specified time."));
topLayout->activate();
KConfig* config = KGlobal::config();
config->setGroup(QString::fromLatin1("EditDialog"));
size = minimumSize();
QWidget* desktop = KApplication::desktop();
size.setWidth(config->readNumEntry(QString::fromLatin1("Width %1").arg(desktop->width()), size.width()));
size.setHeight(config->readNumEntry(QString::fromLatin1("Height %1").arg(desktop->height()), size.height()));
resize(size);
// Set up initial values
if (event)
{
messageEdit->insertLine(event->message());
timeEdit->setValue(event->time().hour()*60 + event->time().minute());
dateEdit->setDate(event->date());
lateCancel->setChecked(event->lateCancel());
beep->setChecked(event->beep());
#ifdef SELECT_FONT
fontColour->setColour(event->colour());
fontColour->setFont(?);
#else
bgColourChoose->setColour(event->colour());
#endif
}
else
{
QDateTime now = QDateTime::currentDateTime();
timeEdit->setValue(now.time().hour()*60 + now.time().minute());
dateEdit->setDate(now.date());
#ifdef SELECT_FONT
fontColour->setColour(theApp()->generalSettings()->defaultBgColour());
fontColour->setFont(theApp()->generalSettings()->messageFont());
#else
bgColourChoose->setColour(theApp()->generalSettings()->defaultBgColour());
#endif
}
messageEdit->setFocus();
}
EditAlarmDlg::~EditAlarmDlg()
{
}
/******************************************************************************
* Get the currently entered message data.
* The data is returned in the supplied Event instance.
*/
void EditAlarmDlg::getEvent(MessageEvent& event)
{
int flags = (lateCancel->isChecked() ? MessageEvent::LATE_CANCEL : 0)
| (beep->isChecked() ? MessageEvent::BEEP : 0);
event.set(alarmDateTime, flags, bgColourChoose->color(), alarmMessage);
}
/******************************************************************************
* Called when the window's size has changed (before it is painted).
* Sets the last column in the list view to extend at least to the right
* hand edge of the list view.
*/
void EditAlarmDlg::resizeEvent(QResizeEvent* re)
{
KConfig* config = KGlobal::config();
config->setGroup(QString::fromLatin1("EditDialog"));
config->writeEntry("Size", re->size());
QWidget* desktop = KApplication::desktop();
config->writeEntry(QString::fromLatin1("Width %1").arg(desktop->width()), re->size().width());
config->writeEntry(QString::fromLatin1("Height %1").arg(desktop->height()), re->size().height());
KDialog::resizeEvent(re);
}
void EditAlarmDlg::slotOk()
{
alarmDateTime.setTime(QTime(timeEdit->value()/60, timeEdit->value()%60));
alarmDateTime.setDate(dateEdit->getDate());
if (alarmDateTime < QDateTime::currentDateTime())
KMessageBox::sorry(this, i18n("Message time has already expired"));
else
{
alarmMessage = messageEdit->text();
alarmMessage.stripWhiteSpace();
if (alarmMessage.isEmpty())
alarmMessage = "Alarm";
accept();
}
}
void EditAlarmDlg::slotCancel()
{
reject();
}
//=============================================================================
class TimeSpinBox::TimeValidator : public QValidator
{
public:
TimeValidator(QWidget* parent, const char* name = 0L) : QValidator(parent, name) { }
virtual State validate(QString&, int&) const;
};
/******************************************************************************
* Validate the time spin box input.
* The entered time must contain a colon, but hours and/or minutes may be blank.
*/
QValidator::State TimeSpinBox::TimeValidator::validate(QString& text, int& /*cursorPos*/) const
{
QValidator::State state = QValidator::Acceptable;
QString hour;
int colon = text.find(':');
if (colon >= 0)
{
QString minute = text.mid(colon + 1).stripWhiteSpace();
if (minute.isEmpty())
state = QValidator::Intermediate;
else
{
bool ok;
if (minute.toUInt(&ok) >= 60 || !ok)
return QValidator::Invalid;
}
hour = text.left(colon).stripWhiteSpace();
}
else
{
state = QValidator::Intermediate;
hour = text;
}
if (hour.isEmpty())
return QValidator::Intermediate;
bool ok;
if (hour.toUInt(&ok) >= 24 || !ok)
return QValidator::Invalid;
return state;
}
TimeSpinBox::TimeSpinBox(QWidget* parent, const char* name)
: QSpinBox(0, 1439, 1, parent, name)
{
validator = new TimeValidator(this, "TimeSpinBox validator");
setValidator(validator);
}
QString TimeSpinBox::mapValueToText(int v)
{
QString s;
s.sprintf("%02d:%02d", v/60, v%60);
return s;
}
/******************************************************************************
* Convert the user-entered text to a value in minutes.
* The allowed format is [hour]:[minute], where hour and
* minute must be non-blank.
*/
int TimeSpinBox::mapTextToValue(bool* ok)
{
QString text = cleanText();
int colon = text.find(':');
if (colon >= 0)
{
QString hour = text.left(colon).stripWhiteSpace();
QString minute = text.mid(colon + 1).stripWhiteSpace();
if (!hour.isEmpty() && !minute.isEmpty())
{
bool okhour, okmin;
int h = hour.toUInt(&okhour);
int m = minute.toUInt(&okmin);
if (okhour && okmin && h < 24 && m < 60)
{
*ok = true;
return h * 60 + m;
}
}
}
*ok = false;
return 0;
}
QDate DateSpinBox::baseDate(2000, 1, 1);
DateSpinBox::DateSpinBox(QWidget* parent, const char* name)
: QSpinBox(0, 0, 1, parent, name)
{
QDate now = QDate::currentDate();
QDate maxDate(now.year() + 100, 12, 31);
setRange(0, baseDate.daysTo(maxDate));
}
QDate DateSpinBox::getDate()
{
return baseDate.addDays(value());
}
void DateSpinBox::setDate(const QDate& date)
{
setValue(baseDate.daysTo(date));
}
QString DateSpinBox::mapValueToText(int v)
{
QDate date = baseDate.addDays(v);
return KGlobal::locale()->formatDate(date, true);
}
/*
* Convert the user-entered text to a value in days.
* The date must be in the range
*/
int DateSpinBox::mapTextToValue(bool* ok)
{
QDate date = KGlobal::locale()->readDate(cleanText());
int days = baseDate.daysTo(date);
int minval = baseDate.daysTo(QDate::currentDate());
if (days >= minval && days <= maxValue())
{
*ok = true;
return days;
}
*ok = false;
return 0;
}
<|endoftext|> |
<commit_before>/*
main.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2001,2002,2004 Klar�vdalens Datakonsult AB
Kleopatra is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Kleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include <config-kleopatra.h>
#include "aboutdata.h"
#include "systemtrayicon.h"
#ifdef KLEO_BUILD_OLD_MAINWINDOW
# include "certmanager.h"
#else
# include "mainwindow.h"
# include <commands/refreshkeyscommand.h>
#endif
#include "libkleo/kleo/cryptobackendfactory.h"
#include <utils/kdpipeiodevice.h>
#include <utils/log.h>
#ifdef HAVE_USABLE_ASSUAN
# include "kleo-assuan.h"
# include <uiserver/uiserver.h>
# include <uiserver/assuancommand.h>
# include <uiserver/echocommand.h>
# include <uiserver/decryptcommand.h>
# include <uiserver/verifycommand.h>
# include <uiserver/decryptverifyfilescommand.h>
# include <uiserver/decryptfilescommand.h>
# include <uiserver/verifyfilescommand.h>
# include <uiserver/prepencryptcommand.h>
# include <uiserver/encryptcommand.h>
# include <uiserver/signcommand.h>
# include <uiserver/signencryptfilescommand.h>
#endif
#include <models/keycache.h>
#include <kcmdlineargs.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <ksplashscreen.h>
#include <KUniqueApplication>
#include <QDebug>
#include <QFile>
#include <QTextDocument> // for Qt::escape
#include <QProcess>
#include <QSystemTrayIcon>
#include <QMenu>
#include <QAction>
#include <boost/shared_ptr.hpp>
#include <cassert>
namespace {
template <typename T>
boost::shared_ptr<T> make_shared_ptr( T * t ) {
return t ? boost::shared_ptr<T>( t ) : boost::shared_ptr<T>() ;
}
}
static QString environmentVariable( const QString& var, const QString& defaultValue=QString() )
{
const QStringList env = QProcess::systemEnvironment();
Q_FOREACH ( const QString& i, env )
{
if ( !i.startsWith( var + '=' ) )
continue;
const int equalPos = i.indexOf( '=' );
assert( equalPos >= 0 );
return i.mid( equalPos + 1 );
}
return defaultValue;
}
static void setupLogging()
{
const QString envOptions = environmentVariable( "KLEOPATRA_LOGOPTIONS", "io" );
const bool logAll = envOptions.trimmed() == "all";
const QStringList options = envOptions.split( ',' );
const QString dir = environmentVariable( "KLEOPATRA_LOGDIR" );
if ( dir.isEmpty() )
return;
std::auto_ptr<QFile> logFile( new QFile( dir + "/kleo-log" ) );
if ( !logFile->open( QIODevice::WriteOnly | QIODevice::Append ) ) {
qDebug() << "Could not open file for logging: " << dir + "/kleo-log\nLogging disabled";
return;
}
Kleo::Log::mutableInstance()->setOutputDirectory( dir );
if ( logAll || options.contains( "io" ) )
Kleo::Log::mutableInstance()->setIOLoggingEnabled( true );
qInstallMsgHandler( Kleo::Log::messageHandler );
#ifdef HAVE_USABLE_ASSUAN
if ( logAll || options.contains( "pipeio" ) )
KDPipeIODevice::setDebugLevel( KDPipeIODevice::Debug );
assuan_set_assuan_log_stream( Kleo::Log::instance()->logFile() );
#endif
}
#ifndef KLEO_BUILD_OLD_MAINWINDOW
static void fillKeyCache( KSplashScreen * splash, Kleo::UiServer * server ) {
QEventLoop loop;
Kleo::RefreshKeysCommand * cmd = new Kleo::RefreshKeysCommand( 0 );
QObject::connect( cmd, SIGNAL(finished()), &loop, SLOT(quit()) );
QObject::connect( cmd, SIGNAL(finished()), server, SLOT(enableCryptoCommands()) );
splash->showMessage( i18n("Loading certificate cache...") );
cmd->start();
loop.exec();
splash->showMessage( i18n("Certificate cache loaded.") );
}
#endif
int main( int argc, char** argv )
{
AboutData aboutData;
KCmdLineArgs::init(argc, argv, &aboutData);
KCmdLineOptions options;
#ifdef KLEO_BUILD_OLD_MAINWINDOW
options.add("external", ki18n("Search for external certificates initially"));
options.add("query ", ki18n("Initial query string"));
#else
options.add("daemon", ki18n("Run UI server only, hide main window"));
#endif
options.add("import-certificate ", ki18n("Name of certificate file to import"));
#ifdef HAVE_USABLE_ASSUAN
options.add("uiserver-socket <argument>", ki18n("Location of the socket the ui server is listening on" ) );
#endif
KCmdLineArgs::addCmdLineOptions( options );
// pin KeyCache to a shared_ptr to define it's minimum lifetime:
const boost::shared_ptr<Kleo::PublicKeyCache> publicKeyCache = Kleo::PublicKeyCache::mutableInstance();
const boost::shared_ptr<Kleo::SecretKeyCache> secretKeyCache = Kleo::SecretKeyCache::mutableInstance();
const boost::shared_ptr<Kleo::Log> log = Kleo::Log::mutableInstance();
setupLogging();
KUniqueApplication app;
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
KGlobal::locale()->insertCatalog( "libkleopatra" );
KIconLoader::global()->addAppDir( "libkleopatra" );
#ifndef KLEO_BUILD_OLD_MAINWINDOW
SystemTrayIconFor<MainWindow> sysTray;
sysTray.show();
#endif
KSplashScreen splash( UserIcon( "kleopatra_splashscreen" ), Qt::WindowStaysOnTopHint );
int rc;
#ifdef HAVE_USABLE_ASSUAN
try {
Kleo::UiServer server( args->getOption("uiserver-socket") );
server.enableCryptoCommands( false );
# ifndef KLEO_BUILD_OLD_MAINWINDOW
QObject::connect( &server, SIGNAL(startKeyManagerRequested()),
&sysTray, SLOT(openOrRaiseMainWindow()) );
# endif
#define REGISTER( Command ) server.registerCommandFactory( boost::shared_ptr<Kleo::AssuanCommandFactory>( new Kleo::GenericAssuanCommandFactory<Kleo::Command> ) )
REGISTER( DecryptCommand );
REGISTER( DecryptFilesCommand );
REGISTER( DecryptVerifyFilesCommand );
REGISTER( EchoCommand );
REGISTER( EncryptCommand );
REGISTER( EncryptFilesCommand );
REGISTER( EncryptSignFilesCommand );
REGISTER( PrepEncryptCommand );
REGISTER( SignCommand );
REGISTER( SignEncryptFilesCommand );
REGISTER( SignFilesCommand );
REGISTER( VerifyCommand );
REGISTER( VerifyFilesCommand );
#undef REGISTER
server.start();
# ifndef KLEO_BUILD_OLD_MAINWINDOW
sysTray.setToolTip( i18n( "Kleopatra UI Server listening on %1", server.socketName() ) );
# endif
#endif
#ifdef KLEO_BUILD_OLD_MAINWINDOW
if( !Kleo::CryptoBackendFactory::instance()->smime() ) {
KMessageBox::error(0,
i18n( "<qt>The crypto plugin could not be initialized.<br />"
"Certificate Manager will terminate now.</qt>") );
return -2;
}
splash.show();
CertManager* manager = new CertManager( args->isSet("external"),
args->getOption("query"),
args->getOption("import-certificate") );
manager->show();
splash.finish( manager );
#else
const bool daemon = args->isSet("daemon");
if ( !daemon )
splash.show();
fillKeyCache( &splash, &server );
if ( !daemon ) {
MainWindow* mainWindow = new MainWindow;
mainWindow->show();
sysTray.setMainWindow( mainWindow );
splash.finish( mainWindow );
}
#endif
args->clear();
QApplication::setQuitOnLastWindowClosed( false );
rc = app.exec();
#ifdef HAVE_USABLE_ASSUAN
# ifndef KLEO_BUILD_OLD_MAINWINDOW
QObject::disconnect( &server, SIGNAL(startKeyManagerRequested()),
&sysTray, SLOT(openOrRaiseMainWindow()) );
#endif
server.stop();
server.waitForStopped();
} catch ( const std::exception & e ) {
QMessageBox::information( 0, i18n("GPG UI Server Error"),
i18n("<qt>The Kleopatra GPG UI Server Module couldn't be initialized.<br/>"
"The error given was: <b>%1</b><br/>"
"You can use Kleopatra as a certificate manager, but cryptographic plugins that "
"rely on a GPG UI Server being present might not work correctly, or at all.</qt>",
Qt::escape( QString::fromUtf8( e.what() ) ) ));
rc = app.exec();
}
#endif
return rc;
}
<commit_msg>Do not break compile with error message /home/kde-devel/kde/src/kdepim/kleopatra/main.cpp:139: error: ‘Kleo::UiServer’ has not been declared<commit_after>/*
main.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2001,2002,2004 Klar�vdalens Datakonsult AB
Kleopatra is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Kleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include <config-kleopatra.h>
#include "aboutdata.h"
#include "systemtrayicon.h"
#ifdef KLEO_BUILD_OLD_MAINWINDOW
# include "certmanager.h"
#else
# include "mainwindow.h"
# include <commands/refreshkeyscommand.h>
#endif
#include "libkleo/kleo/cryptobackendfactory.h"
#include <utils/kdpipeiodevice.h>
#include <utils/log.h>
#ifdef HAVE_USABLE_ASSUAN
# include "kleo-assuan.h"
# include <uiserver/uiserver.h>
# include <uiserver/assuancommand.h>
# include <uiserver/echocommand.h>
# include <uiserver/decryptcommand.h>
# include <uiserver/verifycommand.h>
# include <uiserver/decryptverifyfilescommand.h>
# include <uiserver/decryptfilescommand.h>
# include <uiserver/verifyfilescommand.h>
# include <uiserver/prepencryptcommand.h>
# include <uiserver/encryptcommand.h>
# include <uiserver/signcommand.h>
# include <uiserver/signencryptfilescommand.h>
#endif
#include <models/keycache.h>
#include <kcmdlineargs.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <ksplashscreen.h>
#include <KUniqueApplication>
#include <QDebug>
#include <QFile>
#include <QTextDocument> // for Qt::escape
#include <QProcess>
#include <QSystemTrayIcon>
#include <QMenu>
#include <QAction>
#include <boost/shared_ptr.hpp>
#include <cassert>
namespace {
template <typename T>
boost::shared_ptr<T> make_shared_ptr( T * t ) {
return t ? boost::shared_ptr<T>( t ) : boost::shared_ptr<T>() ;
}
}
static QString environmentVariable( const QString& var, const QString& defaultValue=QString() )
{
const QStringList env = QProcess::systemEnvironment();
Q_FOREACH ( const QString& i, env )
{
if ( !i.startsWith( var + '=' ) )
continue;
const int equalPos = i.indexOf( '=' );
assert( equalPos >= 0 );
return i.mid( equalPos + 1 );
}
return defaultValue;
}
static void setupLogging()
{
const QString envOptions = environmentVariable( "KLEOPATRA_LOGOPTIONS", "io" );
const bool logAll = envOptions.trimmed() == "all";
const QStringList options = envOptions.split( ',' );
const QString dir = environmentVariable( "KLEOPATRA_LOGDIR" );
if ( dir.isEmpty() )
return;
std::auto_ptr<QFile> logFile( new QFile( dir + "/kleo-log" ) );
if ( !logFile->open( QIODevice::WriteOnly | QIODevice::Append ) ) {
qDebug() << "Could not open file for logging: " << dir + "/kleo-log\nLogging disabled";
return;
}
Kleo::Log::mutableInstance()->setOutputDirectory( dir );
if ( logAll || options.contains( "io" ) )
Kleo::Log::mutableInstance()->setIOLoggingEnabled( true );
qInstallMsgHandler( Kleo::Log::messageHandler );
#ifdef HAVE_USABLE_ASSUAN
if ( logAll || options.contains( "pipeio" ) )
KDPipeIODevice::setDebugLevel( KDPipeIODevice::Debug );
assuan_set_assuan_log_stream( Kleo::Log::instance()->logFile() );
#endif
}
#ifndef KLEO_BUILD_OLD_MAINWINDOW
#include <uiserver/uiserver.h>
static void fillKeyCache( KSplashScreen * splash, Kleo::UiServer * server ) {
QEventLoop loop;
Kleo::RefreshKeysCommand * cmd = new Kleo::RefreshKeysCommand( 0 );
QObject::connect( cmd, SIGNAL(finished()), &loop, SLOT(quit()) );
QObject::connect( cmd, SIGNAL(finished()), server, SLOT(enableCryptoCommands()) );
splash->showMessage( i18n("Loading certificate cache...") );
cmd->start();
loop.exec();
splash->showMessage( i18n("Certificate cache loaded.") );
}
#endif
int main( int argc, char** argv )
{
AboutData aboutData;
KCmdLineArgs::init(argc, argv, &aboutData);
KCmdLineOptions options;
#ifdef KLEO_BUILD_OLD_MAINWINDOW
options.add("external", ki18n("Search for external certificates initially"));
options.add("query ", ki18n("Initial query string"));
#else
options.add("daemon", ki18n("Run UI server only, hide main window"));
#endif
options.add("import-certificate ", ki18n("Name of certificate file to import"));
#ifdef HAVE_USABLE_ASSUAN
options.add("uiserver-socket <argument>", ki18n("Location of the socket the ui server is listening on" ) );
#endif
KCmdLineArgs::addCmdLineOptions( options );
// pin KeyCache to a shared_ptr to define it's minimum lifetime:
const boost::shared_ptr<Kleo::PublicKeyCache> publicKeyCache = Kleo::PublicKeyCache::mutableInstance();
const boost::shared_ptr<Kleo::SecretKeyCache> secretKeyCache = Kleo::SecretKeyCache::mutableInstance();
const boost::shared_ptr<Kleo::Log> log = Kleo::Log::mutableInstance();
setupLogging();
KUniqueApplication app;
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
KGlobal::locale()->insertCatalog( "libkleopatra" );
KIconLoader::global()->addAppDir( "libkleopatra" );
#ifndef KLEO_BUILD_OLD_MAINWINDOW
SystemTrayIconFor<MainWindow> sysTray;
sysTray.show();
#endif
KSplashScreen splash( UserIcon( "kleopatra_splashscreen" ), Qt::WindowStaysOnTopHint );
int rc;
#ifdef HAVE_USABLE_ASSUAN
try {
Kleo::UiServer server( args->getOption("uiserver-socket") );
server.enableCryptoCommands( false );
# ifndef KLEO_BUILD_OLD_MAINWINDOW
QObject::connect( &server, SIGNAL(startKeyManagerRequested()),
&sysTray, SLOT(openOrRaiseMainWindow()) );
# endif
#define REGISTER( Command ) server.registerCommandFactory( boost::shared_ptr<Kleo::AssuanCommandFactory>( new Kleo::GenericAssuanCommandFactory<Kleo::Command> ) )
REGISTER( DecryptCommand );
REGISTER( DecryptFilesCommand );
REGISTER( DecryptVerifyFilesCommand );
REGISTER( EchoCommand );
REGISTER( EncryptCommand );
REGISTER( EncryptFilesCommand );
REGISTER( EncryptSignFilesCommand );
REGISTER( PrepEncryptCommand );
REGISTER( SignCommand );
REGISTER( SignEncryptFilesCommand );
REGISTER( SignFilesCommand );
REGISTER( VerifyCommand );
REGISTER( VerifyFilesCommand );
#undef REGISTER
server.start();
# ifndef KLEO_BUILD_OLD_MAINWINDOW
sysTray.setToolTip( i18n( "Kleopatra UI Server listening on %1", server.socketName() ) );
# endif
#endif
#ifdef KLEO_BUILD_OLD_MAINWINDOW
if( !Kleo::CryptoBackendFactory::instance()->smime() ) {
KMessageBox::error(0,
i18n( "<qt>The crypto plugin could not be initialized.<br />"
"Certificate Manager will terminate now.</qt>") );
return -2;
}
splash.show();
CertManager* manager = new CertManager( args->isSet("external"),
args->getOption("query"),
args->getOption("import-certificate") );
manager->show();
splash.finish( manager );
#else
const bool daemon = args->isSet("daemon");
if ( !daemon )
splash.show();
fillKeyCache( &splash, &server );
if ( !daemon ) {
MainWindow* mainWindow = new MainWindow;
mainWindow->show();
sysTray.setMainWindow( mainWindow );
splash.finish( mainWindow );
}
#endif
args->clear();
QApplication::setQuitOnLastWindowClosed( false );
rc = app.exec();
#ifdef HAVE_USABLE_ASSUAN
# ifndef KLEO_BUILD_OLD_MAINWINDOW
QObject::disconnect( &server, SIGNAL(startKeyManagerRequested()),
&sysTray, SLOT(openOrRaiseMainWindow()) );
#endif
server.stop();
server.waitForStopped();
} catch ( const std::exception & e ) {
QMessageBox::information( 0, i18n("GPG UI Server Error"),
i18n("<qt>The Kleopatra GPG UI Server Module couldn't be initialized.<br/>"
"The error given was: <b>%1</b><br/>"
"You can use Kleopatra as a certificate manager, but cryptographic plugins that "
"rely on a GPG UI Server being present might not work correctly, or at all.</qt>",
Qt::escape( QString::fromUtf8( e.what() ) ) ));
rc = app.exec();
}
#endif
return rc;
}
<|endoftext|> |
<commit_before>/* -*- c++ -*-
callback.cpp
This file is used by KMail's plugin interface.
Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>
KMail 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.
KMail is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "callback.h"
#include "kmkernel.h"
#include "kmmessage.h"
#include <libemailfunctions/email.h>
#include <libkpimidentities/identity.h>
#include <libkpimidentities/identitymanager.h>
#include "kmmainwin.h"
#include "kmcomposewin.h"
#include <mimelib/enum.h>
#include <kinputdialog.h>
#include <klocale.h>
#include <kdebug.h>
using namespace KMail;
Callback::Callback( KMMessage* msg ) : mMsg( msg ), mReceiverSet( false )
{
}
bool Callback::mailICal( const QString& to, const QString iCal,
const QString& subject ) const
{
kdDebug(5006) << "Mailing message:\n" << iCal << endl;
KMMessage *msg = new KMMessage;
msg->initHeader();
msg->setHeaderField( "Content-Type",
"text/calendar; method=reply; charset=\"utf-8\"" );
msg->setSubject( subject );
msg->setTo( to );
msg->setBody( iCal.utf8() );
msg->setFrom( receiver() );
/* We want the triggering mail to be moved to the trash once this one
* has been sent successfully. Set a link header which accomplishes that. */
msg->link( mMsg, KMMsgStatusDeleted );
// Outlook will only understand the reply if the From: header is the
// same as the To: header of the invitation message.
KConfigGroup options( KMKernel::config(), "Groupware" );
if( !options.readBoolEntry( "LegacyMangleFromToHeaders", true ) ) {
// Try and match the receiver with an identity
const KPIM::Identity& identity =
kmkernel->identityManager()->identityForAddress( receiver() );
if( identity != KPIM::Identity::null )
// Identity found. Use this
msg->setFrom( identity.fullEmailAddr() );
msg->setHeaderField("X-KMail-Identity", QString::number( identity.uoid() ));
}
KMComposeWin *cWin = new KMComposeWin(msg);
// cWin->setCharset( "", true );
cWin->slotWordWrapToggled( false );
// TODO: These are no longer available. It was an internal
// implementation detail of kmcomposewin, anyway. Please find
// another way...
//cWin->mNeverSign = true;
//cWin->mNeverEncrypt = true;
if ( options.readBoolEntry( "AutomaticSending", true ) ) {
cWin->setAutoDeleteWindow( true );
cWin->slotSendNow();
} else {
cWin->show();
}
return true;
}
QString Callback::receiver() const
{
if ( mReceiverSet )
// Already figured this out
return mReceiver;
mReceiverSet = true;
QStringList addrs = KPIM::splitEmailAddrList( mMsg->to() );
if( addrs.count() < 2 )
// Only one receiver, so that has to be us
mReceiver = mMsg->to();
else {
int found = 0;
for( QStringList::Iterator it = addrs.begin(); it != addrs.end(); ++it ) {
if( kmkernel->identityManager()->identityForAddress( *it ) !=
KPIM::Identity::null ) {
// Ok, this could be us
++found;
mReceiver = *it;
}
}
if( found != 1 ) {
bool ok;
mReceiver =
KInputDialog::getItem( i18n( "Select Address" ),
i18n( "<qt>None of your identities match the "
"receiver of this message,<br>please "
"choose which of the following addresses "
"is yours:" ),
addrs, 0, FALSE, &ok, kmkernel->mainWin() );
if( !ok )
mReceiver = QString::null;
}
}
return mReceiver;
}
<commit_msg>Strip BCC from identity for invitation mails.<commit_after>/* -*- c++ -*-
callback.cpp
This file is used by KMail's plugin interface.
Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>
KMail 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.
KMail is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "callback.h"
#include "kmkernel.h"
#include "kmmessage.h"
#include <libemailfunctions/email.h>
#include <libkpimidentities/identity.h>
#include <libkpimidentities/identitymanager.h>
#include "kmmainwin.h"
#include "kmcomposewin.h"
#include <mimelib/enum.h>
#include <kinputdialog.h>
#include <klocale.h>
#include <kdebug.h>
using namespace KMail;
Callback::Callback( KMMessage* msg ) : mMsg( msg ), mReceiverSet( false )
{
}
bool Callback::mailICal( const QString& to, const QString iCal,
const QString& subject ) const
{
kdDebug(5006) << "Mailing message:\n" << iCal << endl;
KMMessage *msg = new KMMessage;
msg->initHeader();
msg->setHeaderField( "Content-Type",
"text/calendar; method=reply; charset=\"utf-8\"" );
msg->setSubject( subject );
msg->setTo( to );
msg->setBody( iCal.utf8() );
msg->setFrom( receiver() );
/* We want the triggering mail to be moved to the trash once this one
* has been sent successfully. Set a link header which accomplishes that. */
msg->link( mMsg, KMMsgStatusDeleted );
// Outlook will only understand the reply if the From: header is the
// same as the To: header of the invitation message.
KConfigGroup options( KMKernel::config(), "Groupware" );
if( !options.readBoolEntry( "LegacyMangleFromToHeaders", true ) ) {
// Try and match the receiver with an identity
const KPIM::Identity& identity =
kmkernel->identityManager()->identityForAddress( receiver() );
if( identity != KPIM::Identity::null )
// Identity found. Use this
msg->setFrom( identity.fullEmailAddr() );
msg->setHeaderField("X-KMail-Identity", QString::number( identity.uoid() ));
// Remove BCC from identity on ical invitations (https://intevation.de/roundup/kolab/issue474)
msg->setBcc( "" );
}
KMComposeWin *cWin = new KMComposeWin(msg);
// cWin->setCharset( "", true );
cWin->slotWordWrapToggled( false );
// TODO: These are no longer available. It was an internal
// implementation detail of kmcomposewin, anyway. Please find
// another way...
//cWin->mNeverSign = true;
//cWin->mNeverEncrypt = true;
if ( options.readBoolEntry( "AutomaticSending", true ) ) {
cWin->setAutoDeleteWindow( true );
cWin->slotSendNow();
} else {
cWin->show();
}
return true;
}
QString Callback::receiver() const
{
if ( mReceiverSet )
// Already figured this out
return mReceiver;
mReceiverSet = true;
QStringList addrs = KPIM::splitEmailAddrList( mMsg->to() );
if( addrs.count() < 2 )
// Only one receiver, so that has to be us
mReceiver = mMsg->to();
else {
int found = 0;
for( QStringList::Iterator it = addrs.begin(); it != addrs.end(); ++it ) {
if( kmkernel->identityManager()->identityForAddress( *it ) !=
KPIM::Identity::null ) {
// Ok, this could be us
++found;
mReceiver = *it;
}
}
if( found != 1 ) {
bool ok;
mReceiver =
KInputDialog::getItem( i18n( "Select Address" ),
i18n( "<qt>None of your identities match the "
"receiver of this message,<br>please "
"choose which of the following addresses "
"is yours:" ),
addrs, 0, FALSE, &ok, kmkernel->mainWin() );
if( !ok )
mReceiver = QString::null;
}
}
return mReceiver;
}
<|endoftext|> |
<commit_before>#include "bytebuffer.h"
#include "allocators.h"
#include <string.h>
#include <algorithm>
ByteBuffer::ByteBuffer()
{
Construct(NULL, 1024);
}
ByteBuffer::ByteBuffer(size_t size)
{
Construct(NULL, size);
}
ByteBuffer::ByteBuffer(const uint8_t* bytes, size_t len)
{
Construct(bytes, len);
}
void ByteBuffer::Construct(const uint8_t* bytes, size_t len)
{
start_ = 0;
size_ = len;
bytes_ = static_cast<uint8_t*>(erlxml_allocate(size_));
if (bytes)
{
end_ = len;
memcpy(bytes_, bytes, end_);
}
else
{
end_ = 0;
}
}
ByteBuffer::~ByteBuffer()
{
erlxml_deallocate(bytes_);
}
bool ByteBuffer::ReadBytes(uint8_t* val, size_t len)
{
if (len > Length())
return false;
memcpy(val, bytes_ + start_, len);
start_ += len;
return true;
}
void ByteBuffer::WriteBytes(const uint8_t* val, size_t len)
{
memcpy(ReserveWriteBuffer(len), val, len);
}
uint8_t* ByteBuffer::ReserveWriteBuffer(size_t len)
{
if (Length() + len > Capacity())
{
if(!LeftShift())
Resize(Length() + len);
else if (Length() + len > Capacity())
Resize(Length() + len);
}
uint8_t* start = bytes_ + end_;
end_ += len;
return start;
}
void ByteBuffer::Resize(size_t size)
{
if(size == size_)
return;
if (size > size_)
size = std::max(size, 3 * size_ / 2);
size_t len = std::min(end_ - start_, size);
uint8_t* new_bytes = static_cast<uint8_t*>(erlxml_allocate(size));
memcpy(new_bytes, bytes_ + start_, len);
erlxml_deallocate(bytes_);
start_ = 0;
end_ = len;
size_ = size;
bytes_ = new_bytes;
}
bool ByteBuffer::Consume(size_t size)
{
if (size > Length())
return false;
start_ += size;
return true;
}
bool ByteBuffer::LeftShift()
{
if(start_ == 0)
return false;
memmove(bytes_, bytes_ + start_, end_);
end_ -= start_;
start_ = 0;
return true;
}
void ByteBuffer::Clear()
{
start_ = end_ = 0;
}
<commit_msg>Fix LeftShift for buffer<commit_after>#include "bytebuffer.h"
#include "allocators.h"
#include <string.h>
#include <algorithm>
ByteBuffer::ByteBuffer()
{
Construct(NULL, 1024);
}
ByteBuffer::ByteBuffer(size_t size)
{
Construct(NULL, size);
}
ByteBuffer::ByteBuffer(const uint8_t* bytes, size_t len)
{
Construct(bytes, len);
}
void ByteBuffer::Construct(const uint8_t* bytes, size_t len)
{
start_ = 0;
size_ = len;
bytes_ = static_cast<uint8_t*>(erlxml_allocate(size_));
if (bytes)
{
end_ = len;
memcpy(bytes_, bytes, end_);
}
else
{
end_ = 0;
}
}
ByteBuffer::~ByteBuffer()
{
erlxml_deallocate(bytes_);
}
bool ByteBuffer::ReadBytes(uint8_t* val, size_t len)
{
if (len > Length())
return false;
memcpy(val, bytes_ + start_, len);
start_ += len;
return true;
}
void ByteBuffer::WriteBytes(const uint8_t* val, size_t len)
{
memcpy(ReserveWriteBuffer(len), val, len);
}
uint8_t* ByteBuffer::ReserveWriteBuffer(size_t len)
{
if (Length() + len > Capacity())
{
if(!LeftShift())
Resize(Length() + len);
else if (Length() + len > Capacity())
Resize(Length() + len);
}
uint8_t* start = bytes_ + end_;
end_ += len;
return start;
}
void ByteBuffer::Resize(size_t size)
{
if(size == size_)
return;
if (size > size_)
size = std::max(size, 3 * size_ / 2);
size_t len = std::min(end_ - start_, size);
uint8_t* new_bytes = static_cast<uint8_t*>(erlxml_allocate(size));
memcpy(new_bytes, bytes_ + start_, len);
erlxml_deallocate(bytes_);
start_ = 0;
end_ = len;
size_ = size;
bytes_ = new_bytes;
}
bool ByteBuffer::Consume(size_t size)
{
if (size > Length())
return false;
start_ += size;
return true;
}
bool ByteBuffer::LeftShift()
{
if(start_ == 0)
return false;
size_t length = end_ - start_;
memmove(bytes_, bytes_ + start_, length);
start_ = 0;
end_ = length;
return true;
}
void ByteBuffer::Clear()
{
start_ = end_ = 0;
}
<|endoftext|> |
<commit_before>#include "boost_defs.hpp"
#include "hid_manager.hpp"
#include "hid_observer.hpp"
#include <boost/optional/optional_io.hpp>
namespace {
class dump_hid_value final {
public:
dump_hid_value(const dump_hid_value&) = delete;
dump_hid_value(void) {
queue_ = std::make_unique<krbn::thread_utility::queue>();
std::vector<std::pair<krbn::hid_usage_page, krbn::hid_usage>> targets({
std::make_pair(krbn::hid_usage_page::generic_desktop, krbn::hid_usage::gd_keyboard),
std::make_pair(krbn::hid_usage_page::generic_desktop, krbn::hid_usage::gd_mouse),
std::make_pair(krbn::hid_usage_page::generic_desktop, krbn::hid_usage::gd_pointer),
});
hid_manager_ = std::make_unique<krbn::hid_manager>(targets);
hid_manager_->device_detected.connect([this](auto&& weak_hid) {
if (auto hid = weak_hid.lock()) {
hid->values_arrived.connect([this, weak_hid](auto&& shared_event_queue) {
queue_->push_back([this, weak_hid, shared_event_queue] {
if (auto hid = weak_hid.lock()) {
values_arrived(hid, shared_event_queue);
}
});
});
// Observe
auto hid_observer = std::make_shared<krbn::hid_observer>(hid);
hid_observer->device_observed.connect([weak_hid] {
if (auto hid = weak_hid.lock()) {
krbn::logger::get_logger().info("{0} is observed.", hid->get_name_for_log());
}
});
hid_observer->device_unobserved.connect([weak_hid] {
if (auto hid = weak_hid.lock()) {
krbn::logger::get_logger().info("{0} is unobserved.", hid->get_name_for_log());
}
});
hid_observer->async_observe();
hid_observers_[hid->get_registry_entry_id()] = hid_observer;
}
});
hid_manager_->device_removed.connect([this](auto&& weak_hid) {
if (auto hid = weak_hid.lock()) {
krbn::logger::get_logger().info("{0} is removed.", hid->get_name_for_log());
hid_observers_.erase(hid->get_registry_entry_id());
}
});
hid_manager_->async_start();
}
~dump_hid_value(void) {
hid_manager_ = nullptr;
hid_observers_.clear();
queue_->terminate();
queue_ = nullptr;
}
private:
void values_arrived(std::shared_ptr<krbn::human_interface_device> hid,
std::shared_ptr<krbn::event_queue> event_queue) const {
for (const auto& queued_event : event_queue->get_events()) {
std::cout << queued_event.get_event_time_stamp().get_time_stamp() << " ";
switch (queued_event.get_event().get_type()) {
case krbn::event_queue::queued_event::event::type::none:
std::cout << "none" << std::endl;
break;
case krbn::event_queue::queued_event::event::type::key_code:
if (auto key_code = queued_event.get_event().get_key_code()) {
std::cout << "Key: " << std::dec << static_cast<uint32_t>(*key_code) << " "
<< queued_event.get_event_type()
<< std::endl;
}
break;
case krbn::event_queue::queued_event::event::type::consumer_key_code:
if (auto consumer_key_code = queued_event.get_event().get_consumer_key_code()) {
std::cout << "ConsumerKey: " << std::dec << static_cast<uint32_t>(*consumer_key_code) << " "
<< queued_event.get_event_type()
<< std::endl;
}
break;
case krbn::event_queue::queued_event::event::type::pointing_button:
if (auto pointing_button = queued_event.get_event().get_pointing_button()) {
std::cout << "Button: " << std::dec << static_cast<uint32_t>(*pointing_button) << " "
<< queued_event.get_event_type()
<< std::endl;
}
break;
case krbn::event_queue::queued_event::event::type::pointing_motion:
if (auto pointing_motion = queued_event.get_event().get_pointing_motion()) {
std::cout << "pointing_motion: " << pointing_motion->to_json() << std::endl;
}
break;
case krbn::event_queue::queued_event::event::type::shell_command:
std::cout << "shell_command" << std::endl;
break;
case krbn::event_queue::queued_event::event::type::select_input_source:
std::cout << "select_input_source" << std::endl;
break;
case krbn::event_queue::queued_event::event::type::set_variable:
std::cout << "set_variable" << std::endl;
break;
case krbn::event_queue::queued_event::event::type::mouse_key:
std::cout << "mouse_key" << std::endl;
break;
case krbn::event_queue::queued_event::event::type::stop_keyboard_repeat:
std::cout << "stop_keyboard_repeat" << std::endl;
break;
case krbn::event_queue::queued_event::event::type::device_keys_and_pointing_buttons_are_released:
std::cout << "device_keys_and_pointing_buttons_are_released for " << hid->get_name_for_log() << " (" << hid->get_device_id() << ")" << std::endl;
break;
case krbn::event_queue::queued_event::event::type::device_ungrabbed:
std::cout << "device_ungrabbed for " << hid->get_name_for_log() << " (" << hid->get_device_id() << ")" << std::endl;
break;
case krbn::event_queue::queued_event::event::type::caps_lock_state_changed:
if (auto integer_value = queued_event.get_event().get_integer_value()) {
std::cout << "caps_lock_state_changed " << *integer_value << std::endl;
}
break;
case krbn::event_queue::queued_event::event::type::pointing_device_event_from_event_tap:
std::cout << "pointing_device_event_from_event_tap from " << hid->get_name_for_log() << " (" << hid->get_device_id() << ")" << std::endl;
break;
case krbn::event_queue::queued_event::event::type::frontmost_application_changed:
if (auto frontmost_application = queued_event.get_event().get_frontmost_application()) {
std::cout << "frontmost_application_changed "
<< frontmost_application->get_bundle_identifier() << " "
<< frontmost_application->get_file_path() << std::endl;
}
break;
case krbn::event_queue::queued_event::event::type::input_source_changed:
if (auto input_source_identifiers = queued_event.get_event().get_input_source_identifiers()) {
std::cout << "input_source_changed " << input_source_identifiers << std::endl;
}
break;
case krbn::event_queue::queued_event::event::type::keyboard_type_changed:
if (auto keyboard_type = queued_event.get_event().get_keyboard_type()) {
std::cout << "keyboard_type_changed " << keyboard_type << std::endl;
}
break;
default:
std::cout << std::endl;
}
}
}
std::unique_ptr<krbn::thread_utility::queue> queue_;
std::unique_ptr<krbn::hid_manager> hid_manager_;
std::unordered_map<krbn::registry_entry_id, std::shared_ptr<krbn::hid_observer>> hid_observers_;
};
} // namespace
int main(int argc, const char* argv[]) {
krbn::thread_utility::register_main_thread();
signal(SIGINT, [](int) {
CFRunLoopStop(CFRunLoopGetMain());
});
auto d = std::make_unique<dump_hid_value>();
CFRunLoopRun();
d = nullptr;
return 0;
}
<commit_msg>update dump_hid_value<commit_after>#include "boost_defs.hpp"
#include "hid_manager.hpp"
#include "hid_observer.hpp"
#include <boost/optional/optional_io.hpp>
namespace {
class dump_hid_value final {
public:
dump_hid_value(const dump_hid_value&) = delete;
dump_hid_value(void) {
queue_ = std::make_unique<krbn::thread_utility::queue>();
std::vector<std::pair<krbn::hid_usage_page, krbn::hid_usage>> targets({
std::make_pair(krbn::hid_usage_page::generic_desktop, krbn::hid_usage::gd_keyboard),
std::make_pair(krbn::hid_usage_page::generic_desktop, krbn::hid_usage::gd_mouse),
std::make_pair(krbn::hid_usage_page::generic_desktop, krbn::hid_usage::gd_pointer),
});
hid_manager_ = std::make_unique<krbn::hid_manager>(targets);
hid_manager_->device_detected.connect([this](auto&& weak_hid) {
if (auto hid = weak_hid.lock()) {
hid->values_arrived.connect([this, weak_hid](auto&& shared_event_queue) {
queue_->push_back([this, weak_hid, shared_event_queue] {
if (auto hid = weak_hid.lock()) {
values_arrived(hid, shared_event_queue);
}
});
});
// Observe
auto hid_observer = std::make_shared<krbn::hid_observer>(hid);
hid_observer->device_observed.connect([weak_hid] {
if (auto hid = weak_hid.lock()) {
krbn::logger::get_logger().info("{0} is observed.", hid->get_name_for_log());
}
});
hid_observer->device_unobserved.connect([weak_hid] {
if (auto hid = weak_hid.lock()) {
krbn::logger::get_logger().info("{0} is unobserved.", hid->get_name_for_log());
}
});
hid_observer->async_observe();
hid_observers_[hid->get_registry_entry_id()] = hid_observer;
}
});
hid_manager_->device_removed.connect([this](auto&& weak_hid) {
if (auto hid = weak_hid.lock()) {
krbn::logger::get_logger().info("{0} is removed.", hid->get_name_for_log());
hid_observers_.erase(hid->get_registry_entry_id());
}
});
hid_manager_->async_start();
}
~dump_hid_value(void) {
queue_->push_back([this] {
hid_manager_ = nullptr;
hid_observers_.clear();
});
queue_->terminate();
queue_ = nullptr;
}
private:
void values_arrived(std::shared_ptr<krbn::human_interface_device> hid,
std::shared_ptr<krbn::event_queue> event_queue) const {
for (const auto& queued_event : event_queue->get_events()) {
std::cout << queued_event.get_event_time_stamp().get_time_stamp() << " ";
switch (queued_event.get_event().get_type()) {
case krbn::event_queue::queued_event::event::type::none:
std::cout << "none" << std::endl;
break;
case krbn::event_queue::queued_event::event::type::key_code:
if (auto key_code = queued_event.get_event().get_key_code()) {
std::cout << "Key: " << std::dec << static_cast<uint32_t>(*key_code) << " "
<< queued_event.get_event_type()
<< std::endl;
}
break;
case krbn::event_queue::queued_event::event::type::consumer_key_code:
if (auto consumer_key_code = queued_event.get_event().get_consumer_key_code()) {
std::cout << "ConsumerKey: " << std::dec << static_cast<uint32_t>(*consumer_key_code) << " "
<< queued_event.get_event_type()
<< std::endl;
}
break;
case krbn::event_queue::queued_event::event::type::pointing_button:
if (auto pointing_button = queued_event.get_event().get_pointing_button()) {
std::cout << "Button: " << std::dec << static_cast<uint32_t>(*pointing_button) << " "
<< queued_event.get_event_type()
<< std::endl;
}
break;
case krbn::event_queue::queued_event::event::type::pointing_motion:
if (auto pointing_motion = queued_event.get_event().get_pointing_motion()) {
std::cout << "pointing_motion: " << pointing_motion->to_json() << std::endl;
}
break;
case krbn::event_queue::queued_event::event::type::shell_command:
std::cout << "shell_command" << std::endl;
break;
case krbn::event_queue::queued_event::event::type::select_input_source:
std::cout << "select_input_source" << std::endl;
break;
case krbn::event_queue::queued_event::event::type::set_variable:
std::cout << "set_variable" << std::endl;
break;
case krbn::event_queue::queued_event::event::type::mouse_key:
std::cout << "mouse_key" << std::endl;
break;
case krbn::event_queue::queued_event::event::type::stop_keyboard_repeat:
std::cout << "stop_keyboard_repeat" << std::endl;
break;
case krbn::event_queue::queued_event::event::type::device_keys_and_pointing_buttons_are_released:
std::cout << "device_keys_and_pointing_buttons_are_released for " << hid->get_name_for_log() << " (" << hid->get_device_id() << ")" << std::endl;
break;
case krbn::event_queue::queued_event::event::type::device_ungrabbed:
std::cout << "device_ungrabbed for " << hid->get_name_for_log() << " (" << hid->get_device_id() << ")" << std::endl;
break;
case krbn::event_queue::queued_event::event::type::caps_lock_state_changed:
if (auto integer_value = queued_event.get_event().get_integer_value()) {
std::cout << "caps_lock_state_changed " << *integer_value << std::endl;
}
break;
case krbn::event_queue::queued_event::event::type::pointing_device_event_from_event_tap:
std::cout << "pointing_device_event_from_event_tap from " << hid->get_name_for_log() << " (" << hid->get_device_id() << ")" << std::endl;
break;
case krbn::event_queue::queued_event::event::type::frontmost_application_changed:
if (auto frontmost_application = queued_event.get_event().get_frontmost_application()) {
std::cout << "frontmost_application_changed "
<< frontmost_application->get_bundle_identifier() << " "
<< frontmost_application->get_file_path() << std::endl;
}
break;
case krbn::event_queue::queued_event::event::type::input_source_changed:
if (auto input_source_identifiers = queued_event.get_event().get_input_source_identifiers()) {
std::cout << "input_source_changed " << input_source_identifiers << std::endl;
}
break;
case krbn::event_queue::queued_event::event::type::keyboard_type_changed:
if (auto keyboard_type = queued_event.get_event().get_keyboard_type()) {
std::cout << "keyboard_type_changed " << keyboard_type << std::endl;
}
break;
default:
std::cout << std::endl;
}
}
}
std::unique_ptr<krbn::thread_utility::queue> queue_;
std::unique_ptr<krbn::hid_manager> hid_manager_;
std::unordered_map<krbn::registry_entry_id, std::shared_ptr<krbn::hid_observer>> hid_observers_;
};
} // namespace
int main(int argc, const char* argv[]) {
krbn::thread_utility::register_main_thread();
signal(SIGINT, [](int) {
CFRunLoopStop(CFRunLoopGetMain());
});
auto d = std::make_unique<dump_hid_value>();
CFRunLoopRun();
d = nullptr;
return 0;
}
<|endoftext|> |
<commit_before>// Module: LOG4CPLUS
// File: loggingserver.cxx
// Created: 5/2003
// Author: Tad E. Smith
//
//
// Copyright 2003-2013 Tad E. Smith
//
// 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 <cstdlib>
#include <iostream>
#include <log4cplus/configurator.h>
#include <log4cplus/socketappender.h>
#include <log4cplus/helpers/socket.h>
#include <log4cplus/thread/threads.h>
#include <log4cplus/helpers/sleep.h>
#include <log4cplus/spi/loggingevent.h>
namespace loggingserver
{
class ClientThread : public log4cplus::thread::AbstractThread
{
public:
ClientThread(log4cplus::helpers::Socket clientsock)
: clientsock(clientsock)
{
std::cout << "Received a client connection!!!!" << std::endl;
}
~ClientThread()
{
std::cout << "Client connection closed." << std::endl;
}
virtual void run();
private:
log4cplus::helpers::Socket clientsock;
};
class InterruptAcceptThread
: public log4cplus::thread::AbstractThread
{
public:
InterruptAcceptThread(log4cplus::helpers::ServerSocket & s)
: acceptSock (s)
{
std::cout << "Interrupt accept thread created." << std::endl;
}
~InterruptAcceptThread()
{
std::cout << "InterruptAcceptThread closing." << std::endl;
}
virtual void run()
{
log4cplus::helpers::sleep (2);
acceptSock.interruptAccept();
}
private:
log4cplus::helpers::ServerSocket & acceptSock;
};
}
int
main(int argc, char** argv)
{
if(argc < 3) {
std::cout << "Usage: port config_file" << std::endl;
return 1;
}
int port = std::atoi(argv[1]);
const log4cplus::tstring configFile = LOG4CPLUS_C_STR_TO_TSTRING(argv[2]);
log4cplus::PropertyConfigurator config(configFile);
config.configure();
log4cplus::helpers::ServerSocket serverSocket(port);
if (!serverSocket.isOpen()) {
std::cout << "Could not open server socket, maybe port "
<< port << " is already in use." << std::endl;
return 2;
}
while(1) {
log4cplus::thread::AbstractThread *thr;
thr = new loggingserver::InterruptAcceptThread (serverSocket);
thr->start ();
thr = new loggingserver::ClientThread(serverSocket.accept());
thr->start();
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
// loggingserver::ClientThread implementation
////////////////////////////////////////////////////////////////////////////////
void
loggingserver::ClientThread::run()
{
while(1) {
if(!clientsock.isOpen()) {
return;
}
log4cplus::helpers::SocketBuffer msgSizeBuffer(sizeof(unsigned int));
if(!clientsock.read(msgSizeBuffer)) {
return;
}
unsigned int msgSize = msgSizeBuffer.readInt();
log4cplus::helpers::SocketBuffer buffer(msgSize);
if(!clientsock.read(buffer)) {
return;
}
log4cplus::spi::InternalLoggingEvent event
= log4cplus::helpers::readFromBuffer(buffer);
log4cplus::Logger logger
= log4cplus::Logger::getInstance(event.getLoggerName());
logger.callAppenders(event);
}
}
<commit_msg>loggingserver.cxx: Revert accidentally committed testing changes.<commit_after>// Module: LOG4CPLUS
// File: loggingserver.cxx
// Created: 5/2003
// Author: Tad E. Smith
//
//
// Copyright 2003-2013 Tad E. Smith
//
// 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 <cstdlib>
#include <iostream>
#include <log4cplus/configurator.h>
#include <log4cplus/socketappender.h>
#include <log4cplus/helpers/socket.h>
#include <log4cplus/thread/threads.h>
#include <log4cplus/spi/loggingevent.h>
namespace loggingserver
{
class ClientThread : public log4cplus::thread::AbstractThread
{
public:
ClientThread(log4cplus::helpers::Socket clientsock)
: clientsock(clientsock)
{
std::cout << "Received a client connection!!!!" << std::endl;
}
~ClientThread()
{
std::cout << "Client connection closed." << std::endl;
}
virtual void run();
private:
log4cplus::helpers::Socket clientsock;
};
}
int
main(int argc, char** argv)
{
if(argc < 3) {
std::cout << "Usage: port config_file" << std::endl;
return 1;
}
int port = std::atoi(argv[1]);
const log4cplus::tstring configFile = LOG4CPLUS_C_STR_TO_TSTRING(argv[2]);
log4cplus::PropertyConfigurator config(configFile);
config.configure();
log4cplus::helpers::ServerSocket serverSocket(port);
if (!serverSocket.isOpen()) {
std::cout << "Could not open server socket, maybe port "
<< port << " is already in use." << std::endl;
return 2;
}
while(1) {
loggingserver::ClientThread *thr =
new loggingserver::ClientThread(serverSocket.accept());
thr->start();
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
// loggingserver::ClientThread implementation
////////////////////////////////////////////////////////////////////////////////
void
loggingserver::ClientThread::run()
{
while(1) {
if(!clientsock.isOpen()) {
return;
}
log4cplus::helpers::SocketBuffer msgSizeBuffer(sizeof(unsigned int));
if(!clientsock.read(msgSizeBuffer)) {
return;
}
unsigned int msgSize = msgSizeBuffer.readInt();
log4cplus::helpers::SocketBuffer buffer(msgSize);
if(!clientsock.read(buffer)) {
return;
}
log4cplus::spi::InternalLoggingEvent event
= log4cplus::helpers::readFromBuffer(buffer);
log4cplus::Logger logger
= log4cplus::Logger::getInstance(event.getLoggerName());
logger.callAppenders(event);
}
}
<|endoftext|> |
<commit_before>#ifndef MATCHES_DHT_HPP
#define MATCHES_DHT_HPP
#include <Grappa.hpp>
#include <GlobalAllocator.hpp>
#include <ParallelLoop.hpp>
#include <BufferVector.hpp>
#include <list>
// for naming the types scoped in MatchesDHT
#define MDHT_TYPE(type) typename MatchesDHT<K,V,HF>::type
// Hash table for joins
// * allows multiple copies of a Key
// * lookups return all Key matches
template <typename K, typename V, uint64_t (*HF)(K)>
class MatchesDHT {
private:
struct Entry {
K key;
BufferVector<V> * vs;
Entry( K key ) : key(key), vs(new BufferVector<V>()) {}
};
struct Cell {
std::list<Entry> * entries;
Cell() : entries( NULL ) {}
};
struct lookup_result {
GlobalAddress<V> matches;
size_t num;
};
// private members
GlobalAddress< Cell > base;
size_t capacity;
uint64_t computeIndex( K key ) {
return HF(key) % capacity;
}
// for creating local MatchesDHT
MatchesDHT( GlobalAddress<Cell> base, size_t capacity ) {
this->base = base;
this->capacity = capacity;
}
public:
// for static construction
MatchesDHT( ) {}
static void init_global_DHT( MatchesDHT<K,V,HF> * globally_valid_local_pointer, size_t capacity ) {
GlobalAddress<Cell> base = Grappa_typed_malloc<Cell>( capacity );
Grappa::on_all_cores( [globally_valid_local_pointer,base,capacity] {
*globally_valid_local_pointer = MatchesDHT<K,V,HF>( base, capacity );
});
Grappa::forall_localized( base, capacity, []( int64_t i, Cell& c ) {
Cell empty;
c = empty;
});
}
static void set_RO_global( MatchesDHT<K,V,HF> * globally_valid_local_pointer ) {
Grappa::forall_localized( globally_valid_local_pointer->base, globally_valid_local_pointer->capacity, []( int64_t i, Cell& c ) {
// list of entries in this cell
std::list<MDHT_TYPE(Entry)> * entries = c.entries;
// if cell is not hit then no action
if ( entries == NULL ) {
return;
}
// for all keys, set match vector to RO
typename std::list<MDHT_TYPE(Entry)>::iterator it;
for (it = entries->begin(); it!=entries->end(); ++it) {
Entry e = *it;
e.vs->setReadMode();
}
});
}
uint64_t lookup ( K key, GlobalAddress<V> * vals ) {
uint64_t index = computeIndex( key );
GlobalAddress< Cell > target = base + index;
lookup_result result = Grappa::delegate::call( target.node(), [key,target]() {
std::list<MDHT_TYPE(Entry)> * entries = target.pointer()->entries;
MDHT_TYPE(lookup_result) lr;
lr.num = 0;
// first check if the cell has any entries;
// if not then the lookup returns nothing
if ( entries == NULL ) return lr;
typename std::list<MDHT_TYPE(Entry)>::iterator i;
for (i = entries->begin(); i!=entries->end(); ++i) {
const Entry e = *i;
if ( e.key == key ) { // typename K must implement operator==
lr.matches = e.vs->getReadBuffer();
lr.num = e.vs->getLength();
break;
}
}
return lr;
});
*vals = result.matches;
return result.num;
}
void insert( K key, V val ) {
uint64_t index = computeIndex( key );
GlobalAddress< Cell > target = base + index;
Grappa::delegate::call( target.node(), [key, val, target]() { // TODO: upgrade to call_async
// list of entries in this cell
std::list<MDHT_TYPE(Entry)> * entries = target.pointer()->entries;
// if first time the cell is hit then initialize
if ( entries == NULL ) {
entries = new std::list<Entry>();
target.pointer()->entries = entries;
}
// find matching key in the list
typename std::list<MDHT_TYPE(Entry)>::iterator i;
for (i = entries->begin(); i!=entries->end(); ++i) {
Entry e = *i;
if ( e.key == key ) {
// key found so add to matches
e.vs->insert( val );
return 0;
}
}
// this is the first time the key has been seen
// so add it to the list
Entry newe( key );
newe.vs->insert( val );
entries->push_back( newe );
return 0; // TODO: see "delegate that..."
});
}
};
#endif // MATCHES_DHT_HPP
<commit_msg>matches uses new max statistic<commit_after>#ifndef MATCHES_DHT_HPP
#define MATCHES_DHT_HPP
#include <Grappa.hpp>
#include <GlobalAllocator.hpp>
#include <ParallelLoop.hpp>
#include <BufferVector.hpp>
#include <Statistics.hpp>
#include <list>
// for all hash tables
GRAPPA_DEFINE_STAT(MaxStatistic<uint64_t>, max_cell_length, 0);
// for naming the types scoped in MatchesDHT
#define MDHT_TYPE(type) typename MatchesDHT<K,V,HF>::type
// Hash table for joins
// * allows multiple copies of a Key
// * lookups return all Key matches
template <typename K, typename V, uint64_t (*HF)(K)>
class MatchesDHT {
private:
struct Entry {
K key;
BufferVector<V> * vs;
Entry( K key ) : key(key), vs(new BufferVector<V>()) {}
};
struct Cell {
std::list<Entry> * entries;
Cell() : entries( NULL ) {}
};
struct lookup_result {
GlobalAddress<V> matches;
size_t num;
};
// private members
GlobalAddress< Cell > base;
size_t capacity;
uint64_t computeIndex( K key ) {
return HF(key) % capacity;
}
// for creating local MatchesDHT
MatchesDHT( GlobalAddress<Cell> base, size_t capacity ) {
this->base = base;
this->capacity = capacity;
}
public:
// for static construction
MatchesDHT( ) {}
static void init_global_DHT( MatchesDHT<K,V,HF> * globally_valid_local_pointer, size_t capacity ) {
GlobalAddress<Cell> base = Grappa_typed_malloc<Cell>( capacity );
Grappa::on_all_cores( [globally_valid_local_pointer,base,capacity] {
*globally_valid_local_pointer = MatchesDHT<K,V,HF>( base, capacity );
});
Grappa::forall_localized( base, capacity, []( int64_t i, Cell& c ) {
Cell empty;
c = empty;
});
}
static void set_RO_global( MatchesDHT<K,V,HF> * globally_valid_local_pointer ) {
Grappa::forall_localized( globally_valid_local_pointer->base, globally_valid_local_pointer->capacity, []( int64_t i, Cell& c ) {
// list of entries in this cell
std::list<MDHT_TYPE(Entry)> * entries = c.entries;
// if cell is not hit then no action
if ( entries == NULL ) {
return;
}
uint64_t sum_size = 0;
// for all keys, set match vector to RO
typename std::list<MDHT_TYPE(Entry)>::iterator it;
for (it = entries->begin(); it!=entries->end(); ++it) {
Entry e = *it;
e.vs->setReadMode();
sum_size+=e.vs->getLength();
}
max_cell_length.add(sum_size);
});
}
uint64_t lookup ( K key, GlobalAddress<V> * vals ) {
uint64_t index = computeIndex( key );
GlobalAddress< Cell > target = base + index;
lookup_result result = Grappa::delegate::call( target.node(), [key,target]() {
std::list<MDHT_TYPE(Entry)> * entries = target.pointer()->entries;
MDHT_TYPE(lookup_result) lr;
lr.num = 0;
// first check if the cell has any entries;
// if not then the lookup returns nothing
if ( entries == NULL ) return lr;
typename std::list<MDHT_TYPE(Entry)>::iterator i;
for (i = entries->begin(); i!=entries->end(); ++i) {
const Entry e = *i;
if ( e.key == key ) { // typename K must implement operator==
lr.matches = e.vs->getReadBuffer();
lr.num = e.vs->getLength();
break;
}
}
return lr;
});
*vals = result.matches;
return result.num;
}
// Inserts the key if not already in the set
// Shouldn't be used with `insert`.
//
// returns true if the set already contains the key
bool insert_unique( K key ) {
uint64_t index = computeIndex( key );
GlobalAddress< Cell > target = base + index;
//FIXME: remove index capture
bool result = Grappa::delegate::call( target.node(), [index,key, target]() { // TODO: have an additional version that returns void
// to upgrade to call_async
// list of entries in this cell
std::list<MDHT_TYPE(Entry)> * entries = target.pointer()->entries;
// if first time the cell is hit then initialize
if ( entries == NULL ) {
entries = new std::list<Entry>();
target.pointer()->entries = entries;
}
// find matching key in the list
typename std::list<MDHT_TYPE(Entry)>::iterator i;
for (i = entries->begin(); i!=entries->end(); ++i) {
Entry e = *i;
if ( e.key == key ) {
// key found so no insert
return true;
}
}
// this is the first time the key has been seen
// so add it to the list
Entry newe( key ); // TODO: cleanup since sharing insert* code here, we are just going to store an empty vector
// perhaps a different module
entries->push_back( newe );
return false;
});
return result;
}
void insert( K key, V val ) {
uint64_t index = computeIndex( key );
GlobalAddress< Cell > target = base + index;
Grappa::delegate::call( target.node(), [key, val, target]() { // TODO: upgrade to call_async
// list of entries in this cell
std::list<MDHT_TYPE(Entry)> * entries = target.pointer()->entries;
// if first time the cell is hit then initialize
if ( entries == NULL ) {
entries = new std::list<Entry>();
target.pointer()->entries = entries;
}
// find matching key in the list
typename std::list<MDHT_TYPE(Entry)>::iterator i;
for (i = entries->begin(); i!=entries->end(); ++i) {
Entry e = *i;
if ( e.key == key ) {
// key found so add to matches
e.vs->insert( val );
return 0;
}
}
// this is the first time the key has been seen
// so add it to the list
Entry newe( key );
newe.vs->insert( val );
entries->push_back( newe );
return 0;
});
}
};
#endif // MATCHES_DHT_HPP
<|endoftext|> |
<commit_before>/**
* \file summed_table.cpp
*
* Summed area table using overlapped computation
*/
#include <iostream>
#include <Halide.h>
#include "recfilter.h"
#include "timing.h"
using namespace Halide;
using std::map;
using std::vector;
using std::string;
using std::cerr;
using std::cout;
using std::endl;
int main(int argc, char **argv) {
Arguments args(argc, argv);
bool nocheck = args.nocheck;
int iter = args.iterations;
int tile_width = args.block;
int min_w = args.min_width;
int max_w = args.max_width;
int inc_w = tile_width;
Log log("summed_table.perflog");
log << "Width\tOurs" << endl;
// Profile the filter for all image widths
for (int in_w=min_w; in_w<=max_w; in_w+=inc_w) {
int width = in_w;
int height= in_w;
Image<float> image = generate_random_image<float>(width,height);
RecFilterDim x("x", width);
RecFilterDim y("y", height);
RecFilter F;
F(x,y) = image(x,y);
F.add_filter(+x, {1.0, 1.0});
F.add_filter(+y, {1.0, 1.0});
F.split(x, tile_width, y, tile_width);
// ---------------------------------------------------------------------
int order = 1;
int n_scans = 2;
int ws = 32;
int unroll_w = ws/4;
int intra_tiles_per_warp = ws / (order*n_scans);
int inter_tiles_per_warp = 4;
F.intra_schedule(1).compute_locally()
.reorder_storage(F.inner(), F.outer())
.unroll (F.inner_scan())
.split (F.inner(1), unroll_w)
.unroll (F.inner(1).split_var())
.reorder (F.inner_scan(), F.inner(1).split_var(), F.inner(), F.outer())
.gpu_threads (F.inner(0), F.inner(1))
.gpu_blocks (F.outer(0), F.outer(1));
F.intra_schedule(2).compute_locally()
.reorder_storage(F.tail(), F.inner(), F.outer())
.unroll (F.inner_scan())
.split (F.outer(0), intra_tiles_per_warp)
.reorder (F.inner_scan(), F.inner(), F.outer(0).split_var(), F.tail(), F.outer())
.fuse (F.inner(0), F.outer(0).split_var())
.fuse (F.inner(0), F.tail())
.gpu_threads (F.inner(0))
.gpu_blocks (F.outer(0), F.outer(1));
F.inter_schedule().compute_globally()
.reorder_storage(F.inner(), F.tail(), F.outer())
.unroll (F.outer_scan())
.split (F.outer(0), inter_tiles_per_warp)
.reorder (F.outer_scan(), F.tail(), F.outer(0).split_var(), F.inner(), F.outer())
.gpu_threads (F.inner(0), F.outer(0).split_var())
.gpu_blocks (F.outer(0));
float time = F.profile(iter);
cerr << width << "\t" << time << " ms" << endl;
log << width << "\t" << throughput(time,width*width) << endl;
// ---------------------------------------------------------------------
if (!nocheck) {
cerr << "\nChecking difference ... " << endl;
Realization out = F.realize();
Image<float> hl_out(out);
Image<float> ref(width,height);
for (int y=0; y<height; y++) {
for (int x=0; x<width; x++) {
ref(x,y) = image(x,y);
}
}
for (int y=0; y<height; y++) {
for (int x=1; x<width; x++) {
ref(x,y) += ref(x-1,y);
}
}
for (int y=1; y<height; y++) {
for (int x=0; x<width; x++) {
ref(x,y) += ref(x,y-1);
}
}
cout << CheckResult<float>(ref,hl_out) << endl;
}
}
return 0;
}
<commit_msg>Minor changes in summed table<commit_after>/**
* \file summed_table.cpp
*
* Summed area table using overlapped computation
*/
#include <iostream>
#include <Halide.h>
#include "recfilter.h"
#include "timing.h"
using namespace Halide;
using std::map;
using std::vector;
using std::string;
using std::cerr;
using std::cout;
using std::endl;
int main(int argc, char **argv) {
Arguments args(argc, argv);
bool nocheck = args.nocheck;
int iter = args.iterations;
int tile_width = args.block;
int min_w = args.min_width;
int max_w = args.max_width;
int inc_w = tile_width;
Log log("summed_table.perflog");
log << "Width\tOurs" << endl;
// Profile the filter for all image widths
for (int in_w=min_w; in_w<=max_w; in_w+=inc_w) {
int width = in_w;
int height= in_w;
Image<float> image = generate_random_image<float>(width,height);
RecFilterDim x("x", width);
RecFilterDim y("y", height);
RecFilter F;
F(x,y) = image(x,y);
F.add_filter(+x, {1.0, 1.0});
F.add_filter(+y, {1.0, 1.0});
F.split(x, tile_width, y, tile_width);
// ---------------------------------------------------------------------
if (F.target().has_gpu_feature()) {
int order = 1;
int n_scans = 2;
int ws = 32;
int unroll_w = ws/4;
int intra_tiles_per_warp = ws / (order*n_scans);
int inter_tiles_per_warp = 4;
F.intra_schedule(1).compute_locally()
.reorder_storage(F.inner(), F.outer())
.unroll (F.inner_scan())
.split (F.inner(1), unroll_w)
.unroll (F.inner(1).split_var())
.reorder (F.inner_scan(), F.inner(1).split_var(), F.inner(), F.outer())
.gpu_threads (F.inner(0), F.inner(1))
.gpu_blocks (F.outer(0), F.outer(1));
F.intra_schedule(2).compute_locally()
//.reorder_storage(F.tail(), F.inner(), F.outer())
.unroll (F.inner_scan())
.split (F.outer(0), intra_tiles_per_warp)
.reorder (F.inner_scan(), F.inner(), F.tail(), F.outer(0).split_var(), F.outer())
.fuse (F.inner(0), F.outer(0).split_var())
.fuse (F.inner(0), F.tail())
.gpu_threads (F.inner(0))
.gpu_blocks (F.outer(0), F.outer(1));
F.inter_schedule().compute_globally()
.reorder_storage(F.inner(), F.tail(), F.outer())
.unroll (F.outer_scan())
.split (F.outer(0), inter_tiles_per_warp)
.reorder (F.outer_scan(), F.tail(), F.outer(0).split_var(), F.inner(), F.outer())
.gpu_threads (F.inner(0), F.outer(0).split_var())
.gpu_blocks (F.outer(0));
float time = F.profile(iter);
cerr << width << "\t" << time << " ms" << endl;
log << width << "\t" << throughput(time,width*width) << endl;
}
// ---------------------------------------------------------------------
if (!nocheck) {
cerr << "\nChecking difference ... " << endl;
Realization out = F.realize();
Image<float> hl_out(out);
Image<float> ref(width,height);
for (int y=0; y<height; y++) {
for (int x=0; x<width; x++) {
ref(x,y) = image(x,y);
}
}
for (int y=0; y<height; y++) {
for (int x=1; x<width; x++) {
ref(x,y) += ref(x-1,y);
}
}
for (int y=1; y<height; y++) {
for (int x=0; x<width; x++) {
ref(x,y) += ref(x,y-1);
}
}
cout << CheckResult<float>(ref,hl_out) << endl;
}
}
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SdUnoPresView.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-03-21 17:34:45 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "SdUnoPresView.hxx"
namespace sd {
SdUnoPresView::SdUnoPresView (
DrawController& rController,
DrawViewShell& rViewShell,
View& rView) throw()
: SdUnoDrawView (rController, rViewShell, rView)
{
}
SdUnoPresView::~SdUnoPresView (void) throw()
{
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS pchfix02 (1.8.146); FILE MERGED 2006/09/01 17:37:28 kaib 1.8.146.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SdUnoPresView.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-09-16 19:23:44 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "SdUnoPresView.hxx"
namespace sd {
SdUnoPresView::SdUnoPresView (
DrawController& rController,
DrawViewShell& rViewShell,
View& rView) throw()
: SdUnoDrawView (rController, rViewShell, rView)
{
}
SdUnoPresView::~SdUnoPresView (void) throw()
{
}
} // end of namespace sd
<|endoftext|> |
<commit_before>#ifdef WIN32
#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <fcntl.h>
#include <io.h>
#define UNUSED 0xDEADBEEF
#define LOG_DAEMON UNUSED
void syslog(int pri, const TCHAR * msg);
#else
#include <unistd.h> /* fork(), execl(), readlink(), chdir(), ... */
#include <sys/types.h> /* pid_t */
#include <sys/wait.h> /* WEXITSTATUS(), waitpid() */
#include <sys/stat.h> /* umask() */
#include <syslog.h>
#include <stdlib.h> /* system(), exit(), EXIT_... */
#include <string.h> /* strrchr() */
#include <fcntl.h> /* open(), O_RDWR */
#include <limits.h> /* PATH_MAX */
#include <signal.h> /* signal(), kill(), raise(), SIG... */
#include <stdio.h> /* FILE, fgets(), fdopen() */
#include <pwd.h> /* getpwnam() */
static int nfs_delay;
#endif
#include <time.h>
#include "proactivep2p.h"
/*
* If the jvm crashes in less than one minute, three times, there is a problem,
* we shut down the daemon. This is disabled for now, because there is a delay
* during the restart, and every crashing events we encountered would disappear
* after some delay.
*/
#define ACCEPTABLE_CRASH_DELAY 60
#define MAX_CRASH_COUNT 3
typedef enum {
DAEMON_TIME_ERROR,
DAEMON_JVM_KEEPS_CRASHING,
DAEMON_JVM_EXIT_FATAL,
DAEMON_WRONG_PARAM,
DAEMON_UNKNOWN_ERROR,
} daemon_ret_t;
/*
* Exit codes : 0 => OK, restart the daemon
* 220 => Error, don't restart
* 2 => Restart but wait for the next period
* other => Error, restart
*
* These exit codes must be synchronized with the Java code
*/
#define EXIT_OK 0
#define EXIT_FATAL 220
#define EXIT_NEXT_RUN 2
#ifdef WIN32
static void daemonize(void)
{
}
static void init_random_sleep(void)
{
/* TODO */
}
static void random_sleep(int nb_seconds
{
/* TODO */
}
static void symbolink_link_cd(const TCHAR * filename)
{
TCHAR buffer[MAX_PATH];
FILE *file;
file = _tfopen(filename, TEXT("rt"));
if (file == NULL)
return;
if (_fgetts(buffer, sizeof(buffer) / sizeof(TCHAR), file) != NULL) {
SetCurrentDirectory(buffer);
}
fclose(file);
}
static void change_to_daemon_dir(void)
{
TCHAR szDllName[_MAX_PATH];
TCHAR szApp[_MAX_PATH * 2];
int i, len;
GetModuleFileName(0, szDllName, _MAX_PATH);
len = wcslen(szDllName);
wcscpy(szApp, szDllName);
for (i = len - 1; i > 0; i--) {
if (szApp[i] == '\\') {
szApp[i + 1] = 0;
break;
}
}
SetCurrentDirectory(szApp);
symbolink_link_cd(DAEMON_DIR);
}
static PROCESS_INFORMATION piProcInfo;
extern TCHAR *user_name;
extern TCHAR *domain;
extern TCHAR *password;
static BOOL logged = FALSE;
static HANDLE user_token;
static int execute(const TCHAR * cmd, const TCHAR * flag)
{
SECURITY_ATTRIBUTES saAttr;
BOOL fSuccess;
HANDLE hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup, hStdout;
// Set the bInheritHandle flag so pipe handles are inherited.
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
// Get the handle to the current STDOUT.
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
// Create a pipe for the child process's STDOUT.
if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0))
return EXIT_FATAL;
// Create noninheritable read handle and close the inheritable read
// handle.
fSuccess =
DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
GetCurrentProcess(), &hChildStdoutRdDup, 0, FALSE,
DUPLICATE_SAME_ACCESS);
if (!fSuccess)
return EXIT_FATAL;
CloseHandle(hChildStdoutRd);
// Now create the child process.
STARTUPINFO siStartInfo;
BOOL bFuncRetn = FALSE;
// Set up members of the PROCESS_INFORMATION structure.
ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
// Set up members of the STARTUPINFO structure.
ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdError = hChildStdoutWr;
siStartInfo.hStdOutput = hChildStdoutWr;
siStartInfo.dwFlags = STARTF_USESTDHANDLES;
TCHAR *cmd_dup;
if (flag == NULL) {
cmd_dup = _tcsdup(cmd);
} else {
cmd_dup =
(TCHAR *) malloc((_tcslen(cmd) + 2 + _tcslen(flag)) *
sizeof(TCHAR));
_stprintf(cmd_dup, TEXT("%s %s"), cmd, flag);
}
// Create the child process.
if (user_name != NULL) {
if (!logged) {
logged = LogonUser(user_name, // lpszUsername,
domain, // lpszDomain,
password, // lpszPassword,
LOGON32_LOGON_INTERACTIVE, // dwLogonType,
LOGON32_PROVIDER_DEFAULT, // dwLogonProvider,
&user_token); // phToken
if (!logged) {
Error();
return EXIT_FATAL;
}
}
bFuncRetn = CreateProcessAsUser(user_token, // user token
NULL, // application name
cmd_dup, // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
IDLE_PRIORITY_CLASS, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
} else
bFuncRetn = CreateProcess(NULL, // application name
cmd_dup, // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
IDLE_PRIORITY_CLASS, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
if (bFuncRetn == 0) {
syslog(LOG_INFO, cmd_dup);
Error();
syslog(LOG_INFO, cmd_dup);
return EXIT_FATAL;
}
free(cmd_dup);
CloseHandle(piProcInfo.hThread);
// Close the write end of the pipe before reading from the
// read end of the pipe.
CloseHandle(hChildStdoutWr);
// Read output from the child process.
int fd = _open_osfhandle((long) hChildStdoutRdDup, _O_RDONLY | _O_TEXT);
FILE *child_stdout = _tfdopen(fd, TEXT("rt"));
TCHAR buffer[1024];
int prefix_length = _tcslen(DAEMON_LOG);
while (_fgetts(buffer, sizeof(buffer) / sizeof(TCHAR), child_stdout) !=
NULL) {
if (!_tcsncmp(DAEMON_LOG, buffer, prefix_length))
syslog(LOG_INFO, buffer + prefix_length);
}
fclose(child_stdout);
DWORD ret;
GetExitCodeProcess(piProcInfo.hProcess, &ret);
CloseHandle(piProcInfo.hProcess);
return ret;
}
static void openlog(TCHAR * ident, int logstat, int logfac)
{
}
static void closelog()
{
}
#else
static pid_t child_pid;
static int change_uid(const char *username)
{
struct passwd *passwd;
passwd = getpwnam(username);
if (passwd == NULL)
return -1;
return setuid(passwd->pw_uid);
}
static void drop_privileges(void)
{
if (change_uid(DAEMON_USER) < 0)
change_uid("nobody");
}
static void forward_signal(int sig)
{
if (child_pid != 0)
kill(child_pid, sig);
signal(sig, SIG_DFL);
raise(sig);
}
static void init_random_sleep(void)
{
srandom(time(NULL) ^ getpid());
}
static void random_sleep(int nb_seconds)
{
if (nfs_delay) {
struct timespec sleep_time;
sleep_time.tv_nsec = random() % 1000000000;
sleep_time.tv_sec = random() % nb_seconds;
nanosleep(&sleep_time, NULL);
}
}
static void daemonize(void)
{
pid_t pid;
int fd;
if (getppid() == 1)
return; /* already a daemon */
pid = fork();
if (pid < 0)
exit(EXIT_FAILURE);
if (pid > 0)
exit(EXIT_SUCCESS);
/* child (daemon) continues */
setsid(); /* obtain a new process group */
umask(027); /* set newly created file permissions */
for (fd = 0; fd < 3; fd++)
close(fd); /* close all descriptors */
fd = open("/dev/null", O_RDWR); /* STDIN */
if (fd < 0)
return;
dup(fd); /* STDOUT */
dup(fd); /* STDERR */
}
static void change_to_daemon_dir(void)
{
char buffer[PATH_MAX];
int length;
char *last_slash;
length = readlink("/proc/self/exe", buffer, sizeof(buffer));
if (length < 0 || length >= sizeof(buffer))
return;
buffer[length] = '\0';
last_slash = strrchr(buffer, '/');
if (last_slash != NULL)
*last_slash = '\0';
chdir(buffer);
chdir("..");
chdir(DAEMON_DIR);
}
static int execute(const char *cmd, const char *flag)
{
pid_t pid;
int fd[2];
if (pipe(fd) < 0)
return EXIT_FATAL;
pid = fork();
if (pid < 0)
return EXIT_FATAL;
if (pid == 0) {
/* Child */
char *args[4];
close(fd[0]);
close(STDOUT_FILENO);
dup2(fd[1], STDOUT_FILENO);
args[0] = (char*) cmd;
args[1] = (char*) (flag ? flag : "");
args[2] = (char*) (nfs_delay ? "-delay" : "");
args[3] = NULL;
execv(cmd, args);
exit(EXIT_FAILURE);
}
{
/* Parent */
int status;
pid_t wait_pid;
char buffer[1024];
FILE *java_out;
int prefix_length = strlen(DAEMON_LOG);
child_pid = pid;
signal(SIGHUP, forward_signal);
signal(SIGINT, forward_signal);
signal(SIGQUIT, forward_signal);
signal(SIGTERM, forward_signal);
close(fd[1]);
java_out = fdopen(fd[0], "r");
if (java_out == NULL) {
kill(child_pid, SIGKILL);
return EXIT_FATAL;
}
while (fgets(buffer, sizeof(buffer), java_out) != NULL) {
if (!strncmp(DAEMON_LOG, buffer, prefix_length)) {
syslog(LOG_INFO, buffer + prefix_length);
}
}
wait_pid = waitpid(pid, &status, 0);
if (wait_pid < 0)
return EXIT_FATAL;
return WEXITSTATUS(status);
}
}
#endif
static daemon_ret_t run_daemon(const TCHAR * cmd)
{
time_t start, end;
int nb_crash = 0;
int java_ret;
const TCHAR *flag = NULL;
change_to_daemon_dir();
init_random_sleep();
for (;;) {
random_sleep(120);
start = time(NULL);
if (start < 0) {
return DAEMON_TIME_ERROR;
}
java_ret = execute(cmd, flag);
syslog(LOG_INFO, TEXT("JVM stopped"));
switch (java_ret) {
case EXIT_OK:
flag = NULL;
continue;
case EXIT_FATAL:
return DAEMON_JVM_EXIT_FATAL;
case EXIT_NEXT_RUN:
flag = TEXT("-n");
continue;
default:
flag = NULL;
/* Record the timestamp, restart */
break;
}
/* The limitation on the number of restarts is disabled now */
random_sleep(120);
continue;
end = time(NULL);
if (end < 0) {
return DAEMON_TIME_ERROR;
}
if (end - start < ACCEPTABLE_CRASH_DELAY) {
nb_crash++;
if (nb_crash >= MAX_CRASH_COUNT) {
return DAEMON_JVM_KEEPS_CRASHING;
}
} else
nb_crash = 0;
}
return DAEMON_UNKNOWN_ERROR;
}
static void init_logging(void)
{
openlog(DAEMON_NAME, 0, LOG_DAEMON);
}
void p2p_daemon(int argc, TCHAR * argv[])
{
daemon_ret_t ret;
init_logging();
ret = run_daemon(DEFAULT_PRG);
switch (ret) {
case DAEMON_TIME_ERROR:
syslog(LOG_NOTICE,
TEXT("Unknown problem with the time() function, leaving"));
break;
case DAEMON_JVM_KEEPS_CRASHING:
syslog(LOG_NOTICE, TEXT("The JVM keeps crashing, leaving"));
break;
case DAEMON_JVM_EXIT_FATAL:
syslog(LOG_NOTICE, TEXT("The JVM exited, leaving"));
break;
case DAEMON_WRONG_PARAM:
syslog(LOG_NOTICE, TEXT("Wrong number of parameters, leaving"));
break;
default:
syslog(LOG_NOTICE, TEXT("Unknown error, leaving"));
break;
}
closelog();
}
#ifndef WIN32
static void set_nfs_delay(int argc, char *argv[])
{
int i;
for (i = 0; i < argc; i++)
if (!strcmp(argv[i], "-delay"))
nfs_delay = 1;
}
int main(int argc, char *argv[])
{
change_to_daemon_dir();
drop_privileges();
daemonize();
set_nfs_delay(argc, argv);
p2p_daemon(argc, argv);
return EXIT_FAILURE;
}
#endif
<commit_msg>Plug FD leak<commit_after>#ifdef WIN32
#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <fcntl.h>
#include <io.h>
#define UNUSED 0xDEADBEEF
#define LOG_DAEMON UNUSED
void syslog(int pri, const TCHAR * msg);
#else
#include <unistd.h> /* fork(), execl(), readlink(), chdir(), ... */
#include <sys/types.h> /* pid_t */
#include <sys/wait.h> /* WEXITSTATUS(), waitpid() */
#include <sys/stat.h> /* umask() */
#include <syslog.h>
#include <stdlib.h> /* system(), exit(), EXIT_... */
#include <string.h> /* strrchr() */
#include <fcntl.h> /* open(), O_RDWR */
#include <limits.h> /* PATH_MAX */
#include <signal.h> /* signal(), kill(), raise(), SIG... */
#include <stdio.h> /* FILE, fgets(), fdopen() */
#include <pwd.h> /* getpwnam() */
static int nfs_delay;
#endif
#include <time.h>
#include "proactivep2p.h"
/*
* If the jvm crashes in less than one minute, three times, there is a problem,
* we shut down the daemon. This is disabled for now, because there is a delay
* during the restart, and every crashing events we encountered would disappear
* after some delay.
*/
#define ACCEPTABLE_CRASH_DELAY 60
#define MAX_CRASH_COUNT 3
typedef enum {
DAEMON_TIME_ERROR,
DAEMON_JVM_KEEPS_CRASHING,
DAEMON_JVM_EXIT_FATAL,
DAEMON_WRONG_PARAM,
DAEMON_UNKNOWN_ERROR,
} daemon_ret_t;
/*
* Exit codes : 0 => OK, restart the daemon
* 220 => Error, don't restart
* 2 => Restart but wait for the next period
* other => Error, restart
*
* These exit codes must be synchronized with the Java code
*/
#define EXIT_OK 0
#define EXIT_FATAL 220
#define EXIT_NEXT_RUN 2
#ifdef WIN32
static void daemonize(void)
{
}
static void init_random_sleep(void)
{
/* TODO */
}
static void random_sleep(int nb_seconds
{
/* TODO */
}
static void symbolink_link_cd(const TCHAR * filename)
{
TCHAR buffer[MAX_PATH];
FILE *file;
file = _tfopen(filename, TEXT("rt"));
if (file == NULL)
return;
if (_fgetts(buffer, sizeof(buffer) / sizeof(TCHAR), file) != NULL) {
SetCurrentDirectory(buffer);
}
fclose(file);
}
static void change_to_daemon_dir(void)
{
TCHAR szDllName[_MAX_PATH];
TCHAR szApp[_MAX_PATH * 2];
int i, len;
GetModuleFileName(0, szDllName, _MAX_PATH);
len = wcslen(szDllName);
wcscpy(szApp, szDllName);
for (i = len - 1; i > 0; i--) {
if (szApp[i] == '\\') {
szApp[i + 1] = 0;
break;
}
}
SetCurrentDirectory(szApp);
symbolink_link_cd(DAEMON_DIR);
}
static PROCESS_INFORMATION piProcInfo;
extern TCHAR *user_name;
extern TCHAR *domain;
extern TCHAR *password;
static BOOL logged = FALSE;
static HANDLE user_token;
static int execute(const TCHAR * cmd, const TCHAR * flag)
{
SECURITY_ATTRIBUTES saAttr;
BOOL fSuccess;
HANDLE hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup, hStdout;
// Set the bInheritHandle flag so pipe handles are inherited.
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
// Get the handle to the current STDOUT.
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
// Create a pipe for the child process's STDOUT.
if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0))
return EXIT_FATAL;
// Create noninheritable read handle and close the inheritable read
// handle.
fSuccess =
DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
GetCurrentProcess(), &hChildStdoutRdDup, 0, FALSE,
DUPLICATE_SAME_ACCESS);
if (!fSuccess)
return EXIT_FATAL;
CloseHandle(hChildStdoutRd);
// Now create the child process.
STARTUPINFO siStartInfo;
BOOL bFuncRetn = FALSE;
// Set up members of the PROCESS_INFORMATION structure.
ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
// Set up members of the STARTUPINFO structure.
ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdError = hChildStdoutWr;
siStartInfo.hStdOutput = hChildStdoutWr;
siStartInfo.dwFlags = STARTF_USESTDHANDLES;
TCHAR *cmd_dup;
if (flag == NULL) {
cmd_dup = _tcsdup(cmd);
} else {
cmd_dup =
(TCHAR *) malloc((_tcslen(cmd) + 2 + _tcslen(flag)) *
sizeof(TCHAR));
_stprintf(cmd_dup, TEXT("%s %s"), cmd, flag);
}
// Create the child process.
if (user_name != NULL) {
if (!logged) {
logged = LogonUser(user_name, // lpszUsername,
domain, // lpszDomain,
password, // lpszPassword,
LOGON32_LOGON_INTERACTIVE, // dwLogonType,
LOGON32_PROVIDER_DEFAULT, // dwLogonProvider,
&user_token); // phToken
if (!logged) {
Error();
return EXIT_FATAL;
}
}
bFuncRetn = CreateProcessAsUser(user_token, // user token
NULL, // application name
cmd_dup, // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
IDLE_PRIORITY_CLASS, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
} else
bFuncRetn = CreateProcess(NULL, // application name
cmd_dup, // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
IDLE_PRIORITY_CLASS, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
if (bFuncRetn == 0) {
syslog(LOG_INFO, cmd_dup);
Error();
syslog(LOG_INFO, cmd_dup);
return EXIT_FATAL;
}
free(cmd_dup);
CloseHandle(piProcInfo.hThread);
// Close the write end of the pipe before reading from the
// read end of the pipe.
CloseHandle(hChildStdoutWr);
// Read output from the child process.
int fd = _open_osfhandle((long) hChildStdoutRdDup, _O_RDONLY | _O_TEXT);
FILE *child_stdout = _tfdopen(fd, TEXT("rt"));
TCHAR buffer[1024];
int prefix_length = _tcslen(DAEMON_LOG);
while (_fgetts(buffer, sizeof(buffer) / sizeof(TCHAR), child_stdout) !=
NULL) {
if (!_tcsncmp(DAEMON_LOG, buffer, prefix_length))
syslog(LOG_INFO, buffer + prefix_length);
}
fclose(child_stdout);
DWORD ret;
GetExitCodeProcess(piProcInfo.hProcess, &ret);
CloseHandle(piProcInfo.hProcess);
return ret;
}
static void openlog(TCHAR * ident, int logstat, int logfac)
{
}
static void closelog()
{
}
#else
static pid_t child_pid;
static int change_uid(const char *username)
{
struct passwd *passwd;
passwd = getpwnam(username);
if (passwd == NULL)
return -1;
return setuid(passwd->pw_uid);
}
static void drop_privileges(void)
{
if (change_uid(DAEMON_USER) < 0)
change_uid("nobody");
}
static void forward_signal(int sig)
{
if (child_pid != 0)
kill(child_pid, sig);
signal(sig, SIG_DFL);
raise(sig);
}
static void init_random_sleep(void)
{
srandom(time(NULL) ^ getpid());
}
static void random_sleep(int nb_seconds)
{
if (nfs_delay) {
struct timespec sleep_time;
sleep_time.tv_nsec = random() % 1000000000;
sleep_time.tv_sec = random() % nb_seconds;
nanosleep(&sleep_time, NULL);
}
}
static void daemonize(void)
{
pid_t pid;
int fd;
if (getppid() == 1)
return; /* already a daemon */
pid = fork();
if (pid < 0)
exit(EXIT_FAILURE);
if (pid > 0)
exit(EXIT_SUCCESS);
/* child (daemon) continues */
setsid(); /* obtain a new process group */
umask(027); /* set newly created file permissions */
for (fd = 0; fd < 3; fd++)
close(fd); /* close all descriptors */
fd = open("/dev/null", O_RDWR); /* STDIN */
if (fd < 0)
return;
dup(fd); /* STDOUT */
dup(fd); /* STDERR */
}
static void change_to_daemon_dir(void)
{
char buffer[PATH_MAX];
int length;
char *last_slash;
length = readlink("/proc/self/exe", buffer, sizeof(buffer));
if (length < 0 || length >= sizeof(buffer))
return;
buffer[length] = '\0';
last_slash = strrchr(buffer, '/');
if (last_slash != NULL)
*last_slash = '\0';
chdir(buffer);
chdir("..");
chdir(DAEMON_DIR);
}
static int execute(const char *cmd, const char *flag)
{
pid_t pid;
int fd[2];
if (pipe(fd) < 0)
return EXIT_FATAL;
pid = fork();
if (pid < 0) {
close(fd[0]);
close(fd[1]);
return EXIT_FATAL;
}
if (pid == 0) {
/* Child */
char *args[4];
close(fd[0]);
close(STDOUT_FILENO);
dup2(fd[1], STDOUT_FILENO);
args[0] = (char*) cmd;
args[1] = (char*) (flag ? flag : "");
args[2] = (char*) (nfs_delay ? "-delay" : "");
args[3] = NULL;
execv(cmd, args);
exit(EXIT_FAILURE);
}
{
/* Parent */
int status;
pid_t wait_pid;
char buffer[1024];
FILE *java_out;
int prefix_length = strlen(DAEMON_LOG);
child_pid = pid;
signal(SIGHUP, forward_signal);
signal(SIGINT, forward_signal);
signal(SIGQUIT, forward_signal);
signal(SIGTERM, forward_signal);
close(fd[1]);
java_out = fdopen(fd[0], "r");
if (java_out == NULL) {
kill(child_pid, SIGKILL);
close(fd[0]);
return EXIT_FATAL;
}
while (fgets(buffer, sizeof(buffer), java_out) != NULL) {
if (!strncmp(DAEMON_LOG, buffer, prefix_length)) {
syslog(LOG_INFO, buffer + prefix_length);
}
}
wait_pid = waitpid(pid, &status, 0);
close(fd[0]);
if (wait_pid < 0)
return EXIT_FATAL;
return WEXITSTATUS(status);
}
}
#endif
static daemon_ret_t run_daemon(const TCHAR * cmd)
{
time_t start, end;
int nb_crash = 0;
int java_ret;
const TCHAR *flag = NULL;
change_to_daemon_dir();
init_random_sleep();
for (;;) {
random_sleep(120);
start = time(NULL);
if (start < 0) {
return DAEMON_TIME_ERROR;
}
java_ret = execute(cmd, flag);
syslog(LOG_INFO, TEXT("JVM stopped"));
switch (java_ret) {
case EXIT_OK:
flag = NULL;
continue;
case EXIT_FATAL:
return DAEMON_JVM_EXIT_FATAL;
case EXIT_NEXT_RUN:
flag = TEXT("-n");
continue;
default:
flag = NULL;
/* Record the timestamp, restart */
break;
}
/* The limitation on the number of restarts is disabled now */
random_sleep(120);
continue;
end = time(NULL);
if (end < 0) {
return DAEMON_TIME_ERROR;
}
if (end - start < ACCEPTABLE_CRASH_DELAY) {
nb_crash++;
if (nb_crash >= MAX_CRASH_COUNT) {
return DAEMON_JVM_KEEPS_CRASHING;
}
} else
nb_crash = 0;
}
return DAEMON_UNKNOWN_ERROR;
}
static void init_logging(void)
{
openlog(DAEMON_NAME, 0, LOG_DAEMON);
}
void p2p_daemon(int argc, TCHAR * argv[])
{
daemon_ret_t ret;
init_logging();
ret = run_daemon(DEFAULT_PRG);
switch (ret) {
case DAEMON_TIME_ERROR:
syslog(LOG_NOTICE,
TEXT("Unknown problem with the time() function, leaving"));
break;
case DAEMON_JVM_KEEPS_CRASHING:
syslog(LOG_NOTICE, TEXT("The JVM keeps crashing, leaving"));
break;
case DAEMON_JVM_EXIT_FATAL:
syslog(LOG_NOTICE, TEXT("The JVM exited, leaving"));
break;
case DAEMON_WRONG_PARAM:
syslog(LOG_NOTICE, TEXT("Wrong number of parameters, leaving"));
break;
default:
syslog(LOG_NOTICE, TEXT("Unknown error, leaving"));
break;
}
closelog();
}
#ifndef WIN32
static void set_nfs_delay(int argc, char *argv[])
{
int i;
for (i = 0; i < argc; i++)
if (!strcmp(argv[i], "-delay"))
nfs_delay = 1;
}
int main(int argc, char *argv[])
{
change_to_daemon_dir();
drop_privileges();
daemonize();
set_nfs_delay(argc, argv);
p2p_daemon(argc, argv);
return EXIT_FAILURE;
}
#endif
<|endoftext|> |
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
// show MainWindow (GUI)
ui->setupUi(this);
// display message in GUI
ui->textEdit->insertHtml("Scanning for serial ports... ");
// get a list of available serial ports.
// this is not used in the code and only for demontration.
QList <QextPortInfo> ports = QextSerialEnumerator::getPorts();
ui->textEdit->insertHtml("Done.<br><br>");
// for displaying the number of found ports
n = 1;
foreach (QextPortInfo portInfo, ports)
{
// display found ports in GUI
ui->textEdit->insertHtml(QString("<b><u>Port %1</u></b><br>").arg(n));
showPorts(portInfo);
// n plus 1
n++;
}
ui->textEdit->insertHtml("<br><br>");
// if a USB device is added or removed, call the Slot onPortAddedOrRemoved
enumerator = new QextSerialEnumerator(this);
enumerator->setUpNotifications();
connect(enumerator, SIGNAL(deviceDiscovered(QextPortInfo)), SLOT(onPortAdded(QextPortInfo)));
connect(enumerator, SIGNAL(deviceRemoved(QextPortInfo)), SLOT(onPortRemoved(QextPortInfo)));
//--------------------------------------------------------------------------------------------------
// the settings for the serial port
// Be aware, that the Arduino has to use the same speed (9600 Baud)
PortSettings settings = {BAUD9600, DATA_8, PAR_NONE, STOP_1, FLOW_OFF, 10}; // 10 = timeout in ms
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
// the name of the serial port
// on Windows, this would be i.e. COM5
serialPortName = "/dev/tty.usbmodemfd1411";
//--------------------------------------------------------------------------------------------------
// create the serial port object.
// we get the serial data on the port asynchronously!
port = new QextSerialPort(serialPortName, settings);
// try to open Arduino serial port
initArduino();
}
MainWindow::~MainWindow()
{
delete ui;
delete port;
}
void MainWindow::initArduino()
{
// initialise the serial port
if (openSerialPort() == false)
{
// ERROR !!
return;
}
// display message in GUI
ui->textEdit->insertHtml("<b>Sending data to Arduino in some seconds (arduinoInit)...</b><br>");
// Special timer, needed for Arduino!
//
// Reason:
// When the serial (USB) port is opened, the Arduino is not ready for serial communication immediately.
// Therefore we start a timer. After 3000 ms (3 seconds), it will call the function arduinoInit().
// This can then be used for a first command to the Arduino, like "Hey Arduino, Qt-Software now startet!".
QTimer::singleShot(3000, this, SLOT(timerSlot()));
}
bool MainWindow::openSerialPort(void)
{
// open the serial port
port->open(QIODevice::ReadWrite | QIODevice::Unbuffered);
// error opening port
if (port->isOpen() == false)
{
// show error message
ui->textEdit->insertHtml(QString("<b>Error opening serial port <i>%1</i>.</b><br>").arg(serialPortName));
return false;
}
// success
return true;
}
void MainWindow::sendValue(int value)
{
QByteArray byte; // byte to sent to the port
qint64 bw = 0; // bytes really written
byte.clear(); // clear buffer to be sent
byte.append(value); // fill buffer with value to be sent
if (port != NULL)
{
// write byte to serial port
bw = port->write(byte);
// show sent data
ui->textEdit->insertHtml(QString("%1 byte(s) written. Written value: %2 (DEC) / %3 (HEX) / %4 (ASCII)<br>").arg(bw).arg(value).arg(value, 0, 16).arg(QChar(value)));
// flush serial port
port->flush();
}
}
void MainWindow::timerSlot()
{
QTime startTime; // For measuring elapsed time while waiting for an answer on the serial port
qint64 ba = 0; // bytes available on the serial port
QByteArray receivedData; // the data received from the serial port
QString str; // a string to show the received data
QChar ch = 0; // the char of the received data
int dec = 0; // the int of the received data
char buf[1024];
// show message
ui->textEdit->insertHtml("<b>Sending!</b><br>");
// send values to Arduino (insert your own initialisation here!)
sendValue('*');
sendValue('r');
sendValue('e');
sendValue('#');
ui->textEdit->insertHtml("<br><b>Waiting for Arduino answer...</b><br><br>");
// just to make sure...
if (port->isOpen() == false)
{
ui->textEdit->insertHtml("ERROR: serial port not opened!");
return;
}
// check if the Arduino sends all data within an wanted time...
startTime.start();
do
{
// how many bytes are available?
ba = port->bytesAvailable();
// position in the string (index!)
n = 0;
// if data available (should _always_ be the case, since this method is called automatically by an event)
if (ba > 0)
{
// read data and convert them to a QString
receivedData = port->readAll();
/*
// read available bytes as char *
n = port->read(buf, ba);
// ERROR
if ((n < ba) || (n == -1))
{
// get the error code
n = port->lastError();
// show error code and message
ui->textEdit->insertHtml(QString("ERROR %1 at readData: %2").arg(n).arg(port->errorString()));
return;
}
// convert from char * to QBytearray - just for convenience
receivedData = QByteArray::fromRawData(buf, sizeof(buf));
*/
// convert from QByteArray to QString - just for convenience
str = QString::fromUtf8(receivedData.constData());
// show received data as QString
ui->textEdit->insertHtml(QString("<em>%1 byte(s) received. ASCII: %2</em><br>").arg(ba).arg(str));
// show each byte
while (n < receivedData.length())
{
// show DEC of each char
//
// convert one byte to QChar
ch = receivedData.at(n);
// convert to int
dec = (int) ch.toAscii();
// show in GUI
ui->textEdit->insertHtml(QString("Byte No.%1: %2 (DEC)<br>").arg(n+1).arg(dec));
// counter +1
n++;
}
}
} while (startTime.elapsed() < serialReadTimout);
}
void MainWindow::onPortAdded(QextPortInfo newPortInfo)
{
// get part of string
// (i.e. looking only for the "usbmodem1451" within "/dev/tty.usbmodem1451")
QStringRef subString = serialPortName.rightRef(serialPortName.lastIndexOf("."));
// scroll to end
ui->textEdit->ensureCursorVisible();
ui->textEdit->insertHtml("<br><b><i>Serial port added!</i></b><br>");
// show ports, with physical name
showPorts(newPortInfo, true);
// Wanted serial port (Arduino) found!
if (newPortInfo.portName.contains(subString))
{
// show success message!
ui->textEdit->insertHtml("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<br>");
ui->textEdit->insertHtml(QString("+++ Yeah, Arduino '%1' found! +++<br>").arg(subString.toString()));
ui->textEdit->insertHtml("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<br><br>");
// try to open Arduino serial port
initArduino();
}
}
void MainWindow::onPortRemoved(QextPortInfo newPortInfo)
{
// scroll to end
ui->textEdit->ensureCursorVisible();
ui->textEdit->insertHtml("<br><b><i>Serial port removed!</i></b><br>");
// show ports
showPorts(newPortInfo);
}
void MainWindow::showPorts(QextPortInfo portInfos, bool added)
{
ui->textEdit->insertHtml(QString("<b>Port name:</b> %1<br>").arg(portInfos.portName));
if (added)
{
ui->textEdit->insertHtml(QString("<b>Physical name:</b> %1<br>").arg(portInfos.physName));
}
ui->textEdit->insertHtml(QString("<b>Friendly name:</b> %1<br>").arg(portInfos.friendName));
ui->textEdit->insertHtml(QString("<b>Enumerator name:</b> %1<br>").arg(portInfos.enumName));
ui->textEdit->insertHtml(QString("<b>Vendor ID:</b> %1<br>").arg(portInfos.vendorID));
ui->textEdit->insertHtml(QString("<b>Product ID:</b> %1<br>").arg(portInfos.productID));
ui->textEdit->insertHtml("<br>");
// scroll to end
ui->textEdit->ensureCursorVisible();
}
<commit_msg>Still testing the read function because this has an error code instead of readAll. Making progress...<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
// show MainWindow (GUI)
ui->setupUi(this);
// display message in GUI
ui->textEdit->insertHtml("Scanning for serial ports... ");
// get a list of available serial ports.
// this is not used in the code and only for demontration.
QList <QextPortInfo> ports = QextSerialEnumerator::getPorts();
ui->textEdit->insertHtml("Done.<br><br>");
// for displaying the number of found ports
n = 1;
foreach (QextPortInfo portInfo, ports)
{
// display found ports in GUI
ui->textEdit->insertHtml(QString("<b><u>Port %1</u></b><br>").arg(n));
showPorts(portInfo);
// n plus 1
n++;
}
ui->textEdit->insertHtml("<br><br>");
// if a USB device is added or removed, call the Slot onPortAddedOrRemoved
enumerator = new QextSerialEnumerator(this);
enumerator->setUpNotifications();
connect(enumerator, SIGNAL(deviceDiscovered(QextPortInfo)), SLOT(onPortAdded(QextPortInfo)));
connect(enumerator, SIGNAL(deviceRemoved(QextPortInfo)), SLOT(onPortRemoved(QextPortInfo)));
//--------------------------------------------------------------------------------------------------
// the settings for the serial port
// Be aware, that the Arduino has to use the same speed (9600 Baud)
PortSettings settings = {BAUD9600, DATA_8, PAR_NONE, STOP_1, FLOW_OFF, 10}; // 10 = timeout in ms
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
// the name of the serial port
// on Windows, this would be i.e. COM5
serialPortName = "/dev/tty.usbmodemfd1411";
//--------------------------------------------------------------------------------------------------
// create the serial port object.
// we get the serial data on the port asynchronously!
port = new QextSerialPort(serialPortName, settings);
// try to open Arduino serial port
initArduino();
}
MainWindow::~MainWindow()
{
delete ui;
delete port;
}
void MainWindow::initArduino()
{
// initialise the serial port
if (openSerialPort() == false)
{
// ERROR !!
return;
}
// display message in GUI
ui->textEdit->insertHtml("<b>Sending data to Arduino in some seconds (arduinoInit)...</b> ");
// Special timer, needed for Arduino!
//
// Reason:
// When the serial (USB) port is opened, the Arduino is not ready for serial communication immediately.
// Therefore we start a timer. After 3000 ms (3 seconds), it will call the function arduinoInit().
// This can then be used for a first command to the Arduino, like "Hey Arduino, Qt-Software now startet!".
QTimer::singleShot(3000, this, SLOT(timerSlot()));
}
bool MainWindow::openSerialPort(void)
{
// open the serial port
port->open(QIODevice::ReadWrite | QIODevice::Unbuffered);
// error opening port
if (port->isOpen() == false)
{
// show error message
ui->textEdit->insertHtml(QString("<b>Error opening serial port <i>%1</i>.</b><br>").arg(serialPortName));
return false;
}
// success
return true;
}
void MainWindow::sendValue(int value)
{
QByteArray byte; // byte to sent to the port
qint64 bw = 0; // bytes really written
byte.clear(); // clear buffer to be sent
byte.append(value); // fill buffer with value to be sent
if (port != NULL)
{
// write byte to serial port
bw = port->write(byte);
// show sent data
ui->textEdit->insertHtml(QString("%1 byte(s) written. Written value: %2 (DEC) / %3 (HEX) / %4 (ASCII)<br>").arg(bw).arg(value).arg(value, 0, 16).arg(QChar(value)));
// flush serial port
port->flush();
}
}
void MainWindow::timerSlot()
{
QTime startTime; // For measuring elapsed time while waiting for an answer on the serial port
qint64 ba = 0; // bytes available on the serial port
QByteArray receivedData; // the data received from the serial port
QString str; // a string to show the received data
QChar ch = 0; // the char of the received data
int dec = 0; // the int of the received data
qint64 bytesRead = 0;
char buf[1024];
// show message
ui->textEdit->insertHtml("<b>Sending!</b><br><br>");
// send values to Arduino (insert your own initialisation here!)
sendValue('*');
sendValue('r');
sendValue('e');
sendValue('#');
ui->textEdit->insertHtml("<br><b>Waiting for Arduino answer...</b><br><br>");
// just to make sure...
if (port->isOpen() == false)
{
ui->textEdit->insertHtml("ERROR: serial port not opened!");
return;
}
// check if the Arduino sends all data within an wanted time...
startTime.start();
do
{
// how many bytes are available?
ba = port->bytesAvailable();
// show message
ui->textEdit->insertHtml(QString("%1 byte(s) available<br>").arg(ba));
// if data available (should _always_ be the case, since this method is called automatically by an event)
if (ba > 0)
{
// read data and convert them to a QString
// receivedData = port->readAll();
// read a maximum of 'ba' available bytes into the buffer as char *
bytesRead = port->read(buf, ba);
/*
// ERROR
if ((bytesRead < ba) || (bytesRead == -1))
{
// show error code and message
ui->textEdit->insertHtml(QString("ERROR %1 at readData: %2").arg(bytesRead).arg(port->errorString()));
return;
}
*/
// convert from char * to QBytearray - just for convenience
receivedData = QByteArray::fromRawData(buf, bytesRead);
// convert from QByteArray to QString - just for convenience
str = QString::fromUtf8(receivedData.constData());
// show received data as QString
ui->textEdit->insertHtml(QString("<em>%1 byte(s) received. ASCII: %2</em><br>").arg(bytesRead).arg(str));
// position in the string (index!)
n = 0;
// show each byte
while (n < bytesRead)
{
// show DEC of each char
//
// convert one byte to QChar
ch = receivedData.at(n);
// convert to int
dec = (int) ch.toAscii();
// show in GUI
ui->textEdit->insertHtml(QString("Byte No.%1: %2 (DEC)<br>").arg(n+1).arg(dec));
// counter +1
n++;
}
}
} while (startTime.elapsed() < serialReadTimout);
}
void MainWindow::onPortAdded(QextPortInfo newPortInfo)
{
// get part of string
// (i.e. looking only for the "usbmodem1451" within "/dev/tty.usbmodem1451")
QStringRef subString = serialPortName.rightRef(serialPortName.lastIndexOf("."));
// scroll to end
ui->textEdit->ensureCursorVisible();
ui->textEdit->insertHtml("<br><b><i>Serial port added!</i></b><br>");
// show ports, with physical name
showPorts(newPortInfo, true);
// Wanted serial port (Arduino) found!
if (newPortInfo.portName.contains(subString))
{
// show success message!
ui->textEdit->insertHtml("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<br>");
ui->textEdit->insertHtml(QString("+++ Yeah, Arduino '%1' found! +++<br>").arg(subString.toString()));
ui->textEdit->insertHtml("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<br><br>");
// try to open Arduino serial port
initArduino();
}
}
void MainWindow::onPortRemoved(QextPortInfo newPortInfo)
{
// scroll to end
ui->textEdit->ensureCursorVisible();
ui->textEdit->insertHtml("<br><b><i>Serial port removed!</i></b><br>");
// show ports
showPorts(newPortInfo);
}
void MainWindow::showPorts(QextPortInfo portInfos, bool added)
{
ui->textEdit->insertHtml(QString("<b>Port name:</b> %1<br>").arg(portInfos.portName));
if (added)
{
ui->textEdit->insertHtml(QString("<b>Physical name:</b> %1<br>").arg(portInfos.physName));
}
ui->textEdit->insertHtml(QString("<b>Friendly name:</b> %1<br>").arg(portInfos.friendName));
ui->textEdit->insertHtml(QString("<b>Enumerator name:</b> %1<br>").arg(portInfos.enumName));
ui->textEdit->insertHtml(QString("<b>Vendor ID:</b> %1<br>").arg(portInfos.vendorID));
ui->textEdit->insertHtml(QString("<b>Product ID:</b> %1<br>").arg(portInfos.productID));
ui->textEdit->insertHtml("<br>");
// scroll to end
ui->textEdit->ensureCursorVisible();
}
<|endoftext|> |
<commit_before>#include <QtNetwork/QNetworkReply>
#include <QtWidgets>
#include <QtCore>
#include <libethereum/Dagger.h>
#include <libethereum/Client.h>
#include "MainWin.h"
#include "ui_Main.h"
using namespace std;
using namespace eth;
static void initUnits(QComboBox* _b)
{
for (int n = units().size() - 1; n >= 0; --n)
_b->addItem(QString::fromStdString(units()[n].second), n);
_b->setCurrentIndex(6);
}
#define ADD_QUOTES_HELPER(s) #s
#define ADD_QUOTES(s) ADD_QUOTES_HELPER(s)
Main::Main(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Main)
{
setWindowFlags(Qt::Window);
ui->setupUi(this);
g_logPost = [=](std::string const& s, char const*) { ui->log->addItem(QString::fromStdString(s)); };
m_client = new Client("AlethZero");
readSettings();
refresh();
m_refresh = new QTimer(this);
connect(m_refresh, SIGNAL(timeout()), SLOT(refresh()));
m_refresh->start(1000);
#if ETH_DEBUG
m_servers.append("192.168.0.10:30301");
#else
connect(&m_webCtrl, &QNetworkAccessManager::finished, [&](QNetworkReply* _r)
{
m_servers = QString::fromUtf8(_r->readAll()).split("\n", QString::SkipEmptyParts);
});
QNetworkRequest r(QUrl("http://www.ethereum.org/servers.poc2.txt"));
r.setHeader(QNetworkRequest::UserAgentHeader, "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1712.0 Safari/537.36");
m_webCtrl.get(r);
srand(time(0));
#endif
on_verbosity_sliderMoved();
initUnits(ui->valueUnits);
statusBar()->addPermanentWidget(ui->balance);
statusBar()->addPermanentWidget(ui->peerCount);
statusBar()->addPermanentWidget(ui->blockChain);
}
Main::~Main()
{
g_logPost = simpleDebugOut;
writeSettings();
delete ui;
}
void Main::on_about_triggered()
{
QMessageBox::about(this, "About AlethZero PoC-2", "AlethZero/v" ADD_QUOTES(ETH_VERSION) "/" ADD_QUOTES(ETH_BUILD_TYPE) "/" ADD_QUOTES(ETH_BUILD_PLATFORM) "\nBy Gav Wood, 2014.\nBased on a design by Vitalik Buterin.\n\nTeam Ethereum++ includes: Eric Lombrozo, Marko Simovic, Alex Leverington and several others.");
}
void Main::writeSettings()
{
QSettings s("ethereum", "alethzero");
QByteArray b;
b.resize(sizeof(Secret) * m_myKeys.size());
auto p = b.data();
for (auto i: m_myKeys)
{
memcpy(p, &(i.secret()), sizeof(Secret));
p += sizeof(Secret);
}
s.setValue("address", b);
s.setValue("upnp", ui->upnp->isChecked());
s.setValue("clientName", ui->clientName->text());
s.setValue("idealPeers", ui->idealPeers->value());
s.setValue("port", ui->port->value());
if (m_client->peerServer())
{
bytes d = m_client->peerServer()->savePeers();
m_peers = QByteArray((char*)d.data(), d.size());
}
s.setValue("peers", m_peers);
s.setValue("geometry", saveGeometry());
}
void Main::readSettings()
{
QSettings s("ethereum", "alethzero");
restoreGeometry(s.value("geometry").toByteArray());
QByteArray b = s.value("address").toByteArray();
if (b.isEmpty())
m_myKeys.append(KeyPair::create());
else
{
h256 k;
for (unsigned i = 0; i < b.size() / sizeof(Secret); ++i)
{
memcpy(&k, b.data() + i * sizeof(Secret), sizeof(Secret));
m_myKeys.append(KeyPair(k));
}
}
m_client->setAddress(m_myKeys.back().address());
m_peers = s.value("peers").toByteArray();
ui->upnp->setChecked(s.value("upnp", true).toBool());
ui->clientName->setText(s.value("clientName", "").toString());
ui->idealPeers->setValue(s.value("idealPeers", ui->idealPeers->value()).toInt());
ui->port->setValue(s.value("port", ui->port->value()).toInt());
}
void Main::refresh()
{
m_client->lock();
//if (m_client->changed())
{
ui->peerCount->setText(QString::fromStdString(toString(m_client->peerCount())) + " peer(s)");
ui->peers->clear();
for (PeerInfo const& i: m_client->peers())
ui->peers->addItem(QString("%3 ms - %1:%2 - %4").arg(i.host.c_str()).arg(i.port).arg(chrono::duration_cast<chrono::milliseconds>(i.lastPing).count()).arg(i.clientVersion.c_str()));
auto d = m_client->blockChain().details();
auto diff = BlockInfo(m_client->blockChain().block()).difficulty;
ui->blockChain->setText(QString("#%1 @%3 T%2").arg(d.number).arg(toLog2(d.totalDifficulty)).arg(toLog2(diff)));
auto acs = m_client->state().addresses();
ui->accounts->clear();
for (auto i: acs)
ui->accounts->addItem(QString("%1 @ %2").arg(formatBalance(i.second).c_str()).arg(asHex(i.first.asArray()).c_str()));
ui->transactionQueue->clear();
for (pair<h256, bytes> const& i: m_client->transactionQueue().transactions())
{
Transaction t(i.second);
ui->transactionQueue->addItem(QString("%1 @ %2 <- %3")
.arg(formatBalance(t.value).c_str())
.arg(asHex(t.receiveAddress.asArray()).c_str())
.arg(asHex(t.sender().asArray()).c_str()) );
}
ui->transactions->clear();
auto const& bc = m_client->blockChain();
for (auto h = bc.currentHash(); h != bc.genesisHash(); h = bc.details(h).parent)
{
auto d = bc.details(h);
ui->transactions->addItem(QString("# %1 ==== %2").arg(d.number).arg(asHex(h.asArray()).c_str()));
for (auto const& i: RLP(bc.block(h))[1])
{
Transaction t(i.data());
ui->transactions->addItem(QString("%1 @ %2 <- %3")
.arg(formatBalance(t.value).c_str())
.arg(asHex(t.receiveAddress.asArray()).c_str())
.arg(asHex(t.sender().asArray()).c_str()) );
}
}
}
ui->ourAccounts->clear();
u256 totalBalance = 0;
for (auto i: m_myKeys)
{
u256 b = m_client->state().balance(i.address());
ui->ourAccounts->addItem(QString("%1 @ %2").arg(formatBalance(b).c_str()).arg(asHex(i.address().asArray()).c_str()));
totalBalance += b;
}
ui->balance->setText(QString::fromStdString(formatBalance(totalBalance)));
m_client->unlock();
}
void Main::on_idealPeers_valueChanged()
{
if (m_client->peerServer())
m_client->peerServer()->setIdealPeerCount(ui->idealPeers->value());
}
void Main::on_ourAccounts_doubleClicked()
{
qApp->clipboard()->setText(ui->ourAccounts->currentItem()->text().section(" @ ", 1));
}
void Main::on_log_doubleClicked()
{
qApp->clipboard()->setText(ui->log->currentItem()->text());
}
void Main::on_accounts_doubleClicked()
{
qApp->clipboard()->setText(ui->accounts->currentItem()->text().section(" @ ", 1));
}
void Main::on_destination_textChanged()
{
updateFee();
}
void Main::on_data_textChanged()
{
m_data = ui->data->toPlainText().split(QRegExp("[^0-9a-fA-Fx]+"), QString::SkipEmptyParts);
updateFee();
}
u256 Main::fee() const
{
return (ui->destination->text().isEmpty() || !ui->destination->text().toInt()) ? m_client->state().fee(m_data.size()) : m_client->state().fee();
}
u256 Main::value() const
{
return ui->value->value() * units()[units().size() - 1 - ui->valueUnits->currentIndex()].first;
}
u256 Main::total() const
{
return value() + fee();
}
void Main::updateFee()
{
ui->fee->setText(QString("(fee: %1)").arg(formatBalance(fee()).c_str()));
auto totalReq = total();
ui->total->setText(QString("Total: %1").arg(formatBalance(totalReq).c_str()));
bool ok = false;
for (auto i: m_myKeys)
if (m_client->state().balance(i.address()) >= totalReq)
{
ok = true;
break;
}
ui->send->setEnabled(ok);
QPalette p = ui->total->palette();
p.setColor(QPalette::WindowText, QColor(ok ? 0x00 : 0x80, 0x00, 0x00));
ui->total->setPalette(p);
}
void Main::on_net_triggered()
{
ui->port->setEnabled(!ui->net->isChecked());
ui->clientName->setEnabled(!ui->net->isChecked());
string n = "AlethZero/v" ADD_QUOTES(ETH_VERSION);
if (ui->clientName->text().size())
n += "/" + ui->clientName->text().toStdString();
n += "/" ADD_QUOTES(ETH_BUILD_TYPE) "/" ADD_QUOTES(ETH_BUILD_PLATFORM);
m_client->setClientVersion(n);
if (ui->net->isChecked())
{
m_client->startNetwork(ui->port->value(), string(), 0, NodeMode::Full, ui->idealPeers->value(), std::string(), ui->upnp->isChecked());
if (m_peers.size())
m_client->peerServer()->restorePeers(bytesConstRef((byte*)m_peers.data(), m_peers.size()));
}
else
m_client->stopNetwork();
}
void Main::on_connect_triggered()
{
if (!ui->net->isChecked())
{
ui->net->setChecked(true);
on_net_triggered();
}
bool ok = false;
QString s = QInputDialog::getItem(this, "Connect to a Network Peer", "Enter a peer to which a connection may be made:", m_servers, m_servers.count() ? rand() % m_servers.count() : 0, true, &ok);
if (ok && s.contains(":"))
{
string host = s.section(":", 0, 0).toStdString();
short port = s.section(":", 1).toInt();
m_client->connect(host, port);
}
}
void Main::on_verbosity_sliderMoved()
{
g_logVerbosity = ui->verbosity->value();
}
void Main::on_mine_triggered()
{
if (ui->mine->isChecked())
{
m_client->setAddress(m_myKeys.last().address());
m_client->startMining();
}
else
m_client->stopMining();
}
void Main::on_send_clicked()
{
u256 totalReq = value() + fee();
m_client->lock();
for (auto i: m_myKeys)
if (m_client->state().balance(i.address()) >= totalReq)
{
m_client->unlock();
Secret s = m_myKeys.front().secret();
Address r = Address(fromUserHex(ui->destination->text().toStdString()));
u256s data;
data.reserve(m_data.size());
for (QString const& i: m_data)
data.push_back(u256(i.toStdString()));
m_client->transact(s, r, value(), data);
refresh();
return;
}
m_client->unlock();
statusBar()->showMessage("Couldn't make transaction: no single account contains at least the required amount.");
}
void Main::on_create_triggered()
{
m_myKeys.append(KeyPair::create());
}
<commit_msg>bug: send wei not using selected address<commit_after>#include <QtNetwork/QNetworkReply>
#include <QtWidgets>
#include <QtCore>
#include <libethereum/Dagger.h>
#include <libethereum/Client.h>
#include "MainWin.h"
#include "ui_Main.h"
using namespace std;
using namespace eth;
static void initUnits(QComboBox* _b)
{
for (int n = units().size() - 1; n >= 0; --n)
_b->addItem(QString::fromStdString(units()[n].second), n);
_b->setCurrentIndex(6);
}
#define ADD_QUOTES_HELPER(s) #s
#define ADD_QUOTES(s) ADD_QUOTES_HELPER(s)
Main::Main(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Main)
{
setWindowFlags(Qt::Window);
ui->setupUi(this);
g_logPost = [=](std::string const& s, char const*) { ui->log->addItem(QString::fromStdString(s)); };
m_client = new Client("AlethZero");
readSettings();
refresh();
m_refresh = new QTimer(this);
connect(m_refresh, SIGNAL(timeout()), SLOT(refresh()));
m_refresh->start(1000);
#if ETH_DEBUG
m_servers.append("192.168.0.10:30301");
#else
connect(&m_webCtrl, &QNetworkAccessManager::finished, [&](QNetworkReply* _r)
{
m_servers = QString::fromUtf8(_r->readAll()).split("\n", QString::SkipEmptyParts);
});
QNetworkRequest r(QUrl("http://www.ethereum.org/servers.poc2.txt"));
r.setHeader(QNetworkRequest::UserAgentHeader, "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1712.0 Safari/537.36");
m_webCtrl.get(r);
srand(time(0));
#endif
on_verbosity_sliderMoved();
initUnits(ui->valueUnits);
statusBar()->addPermanentWidget(ui->balance);
statusBar()->addPermanentWidget(ui->peerCount);
statusBar()->addPermanentWidget(ui->blockChain);
}
Main::~Main()
{
g_logPost = simpleDebugOut;
writeSettings();
delete ui;
}
void Main::on_about_triggered()
{
QMessageBox::about(this, "About AlethZero PoC-2", "AlethZero/v" ADD_QUOTES(ETH_VERSION) "/" ADD_QUOTES(ETH_BUILD_TYPE) "/" ADD_QUOTES(ETH_BUILD_PLATFORM) "\nBy Gav Wood, 2014.\nBased on a design by Vitalik Buterin.\n\nTeam Ethereum++ includes: Eric Lombrozo, Marko Simovic, Alex Leverington and several others.");
}
void Main::writeSettings()
{
QSettings s("ethereum", "alethzero");
QByteArray b;
b.resize(sizeof(Secret) * m_myKeys.size());
auto p = b.data();
for (auto i: m_myKeys)
{
memcpy(p, &(i.secret()), sizeof(Secret));
p += sizeof(Secret);
}
s.setValue("address", b);
s.setValue("upnp", ui->upnp->isChecked());
s.setValue("clientName", ui->clientName->text());
s.setValue("idealPeers", ui->idealPeers->value());
s.setValue("port", ui->port->value());
if (m_client->peerServer())
{
bytes d = m_client->peerServer()->savePeers();
m_peers = QByteArray((char*)d.data(), d.size());
}
s.setValue("peers", m_peers);
s.setValue("geometry", saveGeometry());
}
void Main::readSettings()
{
QSettings s("ethereum", "alethzero");
restoreGeometry(s.value("geometry").toByteArray());
QByteArray b = s.value("address").toByteArray();
if (b.isEmpty())
m_myKeys.append(KeyPair::create());
else
{
h256 k;
for (unsigned i = 0; i < b.size() / sizeof(Secret); ++i)
{
memcpy(&k, b.data() + i * sizeof(Secret), sizeof(Secret));
m_myKeys.append(KeyPair(k));
}
}
m_client->setAddress(m_myKeys.back().address());
m_peers = s.value("peers").toByteArray();
ui->upnp->setChecked(s.value("upnp", true).toBool());
ui->clientName->setText(s.value("clientName", "").toString());
ui->idealPeers->setValue(s.value("idealPeers", ui->idealPeers->value()).toInt());
ui->port->setValue(s.value("port", ui->port->value()).toInt());
}
void Main::refresh()
{
m_client->lock();
//if (m_client->changed())
{
ui->peerCount->setText(QString::fromStdString(toString(m_client->peerCount())) + " peer(s)");
ui->peers->clear();
for (PeerInfo const& i: m_client->peers())
ui->peers->addItem(QString("%3 ms - %1:%2 - %4").arg(i.host.c_str()).arg(i.port).arg(chrono::duration_cast<chrono::milliseconds>(i.lastPing).count()).arg(i.clientVersion.c_str()));
auto d = m_client->blockChain().details();
auto diff = BlockInfo(m_client->blockChain().block()).difficulty;
ui->blockChain->setText(QString("#%1 @%3 T%2").arg(d.number).arg(toLog2(d.totalDifficulty)).arg(toLog2(diff)));
auto acs = m_client->state().addresses();
ui->accounts->clear();
for (auto i: acs)
ui->accounts->addItem(QString("%1 @ %2").arg(formatBalance(i.second).c_str()).arg(asHex(i.first.asArray()).c_str()));
ui->transactionQueue->clear();
for (pair<h256, bytes> const& i: m_client->transactionQueue().transactions())
{
Transaction t(i.second);
ui->transactionQueue->addItem(QString("%1 @ %2 <- %3")
.arg(formatBalance(t.value).c_str())
.arg(asHex(t.receiveAddress.asArray()).c_str())
.arg(asHex(t.sender().asArray()).c_str()) );
}
ui->transactions->clear();
auto const& bc = m_client->blockChain();
for (auto h = bc.currentHash(); h != bc.genesisHash(); h = bc.details(h).parent)
{
auto d = bc.details(h);
ui->transactions->addItem(QString("# %1 ==== %2").arg(d.number).arg(asHex(h.asArray()).c_str()));
for (auto const& i: RLP(bc.block(h))[1])
{
Transaction t(i.data());
ui->transactions->addItem(QString("%1 @ %2 <- %3")
.arg(formatBalance(t.value).c_str())
.arg(asHex(t.receiveAddress.asArray()).c_str())
.arg(asHex(t.sender().asArray()).c_str()) );
}
}
}
ui->ourAccounts->clear();
u256 totalBalance = 0;
for (auto i: m_myKeys)
{
u256 b = m_client->state().balance(i.address());
ui->ourAccounts->addItem(QString("%1 @ %2").arg(formatBalance(b).c_str()).arg(asHex(i.address().asArray()).c_str()));
totalBalance += b;
}
ui->balance->setText(QString::fromStdString(formatBalance(totalBalance)));
m_client->unlock();
}
void Main::on_idealPeers_valueChanged()
{
if (m_client->peerServer())
m_client->peerServer()->setIdealPeerCount(ui->idealPeers->value());
}
void Main::on_ourAccounts_doubleClicked()
{
qApp->clipboard()->setText(ui->ourAccounts->currentItem()->text().section(" @ ", 1));
}
void Main::on_log_doubleClicked()
{
qApp->clipboard()->setText(ui->log->currentItem()->text());
}
void Main::on_accounts_doubleClicked()
{
qApp->clipboard()->setText(ui->accounts->currentItem()->text().section(" @ ", 1));
}
void Main::on_destination_textChanged()
{
updateFee();
}
void Main::on_data_textChanged()
{
m_data = ui->data->toPlainText().split(QRegExp("[^0-9a-fA-Fx]+"), QString::SkipEmptyParts);
updateFee();
}
u256 Main::fee() const
{
return (ui->destination->text().isEmpty() || !ui->destination->text().toInt()) ? m_client->state().fee(m_data.size()) : m_client->state().fee();
}
u256 Main::value() const
{
return ui->value->value() * units()[units().size() - 1 - ui->valueUnits->currentIndex()].first;
}
u256 Main::total() const
{
return value() + fee();
}
void Main::updateFee()
{
ui->fee->setText(QString("(fee: %1)").arg(formatBalance(fee()).c_str()));
auto totalReq = total();
ui->total->setText(QString("Total: %1").arg(formatBalance(totalReq).c_str()));
bool ok = false;
for (auto i: m_myKeys)
if (m_client->state().balance(i.address()) >= totalReq)
{
ok = true;
break;
}
ui->send->setEnabled(ok);
QPalette p = ui->total->palette();
p.setColor(QPalette::WindowText, QColor(ok ? 0x00 : 0x80, 0x00, 0x00));
ui->total->setPalette(p);
}
void Main::on_net_triggered()
{
ui->port->setEnabled(!ui->net->isChecked());
ui->clientName->setEnabled(!ui->net->isChecked());
string n = "AlethZero/v" ADD_QUOTES(ETH_VERSION);
if (ui->clientName->text().size())
n += "/" + ui->clientName->text().toStdString();
n += "/" ADD_QUOTES(ETH_BUILD_TYPE) "/" ADD_QUOTES(ETH_BUILD_PLATFORM);
m_client->setClientVersion(n);
if (ui->net->isChecked())
{
m_client->startNetwork(ui->port->value(), string(), 0, NodeMode::Full, ui->idealPeers->value(), std::string(), ui->upnp->isChecked());
if (m_peers.size())
m_client->peerServer()->restorePeers(bytesConstRef((byte*)m_peers.data(), m_peers.size()));
}
else
m_client->stopNetwork();
}
void Main::on_connect_triggered()
{
if (!ui->net->isChecked())
{
ui->net->setChecked(true);
on_net_triggered();
}
bool ok = false;
QString s = QInputDialog::getItem(this, "Connect to a Network Peer", "Enter a peer to which a connection may be made:", m_servers, m_servers.count() ? rand() % m_servers.count() : 0, true, &ok);
if (ok && s.contains(":"))
{
string host = s.section(":", 0, 0).toStdString();
short port = s.section(":", 1).toInt();
m_client->connect(host, port);
}
}
void Main::on_verbosity_sliderMoved()
{
g_logVerbosity = ui->verbosity->value();
}
void Main::on_mine_triggered()
{
if (ui->mine->isChecked())
{
m_client->setAddress(m_myKeys.last().address());
m_client->startMining();
}
else
m_client->stopMining();
}
void Main::on_send_clicked()
{
u256 totalReq = value() + fee();
m_client->lock();
for (auto i: m_myKeys)
if (m_client->state().balance(i.address()) >= totalReq)
{
m_client->unlock();
Secret s = i.secret();
Address r = Address(fromUserHex(ui->destination->text().toStdString()));
u256s data;
data.reserve(m_data.size());
for (QString const& i: m_data)
data.push_back(u256(i.toStdString()));
m_client->transact(s, r, value(), data);
refresh();
return;
}
m_client->unlock();
statusBar()->showMessage("Couldn't make transaction: no single account contains at least the required amount.");
}
void Main::on_create_triggered()
{
m_myKeys.append(KeyPair::create());
}
<|endoftext|> |
<commit_before>#pragma once
#include <raindance/Core/Headers.hh>
#include <raindance/Core/Context.hh>
#include <raindance/Core/Interface/WindowManager.hh>
class Raindance
{
public:
Raindance(int argc, char** argv)
{
GLFW::create(argc, argv);
m_Context = new Context();
}
virtual ~Raindance()
{
GLFW::destroy();
}
virtual void add(rd::Window* window)
{
GLFW::setCallbacks(window);
auto id = m_WindowManager.add(window);
m_WindowManager.bind(id);
}
virtual void run()
{
m_WindowManager.active()->initialize(m_Context);
while (m_WindowManager.active()->state() == rd::Window::ALIVE)
{
Geometry::beginFrame();
auto window = m_WindowManager.active();
window->before(m_Context);
window->canvas()->bind();
window->draw(m_Context);
window->canvas()->unbind();
window->canvas()->draw(m_Context);
/*
static int count = 0;
if (count == 100)
window->canvas()->dump("test.tga");
count++;
*/
window->after(m_Context);
Geometry::endFrame();
idle();
checkGLErrors();
}
}
virtual void stop()
{
windows().active()->close();
}
virtual void idle()
{
windows().active()->idle(m_Context);
}
inline WindowManager& windows() { return m_WindowManager; }
protected:
Context* m_Context;
WindowManager m_WindowManager;
};
<commit_msg>Basic screenshot implementation<commit_after>#pragma once
#include <raindance/Core/Headers.hh>
#include <raindance/Core/Context.hh>
#include <raindance/Core/Interface/WindowManager.hh>
class Raindance
{
public:
Raindance(int argc, char** argv)
{
GLFW::create(argc, argv);
m_Context = new Context();
m_Screenshot = false;
m_ScreenshotFactor = 1.0;
}
virtual ~Raindance()
{
GLFW::destroy();
}
virtual void add(rd::Window* window)
{
GLFW::setCallbacks(window);
auto id = m_WindowManager.add(window);
m_WindowManager.bind(id);
}
virtual void run()
{
m_WindowManager.active()->initialize(m_Context);
while (m_WindowManager.active()->state() == rd::Window::ALIVE)
{
Geometry::beginFrame();
auto window = m_WindowManager.active();
window->before(m_Context);
//if (m_Screenshot)
//{
//}
window->canvas()->bind();
window->draw(m_Context);
window->canvas()->unbind();
window->canvas()->draw(m_Context);
if (m_Screenshot)
{
window->canvas()->dump(m_ScreenshotFilename.c_str());
m_Screenshot = false;
}
window->after(m_Context);
Geometry::endFrame();
idle();
checkGLErrors();
}
}
virtual void stop()
{
windows().active()->close();
}
virtual void idle()
{
windows().active()->idle(m_Context);
}
inline WindowManager& windows() { return m_WindowManager; }
void screenshot(const std::string& filename, float factor = 1.0)
{
m_Screenshot = true;
m_ScreenshotFilename = filename;
m_ScreenshotFactor = factor;
}
protected:
Context* m_Context;
WindowManager m_WindowManager;
bool m_Screenshot;
std::string m_ScreenshotFilename;
float m_ScreenshotFactor;
};
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <ctype.h>
#include <list>
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <RhIO.hpp>
#include "Stream.h"
#include "Shell.h"
#include "utils.h"
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
namespace RhIO
{
Shell::Shell(std::string server_)
: server(server_), client(NULL), clientSub(NULL), stream(NULL)
{
}
void Shell::terminal_set_ioconfig() {
struct termios custom;
int fd=fileno(stdin);
tcgetattr(fd, &termsave);
custom=termsave;
custom.c_lflag &= ~(ICANON|ECHO);
tcsetattr(fd,TCSANOW,&custom);
// fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)|O_NONBLOCK);
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)); //blocking
}
void Shell::displayPrompt()
{
Terminal::setColor("yellow", true);
std::cout << "RhIO";
Terminal::clear();
std::cout << ":";
Terminal::setColor("blue", true);
std::cout << getPath();
Terminal::clear();
std::cout << "# " << std::flush;
}
void Shell::run()
{
terminal_set_ioconfig();
std::string reqServer = "tcp://"+server+":"+ServerRepPort;
std::string subServer = "tcp://"+server+":"+ServerPubPort;
terminate = false;
Terminal::setColor("white", true);
std::cout << "Rhoban I/O shell, welcome!" << std::endl;
std::cout << "Connecting to " << server << std::endl;
client = new ClientReq(reqServer);
clientSub = new ClientSub(subServer);
stream = new Stream(this);
std::cout << "Downloading the tree..." << std::endl;
tree = new Node(client, "");
Terminal::clear();
// Reading lines from stdin
while (!terminate ) {
displayPrompt();
std::string line;
// std::getline(std::cin, line);
line=getLine();
parse(line);
}
tcsetattr(fileno(stdin),TCSANOW,&termsave);
std::cout << std::endl << std::flush;
}
std::string Shell::getLine()
{
char c;
std::string line("");
bool done=false;
bool esc_mode=false;
std::deque<std::string>::iterator hist_it=shell_history.end();
int cursorpos=0;
std::string lastcmd("");
while(!done)
{
if ((c = getchar())>0)
{
switch(c)
{
case 0x0a: //enter
putchar(c);
done=true;
lastcmd="";
if(shell_history.size()>0)
lastcmd=shell_history.back();
if(line.compare("")!=0 && line.compare(lastcmd)!=0) //store in history if non null and different than the last cmd
{
shell_history.push_back(line);
if(shell_history.size()>MAX_HISTORY)
shell_history.pop_front();
hist_it=shell_history.begin();
}
return line;
break;//useless
case 0x01: //Ctrl-a goto begin of line
Terminal::clearLine();
displayPrompt();
std::cout<<line;
cursorpos=0;
if(line.size()>0)
Terminal::cursorNLeft(line.size());
break;
case 0x05: //Ctrl-e goto end of line
Terminal::clearLine();
displayPrompt();
std::cout<<line;
if(cursorpos<line.size() )
{
Terminal::cursorNRight(line.size()-cursorpos);
cursorpos=line.size();
}
break;
case 0xc: //Ctrl-l clear screen
Terminal::clearScreen();
Terminal::clearLine();
Terminal::initCursor();
displayPrompt();
line="";
cursorpos=0;
break;
case 0x1b: //begin break mode (arrows)
esc_mode=true;
break;
case 0x5b: //just after 0x1b
break;
case 0x41: //up
if(esc_mode)
{
if(shell_history.size()>0 && hist_it!= shell_history.begin())
{
line=*--hist_it;
cursorpos=line.size();
Terminal::clearLine();
displayPrompt();
std::cout<<line;
}
esc_mode=false;
}
break;
case 0x42: //down
if(esc_mode)
{
if(shell_history.size()>0 && hist_it!= shell_history.end())
{
line=*hist_it++;
cursorpos=line.size();
Terminal::clearLine();
displayPrompt();
std::cout<<line;
}
else if( hist_it== shell_history.end())
{
Terminal::clearLine();
displayPrompt();
line="";
cursorpos=0;
}
esc_mode=false;
}
break;
case 0x43: //right
if(esc_mode)
{
if(cursorpos<line.size())
{
Terminal::cursorRight();
cursorpos++;
}
esc_mode=false;
}
break;
case 0x44: //left
if(esc_mode)
{
if(cursorpos>0)
{
Terminal::cursorLeft();
cursorpos--;
}
esc_mode=false;
}
break;
case 0x7f: //backspace
if(line.size()>0)
{
line.pop_back();
Terminal::clearLine();
displayPrompt();
cursorpos--;
std::cout<<line;
}
break;
default:
if(line.size()>0)
{
std::string tmp("");
tmp+=c;
line.insert(cursorpos,tmp);
}
else{
line+=c;
}
cursorpos++;
Terminal::clearLine();
displayPrompt();
std::cout<<line;
if(line.size()-cursorpos>0)
Terminal::cursorNLeft(line.size()-cursorpos);
break;
}
}
}
}
void Shell::parse(std::string line)
{
// Try to interpret command as a set
for (int i=0; i<line.size(); i++) {
if (line[i] == '=') {
std::string lvalue = line.substr(0, i);
std::string rvalue = line.substr(i+1);
trim(lvalue);
trim(rvalue);
set(lvalue, rvalue);
return;
}
}
// Try to split line into parts and execute it
std::list<std::string> parts;
std::string part;
for (int i=0; i<line.size(); i++) {
if (std::isspace(line[i])) {
if (part != "") {
parts.push_back(part);
part = "";
}
} else {
part += line[i];
}
}
if (part != "") {
parts.push_back(part);
}
if (parts.size()) {
auto command = parts.front();
parts.pop_front();
process(command, parts);
}
}
void Shell::process(std::string command, std::list<std::string> args)
{
// First, try to quit/exit
if (command == "quit" || command == "exit") {
terminate = true;
} else {
// Checking for the command in the list
if (commands.count(command)) {
std::vector<std::string> argsV;
for (auto part : args) {
argsV.push_back(part);
}
commands[command]->process(argsV);
} else {
auto nodeValue = getNodeValue(command);
auto value = nodeValue.value;
if (value) {
Node::get(this, nodeValue);
std::cout << command << "=" << Node::toString(value) << std::endl;
} else {
Terminal::setColor("red", true);
std::cout << "Unknown command: " << command << std::endl;
Terminal::clear();
}
}
}
}
void Shell::set(std::string lvalue, std::string rvalue)
{
auto node = getCurrentNode();
auto nodeValue = getNodeValue(lvalue);
auto value = nodeValue.value;
if (value) {
Node::setFromString(this, nodeValue, rvalue);
} else {
Terminal::setColor("red", true);
std::cout << "Unknown parameter: " << lvalue << std::endl;
Terminal::clear();
}
}
void Shell::registerCommand(Command *command)
{
command->setShell(this);
commands[command->getName()] = command;
}
std::map<std::string, Command*> Shell::getCommands()
{
return commands;
}
ClientReq *Shell::getClient()
{
return client;
}
ClientSub *Shell::getClientSub()
{
return clientSub;
}
void Shell::enterPath(std::string path_)
{
path.push_back(path_);
}
void Shell::upPath()
{
if (path.size()) {
path.pop_back();
}
}
bool Shell::goToPath(std::string spath)
{
if (auto node = getNode(spath)) {
auto parts = pathToParts(node->getPath());
path.clear();
for (auto part : parts) {
path.push_back(part);
}
return true;
} else {
return false;
}
}
std::string Shell::getPath()
{
std::string p = "";
for (auto part : path) {
if (p != "") {
p += "/";
}
p += part;
}
return p;
}
std::vector<std::string> Shell::pathToParts(std::string spath)
{
auto parts = split(spath, '/');
std::vector<std::string> path;
for (auto part : parts) {
if (part != "") {
path.push_back(part);
}
}
return path;
}
Node *Shell::getNode(std::string spath)
{
if (spath.size()==0 || spath[0]!='/') {
auto myPath = getPath();
if (myPath != "") {
myPath += "/";
}
spath = myPath + spath;
}
auto path = pathToParts(spath);
Node *node = tree;
for (auto part : path) {
node = node->getChild(part);
if (node == NULL) {
return NULL;
}
}
return node;
}
NodeValue Shell::getNodeValue(std::string path)
{
auto parts = pathToParts(path);
if (parts.size() == 0) {
return NodeValue(NULL, NULL);
}
// Child name
auto name = parts[parts.size()-1];
parts.pop_back();
// Creating value path
std::string prefix = "";
for (auto part : parts) {
if (prefix != "") prefix += "/";
prefix += part;
}
if (path[0] == '/') {
prefix = "/" + prefix;
}
// Getting node
auto node = getNode(prefix);
if (node == NULL) {
return NodeValue(NULL, NULL);
}
return node->getNodeValue(name);
}
Stream *Shell::getStream()
{
return stream;
}
ValueBase *Shell::getValue(std::string path)
{
return getNodeValue(path).value;
}
Node *Shell::getCurrentNode()
{
return getNode();
}
}
<commit_msg>return getline<commit_after>#include <stdio.h>
#include <ctype.h>
#include <list>
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <RhIO.hpp>
#include "Stream.h"
#include "Shell.h"
#include "utils.h"
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
namespace RhIO
{
Shell::Shell(std::string server_)
: server(server_), client(NULL), clientSub(NULL), stream(NULL)
{
}
void Shell::terminal_set_ioconfig() {
struct termios custom;
int fd=fileno(stdin);
tcgetattr(fd, &termsave);
custom=termsave;
custom.c_lflag &= ~(ICANON|ECHO);
tcsetattr(fd,TCSANOW,&custom);
// fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)|O_NONBLOCK);
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)); //blocking
}
void Shell::displayPrompt()
{
Terminal::setColor("yellow", true);
std::cout << "RhIO";
Terminal::clear();
std::cout << ":";
Terminal::setColor("blue", true);
std::cout << getPath();
Terminal::clear();
std::cout << "# " << std::flush;
}
void Shell::run()
{
terminal_set_ioconfig();
std::string reqServer = "tcp://"+server+":"+ServerRepPort;
std::string subServer = "tcp://"+server+":"+ServerPubPort;
terminate = false;
Terminal::setColor("white", true);
std::cout << "Rhoban I/O shell, welcome!" << std::endl;
std::cout << "Connecting to " << server << std::endl;
client = new ClientReq(reqServer);
clientSub = new ClientSub(subServer);
stream = new Stream(this);
std::cout << "Downloading the tree..." << std::endl;
tree = new Node(client, "");
Terminal::clear();
// Reading lines from stdin
while (!terminate ) {
displayPrompt();
std::string line;
// std::getline(std::cin, line);
line=getLine();
parse(line);
}
tcsetattr(fileno(stdin),TCSANOW,&termsave);
std::cout << std::endl << std::flush;
}
std::string Shell::getLine()
{
char c;
std::string line("");
bool done=false;
bool esc_mode=false;
std::deque<std::string>::iterator hist_it=shell_history.end();
int cursorpos=0;
std::string lastcmd("");
while(!done)
{
if ((c = getchar())>0)
{
switch(c)
{
case 0x0a: //enter
putchar(c);
done=true;
lastcmd="";
if(shell_history.size()>0)
lastcmd=shell_history.back();
if(line.compare("")!=0 && line.compare(lastcmd)!=0) //store in history if non null and different than the last cmd
{
shell_history.push_back(line);
if(shell_history.size()>MAX_HISTORY)
shell_history.pop_front();
hist_it=shell_history.begin();
}
return line;
break;//useless
case 0x01: //Ctrl-a goto begin of line
Terminal::clearLine();
displayPrompt();
std::cout<<line;
cursorpos=0;
if(line.size()>0)
Terminal::cursorNLeft(line.size());
break;
case 0x05: //Ctrl-e goto end of line
Terminal::clearLine();
displayPrompt();
std::cout<<line;
if(cursorpos<line.size() )
{
// Terminal::cursorNLeft(cursorpos);
// Terminal::cursorNRight(line.size());
cursorpos=line.size();
}
break;
case 0xc: //Ctrl-l clear screen
Terminal::clearScreen();
Terminal::clearLine();
Terminal::initCursor();
displayPrompt();
line="";
cursorpos=0;
break;
case 0x1b: //begin break mode (arrows)
esc_mode=true;
break;
case 0x5b: //just after 0x1b
break;
case 0x41: //up
if(esc_mode)
{
if(shell_history.size()>0 && hist_it!= shell_history.begin())
{
line=*--hist_it;
cursorpos=line.size();
Terminal::clearLine();
displayPrompt();
std::cout<<line;
}
esc_mode=false;
}
break;
case 0x42: //down
if(esc_mode)
{
if(shell_history.size()>0 && hist_it!= shell_history.end())
{
line=*hist_it++;
cursorpos=line.size();
Terminal::clearLine();
displayPrompt();
std::cout<<line;
}
else if( hist_it== shell_history.end())
{
Terminal::clearLine();
displayPrompt();
line="";
cursorpos=0;
}
esc_mode=false;
}
break;
case 0x43: //right
if(esc_mode)
{
if(cursorpos<line.size())
{
Terminal::cursorRight();
cursorpos++;
}
esc_mode=false;
}
break;
case 0x44: //left
if(esc_mode)
{
if(cursorpos>0)
{
Terminal::cursorLeft();
cursorpos--;
}
esc_mode=false;
}
break;
case 0x7f: //backspace
if(line.size()>0)
{
line.pop_back();
Terminal::clearLine();
displayPrompt();
cursorpos--;
std::cout<<line;
}
break;
default:
if(line.size()>0)
{
std::string tmp("");
tmp+=c;
line.insert(cursorpos,tmp);
}
else{
line+=c;
}
cursorpos++;
Terminal::clearLine();
displayPrompt();
std::cout<<line;
if(line.size()-cursorpos>0)
Terminal::cursorNLeft(line.size()-cursorpos);
break;
}
}
}
line="";
return line;
}
void Shell::parse(std::string line)
{
// Try to interpret command as a set
for (int i=0; i<line.size(); i++) {
if (line[i] == '=') {
std::string lvalue = line.substr(0, i);
std::string rvalue = line.substr(i+1);
trim(lvalue);
trim(rvalue);
set(lvalue, rvalue);
return;
}
}
// Try to split line into parts and execute it
std::list<std::string> parts;
std::string part;
for (int i=0; i<line.size(); i++) {
if (std::isspace(line[i])) {
if (part != "") {
parts.push_back(part);
part = "";
}
} else {
part += line[i];
}
}
if (part != "") {
parts.push_back(part);
}
if (parts.size()) {
auto command = parts.front();
parts.pop_front();
process(command, parts);
}
}
void Shell::process(std::string command, std::list<std::string> args)
{
// First, try to quit/exit
if (command == "quit" || command == "exit") {
terminate = true;
} else {
// Checking for the command in the list
if (commands.count(command)) {
std::vector<std::string> argsV;
for (auto part : args) {
argsV.push_back(part);
}
commands[command]->process(argsV);
} else {
auto nodeValue = getNodeValue(command);
auto value = nodeValue.value;
if (value) {
Node::get(this, nodeValue);
std::cout << command << "=" << Node::toString(value) << std::endl;
} else {
Terminal::setColor("red", true);
std::cout << "Unknown command: " << command << std::endl;
Terminal::clear();
}
}
}
}
void Shell::set(std::string lvalue, std::string rvalue)
{
auto node = getCurrentNode();
auto nodeValue = getNodeValue(lvalue);
auto value = nodeValue.value;
if (value) {
Node::setFromString(this, nodeValue, rvalue);
} else {
Terminal::setColor("red", true);
std::cout << "Unknown parameter: " << lvalue << std::endl;
Terminal::clear();
}
}
void Shell::registerCommand(Command *command)
{
command->setShell(this);
commands[command->getName()] = command;
}
std::map<std::string, Command*> Shell::getCommands()
{
return commands;
}
ClientReq *Shell::getClient()
{
return client;
}
ClientSub *Shell::getClientSub()
{
return clientSub;
}
void Shell::enterPath(std::string path_)
{
path.push_back(path_);
}
void Shell::upPath()
{
if (path.size()) {
path.pop_back();
}
}
bool Shell::goToPath(std::string spath)
{
if (auto node = getNode(spath)) {
auto parts = pathToParts(node->getPath());
path.clear();
for (auto part : parts) {
path.push_back(part);
}
return true;
} else {
return false;
}
}
std::string Shell::getPath()
{
std::string p = "";
for (auto part : path) {
if (p != "") {
p += "/";
}
p += part;
}
return p;
}
std::vector<std::string> Shell::pathToParts(std::string spath)
{
auto parts = split(spath, '/');
std::vector<std::string> path;
for (auto part : parts) {
if (part != "") {
path.push_back(part);
}
}
return path;
}
Node *Shell::getNode(std::string spath)
{
if (spath.size()==0 || spath[0]!='/') {
auto myPath = getPath();
if (myPath != "") {
myPath += "/";
}
spath = myPath + spath;
}
auto path = pathToParts(spath);
Node *node = tree;
for (auto part : path) {
node = node->getChild(part);
if (node == NULL) {
return NULL;
}
}
return node;
}
NodeValue Shell::getNodeValue(std::string path)
{
auto parts = pathToParts(path);
if (parts.size() == 0) {
return NodeValue(NULL, NULL);
}
// Child name
auto name = parts[parts.size()-1];
parts.pop_back();
// Creating value path
std::string prefix = "";
for (auto part : parts) {
if (prefix != "") prefix += "/";
prefix += part;
}
if (path[0] == '/') {
prefix = "/" + prefix;
}
// Getting node
auto node = getNode(prefix);
if (node == NULL) {
return NodeValue(NULL, NULL);
}
return node->getNodeValue(name);
}
Stream *Shell::getStream()
{
return stream;
}
ValueBase *Shell::getValue(std::string path)
{
return getNodeValue(path).value;
}
Node *Shell::getCurrentNode()
{
return getNode();
}
}
<|endoftext|> |
<commit_before>#define _JNI_IMPLEMENTATION_ 1
#include <jni.h>
#include <dlfcn.h>
#include <assert.h>
#include "KrapsRDD.h"
typedef KrapsIterator* (*iterator_constructor_t)(JNIEnv* env);
struct KrapsRDD
{
void* dll;
KrapsIterator* iterator;
void* next() {
return iterator->next();
}
KrapsRDD(void* so, KrapsIterator* iter) : dll(so), iterator(iter) {}
~KrapsRDD() {
dlclose(dll);
delete iterator;
}
};
class KrapsCluster
{
public:
Cluster* cluster;
char** nodes;
int executorId;
pthread_mutex_t mutex;
int getExecutorId()
{
#ifdef SMP_SUPPORT
pthread_mutex_lock(&mutex);
int id = ++executorId;
pthread_mutex_unlock(&mutex);
return id;
#else
return 1;
#endif
}
public:
KrapsCluster() : executorId(0)
{
pthread_mutex_init(&mutex, NULL);
}
~KrapsCluster()
{
pthread_mutex_destroy(&mutex);
}
void start(JNIEnv* env, jobjectArray hosts, jint nCores) {
int nHosts = env->GetArrayLength(hosts);
int nNodes = nHosts*nCores;
nodes = new char*[nNodes];
int nodeId = -1;
int id = getExecutorId();
for (int i = 0; i < nNodes; i++) {
nodes[i] = new char[16];
jstring host = (jstring)env->GetObjectArrayElement(hosts, i % nHosts);
char const* hostName = env->GetStringUTFChars(host, 0);
sprintf(nodes[i], "%s:500%d", hostName, (i / nHosts) + 1);
env->ReleaseStringUTFChars(host, hostName);
if (Socket::isLocalHost(nodes[i])) {
if (--id == 0) {
nodeId = i;
}
}
}
assert(nodeId >= 0);
cluster = new Cluster(nodeId, nNodes, nodes);
cluster->userData = env;
}
void stop()
{
for (size_t i = 0; i < cluster->nNodes; i++) {
delete nodes[i];
}
delete[] nodes;
delete cluster;
}
};
static KrapsCluster kraps;
extern "C" {
JNIEXPORT jlong Java_kraps_KrapsRDD_createIterator(JNIEnv* env, jobject self, jint queryId)
{
char buf[256];
sprintf(buf, "libQ%d.so", queryId);
void* dll = dlopen(buf, RTLD_NOW|RTLD_GLOBAL);
assert(dll != NULL);
sprintf(buf, "getQ%dIterator", queryId);
iterator_constructor_t constructor = (iterator_constructor_t)dlsym(dll, buf);
assert(constructor != NULL);
return (jlong)(size_t)new KrapsRDD(dll, constructor(env));
}
JNIEXPORT jlong Java_kraps_KrapsRDD_nextRow(JNIEnv* env, jobject self, jlong iterator, jobjectArray sparkInputs)
{
KrapsRDD* rdd = (KrapsRDD*)iterator;
Cluster* cluster = Cluster::instance.get();
if (cluster == NULL) {
cluster = kraps.cluster;
Cluster::instance.set(cluster);
}
JavaContext ctx(env, sparkInputs);
cluster->userData = &ctx;
void* row = rdd->next();
if (row != NULL) {
return (jlong)(size_t)row;
}
cluster->barrier();
delete rdd;
return 0;
}
JNIEXPORT void Java_kraps_KrapsCluster_00024_start(JNIEnv* env, jobject self, jobjectArray hosts, jint nCores)
{
kraps.start(env, hosts, nCores);
}
JNIEXPORT void Java_kraps_KrapsCluster_00024_stop(JNIEnv* env, jobject self)
{
kraps.stop();
}
}
<commit_msg>Change order of destroying DLL in KrapsRDD destructor<commit_after>#define _JNI_IMPLEMENTATION_ 1
#include <jni.h>
#include <dlfcn.h>
#include <assert.h>
#include "KrapsRDD.h"
typedef KrapsIterator* (*iterator_constructor_t)(JNIEnv* env);
struct KrapsRDD
{
void* dll;
KrapsIterator* iterator;
void* next() {
return iterator->next();
}
KrapsRDD(void* so, KrapsIterator* iter) : dll(so), iterator(iter) {}
~KrapsRDD() {
delete iterator;
dlclose(dll);
}
};
class KrapsCluster
{
public:
Cluster* cluster;
char** nodes;
int executorId;
pthread_mutex_t mutex;
int getExecutorId()
{
#ifdef SMP_SUPPORT
pthread_mutex_lock(&mutex);
int id = ++executorId;
pthread_mutex_unlock(&mutex);
return id;
#else
return 1;
#endif
}
public:
KrapsCluster() : executorId(0)
{
pthread_mutex_init(&mutex, NULL);
}
~KrapsCluster()
{
pthread_mutex_destroy(&mutex);
}
void start(JNIEnv* env, jobjectArray hosts, jint nCores) {
int nHosts = env->GetArrayLength(hosts);
int nNodes = nHosts*nCores;
nodes = new char*[nNodes];
int nodeId = -1;
int id = getExecutorId();
for (int i = 0; i < nNodes; i++) {
nodes[i] = new char[16];
jstring host = (jstring)env->GetObjectArrayElement(hosts, i % nHosts);
char const* hostName = env->GetStringUTFChars(host, 0);
sprintf(nodes[i], "%s:500%d", hostName, (i / nHosts) + 1);
env->ReleaseStringUTFChars(host, hostName);
if (Socket::isLocalHost(nodes[i])) {
if (--id == 0) {
nodeId = i;
}
}
}
assert(nodeId >= 0);
cluster = new Cluster(nodeId, nNodes, nodes);
cluster->userData = env;
}
void stop()
{
for (size_t i = 0; i < cluster->nNodes; i++) {
delete nodes[i];
}
delete[] nodes;
delete cluster;
}
};
static KrapsCluster kraps;
extern "C" {
JNIEXPORT jlong Java_kraps_KrapsRDD_createIterator(JNIEnv* env, jobject self, jint queryId)
{
char buf[256];
sprintf(buf, "libQ%d.so", queryId);
void* dll = dlopen(buf, RTLD_NOW|RTLD_GLOBAL);
assert(dll != NULL);
sprintf(buf, "getQ%dIterator", queryId);
iterator_constructor_t constructor = (iterator_constructor_t)dlsym(dll, buf);
assert(constructor != NULL);
return (jlong)(size_t)new KrapsRDD(dll, constructor(env));
}
JNIEXPORT jlong Java_kraps_KrapsRDD_nextRow(JNIEnv* env, jobject self, jlong iterator, jobjectArray sparkInputs)
{
KrapsRDD* rdd = (KrapsRDD*)iterator;
Cluster* cluster = Cluster::instance.get();
if (cluster == NULL) {
cluster = kraps.cluster;
Cluster::instance.set(cluster);
}
JavaContext ctx(env, sparkInputs);
cluster->userData = &ctx;
void* row = rdd->next();
if (row != NULL) {
return (jlong)(size_t)row;
}
cluster->barrier();
delete rdd;
return 0;
}
JNIEXPORT void Java_kraps_KrapsCluster_00024_start(JNIEnv* env, jobject self, jobjectArray hosts, jint nCores)
{
kraps.start(env, hosts, nCores);
}
JNIEXPORT void Java_kraps_KrapsCluster_00024_stop(JNIEnv* env, jobject self)
{
kraps.stop();
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: qualiname.hxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: np $ $Date: 2002-11-01 17:10: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): _______________________________________
*
*
************************************************************************/
#ifndef ARY_QUALINAME_HXX
#define ARY_QUALINAME_HXX
// VERSION: Autodoc 2.2
// USED SERVICES
// BASE CLASSES
// COMPONENTS
// PARAMETERS
#include <cosv/template/tpltools.hxx>
namespace ary
{
class QualifiedName
{
public:
typedef StringVector::const_iterator namespace_iterator;
QualifiedName(
uintt i_nSize = 0);
/// @see AssignText()
QualifiedName(
const char * i_sText,
const char * i_sSeparator );
~QualifiedName();
QualifiedName & operator+=(
const String & i_sNamespaceName )
{ if (i_sNamespaceName.length() > 0)
aNamespace.push_back(i_sNamespaceName);
return *this; }
/// @precond i_nIndex < NamespaceDepth().
String & operator[](
uintt i_nIndex )
{ csv_assert(i_nIndex < aNamespace.size());
return aNamespace[i_nIndex]; }
void Init(
bool i_bAbsolute )
{ Empty(); bIsAbsolute = i_bAbsolute; }
/** Reads a qualified name from a string.
If the last two charcters are "()", the inquiry IsFunction() will return
true.
*/
void AssignText(
const char * i_sText,
const char * i_sSeparator );
void SetLocalName(
const String & i_sLocalName )
{ sLocalName = i_sLocalName; }
void Empty() { csv::erase_container(aNamespace); sLocalName.clear(); bIsAbsolute = false; }
const String & LocalName() const { return sLocalName; }
namespace_iterator first_namespace() const { return aNamespace.begin(); }
namespace_iterator end_namespace() const { return aNamespace.end(); }
uintt NamespaceDepth() const { return aNamespace.size(); }
bool IsAbsolute() const { return bIsAbsolute; }
bool IsQualified() const { return aNamespace.size() > 0; }
bool IsFunction() const { return bIsFunction; }
private:
// DATA
StringVector aNamespace;
String sLocalName;
bool bIsAbsolute; /// true := beginning with "::".
bool bIsFunction; /// true := ending with "()"
};
// IMPLEMENTATION
} // namespace ary
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.132); FILE MERGED 2005/09/05 13:08:56 rt 1.1.132.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: qualiname.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-07 15:54:46 $
*
* 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 ARY_QUALINAME_HXX
#define ARY_QUALINAME_HXX
// VERSION: Autodoc 2.2
// USED SERVICES
// BASE CLASSES
// COMPONENTS
// PARAMETERS
#include <cosv/template/tpltools.hxx>
namespace ary
{
class QualifiedName
{
public:
typedef StringVector::const_iterator namespace_iterator;
QualifiedName(
uintt i_nSize = 0);
/// @see AssignText()
QualifiedName(
const char * i_sText,
const char * i_sSeparator );
~QualifiedName();
QualifiedName & operator+=(
const String & i_sNamespaceName )
{ if (i_sNamespaceName.length() > 0)
aNamespace.push_back(i_sNamespaceName);
return *this; }
/// @precond i_nIndex < NamespaceDepth().
String & operator[](
uintt i_nIndex )
{ csv_assert(i_nIndex < aNamespace.size());
return aNamespace[i_nIndex]; }
void Init(
bool i_bAbsolute )
{ Empty(); bIsAbsolute = i_bAbsolute; }
/** Reads a qualified name from a string.
If the last two charcters are "()", the inquiry IsFunction() will return
true.
*/
void AssignText(
const char * i_sText,
const char * i_sSeparator );
void SetLocalName(
const String & i_sLocalName )
{ sLocalName = i_sLocalName; }
void Empty() { csv::erase_container(aNamespace); sLocalName.clear(); bIsAbsolute = false; }
const String & LocalName() const { return sLocalName; }
namespace_iterator first_namespace() const { return aNamespace.begin(); }
namespace_iterator end_namespace() const { return aNamespace.end(); }
uintt NamespaceDepth() const { return aNamespace.size(); }
bool IsAbsolute() const { return bIsAbsolute; }
bool IsQualified() const { return aNamespace.size() > 0; }
bool IsFunction() const { return bIsFunction; }
private:
// DATA
StringVector aNamespace;
String sLocalName;
bool bIsAbsolute; /// true := beginning with "::".
bool bIsFunction; /// true := ending with "()"
};
// IMPLEMENTATION
} // namespace ary
#endif
<|endoftext|> |
<commit_before>
/*
* BSD 3-Clause License
*
* Copyright (c) 2018, mtezych
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cl/Platform.h>
#include <cl/Context.h>
#include <cl/CommandQueue.h>
#include <cl/Program.h>
#include <cl/Kernel.h>
#include <cl/Memory.h>
//
// [ Platform & Memory Models ]
//
// ┌─────────────────────────────────────────────────────────────────────┐
// │ Host Memory │
// └──────────────────────────────────┰──────────────────────────────────┘
// ┌──────────────────────────────────┸──────────────────────────────────┐
// │ Host │
// └──────────────────────────────────┰──────────────────────────────────┘
// ┏━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━┓
// ┌────────────────┸──────────────┐ ┌────────────────┸──────────────┐
// │ OpenCL Device │ │ OpenCL Device │
// │ ┌────────────────────────┐ │ │ ┌────────────────────────┐ │
// │ │ Compute Unit │ │ │ │ Compute Unit │ │
// │ ┌──┴─────────────────────┐ │ │ │ ┌──┴─────────────────────┐ │ │
// │ │ Compute Unit │ │ │ │ │ Compute Unit │ │ │
// │ │ ┌────────────────────┐ │ │ │ │ │ ┌────────────────────┐ │ │ │
// │ │ │ Processing Element │ │ │ │ │ │ │ Processing Element │ │ │ │
// │ │ └──────────┰─────────┘ │ │ │ │ │ └──────────┰─────────┘ │ │ │
// │ │ ┌──────────┸─────────┐ │ │ │ │ │ ┌──────────┸─────────┐ │ │ │
// │ │ │ Private Memory │ │ │ │ │ │ │ Private Memory │ │ │ │
// │ │ └────────────────────┘ │ │ │ ... │ │ └────────────────────┘ │ │ │
// │ │ ... │ │ │ │ │ ... │ │ │
// │ │ ┌────────────────────┐ │ │ │ │ │ ┌────────────────────┐ │ │ │
// │ │ │ Processing Element │ │ │ │ │ │ │ Processing Element │ │ │ │
// │ │ └──────────┰─────────┘ │ │ │ │ │ └──────────┰─────────┘ │ │ │
// │ │ ┌──────────┸─────────┐ │ │ │ │ │ ┌──────────┸─────────┐ │ │ │
// │ │ │ Private Memory │ ├──┘ │ │ │ │ Private Memory │ ├──┘ │
// │ │ └────────────────────┘ ├──┐ │ │ │ └────────────────────┘ ├──┐ │
// │ └────────────┰───────────┘ │ │ │ └────────────┰───────────┘ │ │
// │ ┌────────────┸───────────┐──┘ │ │ ┌────────────┸───────────┐──┘ │
// │ │ Local Memory │ │ │ │ Local Memory │ │
// │ └────────────────────────┘ │ │ └────────────────────────┘ │
// └──────────────┰────────────────┘ └──────────────┰────────────────┘
// ┌──────────────┸────────────────┐ ┌──────────────┸────────────────┐
// │ Global / Constant Memory │ │ Global / Constant Memory │
// └───────────────────────────────┘ └───────────────────────────────┘
//
// [ Execution Model ]
//
// ┌───────────────┐ ┌───────────────┐ ┌───────────────┐
// │ Work Group │ │ Work Group │ │ Work Group │
// │ ┌───────────┐ │ │ ┌───────────┐ │ │ ┌───────────┐ │
// │ │ Work Item │ │ │ │ Work Item │ │ │ │ Work Item │ │
// │ └───────────┘ │ │ └───────────┘ │ │ └───────────┘ │
// │ ┌───────────┐ │ │ ┌───────────┐ │ │ ┌───────────┐ │
// │ │ Work Item │ │ │ │ Work Item │ │ ... │ │ Work Item │ │
// │ └───────────┘ │ │ └───────────┘ │ │ └───────────┘ │
// │ ... │ │ ... │ │ ... │
// │ ┌───────────┐ │ │ ┌───────────┐ │ │ ┌───────────┐ │
// │ │ Work Item │ │ │ │ Work Item │ │ │ │ Work Item │ │
// │ └───────────┘ │ │ └───────────┘ │ │ └───────────┘ │
// └───────────────┘ └───────────────┘ └───────────────┘
// ┌───────────────────┬───────────────────────┐
// │ OpenCL C │ GLSL │
// ┌────────────┼───────────────────┼───────────────────────┤
// │ │ get_work_dim() │ │
// │ NDRange │ get_num_groups() │ gl_NumWorkGroups │
// │ │ get_local_size() │ gl_WorkGroupSize │
// │ │ get_global_size() │ │
// ├────────────┼───────────────────┼───────────────────────┤
// │ Work Group │ get_group_id() │ gl_WorkGroupID │
// ├────────────┼───────────────────┼───────────────────────┤
// │ │ get_local_id() │ gl_LocalInvocationID │
// │ Work Item │ get_global_id() │ gl_GlobalInvocationID │
// └────────────┴───────────────────┴───────────────────────┘
//
// get_global_size() = get_num_groups() * get_local_size()
//
// get_global_id() = get_group_id() * get_local_size() + get_local_id()
// gl_GlobalInvocationID = gl_WorkGroupID * gl_WorkGroupSize + gl_LocalInvocationID
//
int main ()
{
const auto platforms = cl::GetPlatforms();
for (const auto& platform : platforms)
{
const auto platformProfile = platform.GetInfo<cl::Platform::Info::Profile >();
const auto platformVersion = platform.GetInfo<cl::Platform::Info::Version >();
const auto platformVendor = platform.GetInfo<cl::Platform::Info::Vendor >();
const auto platformName = platform.GetInfo<cl::Platform::Info::Name >();
const auto platformExtensions = platform.GetInfo<cl::Platform::Info::Extensions>();
const auto devices = platform.GetDevices();
for (const auto& device : devices)
{
const auto deviceType = device.GetInfo<cl::Device::Info::Type >();
const auto deviceProfile = device.GetInfo<cl::Device::Info::Profile >();
const auto deviceVersion = device.GetInfo<cl::Device::Info::Version >();
const auto deviceVendor = device.GetInfo<cl::Device::Info::Vendor >();
const auto deviceName = device.GetInfo<cl::Device::Info::Name >();
const auto deviceExtensions = device.GetInfo<cl::Device::Info::Extensions >();
const auto deviceVendorID = device.GetInfo<cl::Device::Info::VendorID >();
const auto driverVersion = device.GetInfo<cl::Device::Info::DriverVersion>();
}
const auto context = cl::Context { platform, devices };
const auto contextNumDevices = context.GetInfo<cl::Context::Info::NumDevices >();
const auto contextReferenceCount = context.GetInfo<cl::Context::Info::ReferenceCount>();
for (const auto& device : devices)
{
const auto commandQueue = cl::CommandQueue { context, device };
}
auto program = cl::Program
{
context,
"__kernel void cl_main \n"
"( \n"
" __global const float* firstInput, \n"
" __global const float* secondInput, \n"
" __global float* output \n"
") \n"
"{ \n"
" int globalID = get_global_id(0); \n"
" \n"
" output[globalID] = firstInput[globalID] + secondInput[globalID]; \n"
"} \n"
};
program.Build();
auto kernel = cl::Kernel { program, "cl_main" };
const auto firstSrcMemory = cl::Memory
{
context,
cl::Memory::DeviceAccess::ReadOnly,
cl::Memory::HostAccess::ReadWrite,
cl::Memory::Alloc::Device,
std::vector<float>
{
1.5f, 7.6f, 8.1f, 1.5f, 1.7f, 2.4f, 9.0f, 3.5f,
},
};
const auto secondSrcMemory = cl::Memory
{
context,
cl::Memory::DeviceAccess::ReadOnly,
cl::Memory::HostAccess::ReadWrite,
cl::Memory::Alloc::Device,
std::vector<float>
{
3.6f, 7.0f, 0.8f, 4.3f, 2.7f, 6.5f, 2.8f, 1.4f,
},
};
const auto dstMemory = cl::Memory
{
context,
cl::Memory::DeviceAccess::WriteOnly,
cl::Memory::HostAccess::ReadWrite,
cl::Memory::Alloc::Device,
8
};
kernel.SetArg(0, firstSrcMemory);
kernel.SetArg(1, secondSrcMemory);
kernel.SetArg(2, dstMemory);
}
return 0;
}
<commit_msg>CL -> Implemented GetInfo() functions in OpenCL demo.<commit_after>
/*
* BSD 3-Clause License
*
* Copyright (c) 2018, mtezych
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cl/Platform.h>
#include <cl/Context.h>
#include <cl/CommandQueue.h>
#include <cl/Program.h>
#include <cl/Kernel.h>
#include <cl/Memory.h>
//
// [ Platform & Memory Models ]
//
// ┌─────────────────────────────────────────────────────────────────────┐
// │ Host Memory │
// └──────────────────────────────────┰──────────────────────────────────┘
// ┌──────────────────────────────────┸──────────────────────────────────┐
// │ Host │
// └──────────────────────────────────┰──────────────────────────────────┘
// ┏━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━┓
// ┌────────────────┸──────────────┐ ┌────────────────┸──────────────┐
// │ OpenCL Device │ │ OpenCL Device │
// │ ┌────────────────────────┐ │ │ ┌────────────────────────┐ │
// │ │ Compute Unit │ │ │ │ Compute Unit │ │
// │ ┌──┴─────────────────────┐ │ │ │ ┌──┴─────────────────────┐ │ │
// │ │ Compute Unit │ │ │ │ │ Compute Unit │ │ │
// │ │ ┌────────────────────┐ │ │ │ │ │ ┌────────────────────┐ │ │ │
// │ │ │ Processing Element │ │ │ │ │ │ │ Processing Element │ │ │ │
// │ │ └──────────┰─────────┘ │ │ │ │ │ └──────────┰─────────┘ │ │ │
// │ │ ┌──────────┸─────────┐ │ │ │ │ │ ┌──────────┸─────────┐ │ │ │
// │ │ │ Private Memory │ │ │ │ │ │ │ Private Memory │ │ │ │
// │ │ └────────────────────┘ │ │ │ ... │ │ └────────────────────┘ │ │ │
// │ │ ... │ │ │ │ │ ... │ │ │
// │ │ ┌────────────────────┐ │ │ │ │ │ ┌────────────────────┐ │ │ │
// │ │ │ Processing Element │ │ │ │ │ │ │ Processing Element │ │ │ │
// │ │ └──────────┰─────────┘ │ │ │ │ │ └──────────┰─────────┘ │ │ │
// │ │ ┌──────────┸─────────┐ │ │ │ │ │ ┌──────────┸─────────┐ │ │ │
// │ │ │ Private Memory │ ├──┘ │ │ │ │ Private Memory │ ├──┘ │
// │ │ └────────────────────┘ ├──┐ │ │ │ └────────────────────┘ ├──┐ │
// │ └────────────┰───────────┘ │ │ │ └────────────┰───────────┘ │ │
// │ ┌────────────┸───────────┐──┘ │ │ ┌────────────┸───────────┐──┘ │
// │ │ Local Memory │ │ │ │ Local Memory │ │
// │ └────────────────────────┘ │ │ └────────────────────────┘ │
// └──────────────┰────────────────┘ └──────────────┰────────────────┘
// ┌──────────────┸────────────────┐ ┌──────────────┸────────────────┐
// │ Global / Constant Memory │ │ Global / Constant Memory │
// └───────────────────────────────┘ └───────────────────────────────┘
//
// [ Execution Model ]
//
// ┌───────────────┐ ┌───────────────┐ ┌───────────────┐
// │ Work Group │ │ Work Group │ │ Work Group │
// │ ┌───────────┐ │ │ ┌───────────┐ │ │ ┌───────────┐ │
// │ │ Work Item │ │ │ │ Work Item │ │ │ │ Work Item │ │
// │ └───────────┘ │ │ └───────────┘ │ │ └───────────┘ │
// │ ┌───────────┐ │ │ ┌───────────┐ │ │ ┌───────────┐ │
// │ │ Work Item │ │ │ │ Work Item │ │ ... │ │ Work Item │ │
// │ └───────────┘ │ │ └───────────┘ │ │ └───────────┘ │
// │ ... │ │ ... │ │ ... │
// │ ┌───────────┐ │ │ ┌───────────┐ │ │ ┌───────────┐ │
// │ │ Work Item │ │ │ │ Work Item │ │ │ │ Work Item │ │
// │ └───────────┘ │ │ └───────────┘ │ │ └───────────┘ │
// └───────────────┘ └───────────────┘ └───────────────┘
// ┌───────────────────┬───────────────────────┐
// │ OpenCL C │ GLSL │
// ┌────────────┼───────────────────┼───────────────────────┤
// │ │ get_work_dim() │ │
// │ NDRange │ get_num_groups() │ gl_NumWorkGroups │
// │ │ get_local_size() │ gl_WorkGroupSize │
// │ │ get_global_size() │ │
// ├────────────┼───────────────────┼───────────────────────┤
// │ Work Group │ get_group_id() │ gl_WorkGroupID │
// ├────────────┼───────────────────┼───────────────────────┤
// │ │ get_local_id() │ gl_LocalInvocationID │
// │ Work Item │ get_global_id() │ gl_GlobalInvocationID │
// └────────────┴───────────────────┴───────────────────────┘
//
// get_global_size() = get_num_groups() * get_local_size()
//
// get_global_id() = get_group_id() * get_local_size() + get_local_id()
// gl_GlobalInvocationID = gl_WorkGroupID * gl_WorkGroupSize + gl_LocalInvocationID
//
void GetInfo (const cl::Platform& platform)
{
const auto profile = platform.GetInfo<cl::Platform::Info::Profile >();
const auto version = platform.GetInfo<cl::Platform::Info::Version >();
const auto vendor = platform.GetInfo<cl::Platform::Info::Vendor >();
const auto name = platform.GetInfo<cl::Platform::Info::Name >();
const auto extensions = platform.GetInfo<cl::Platform::Info::Extensions>();
}
void GetInfo (const cl::Device& device)
{
const auto type = device.GetInfo<cl::Device::Info::Type >();
const auto profile = device.GetInfo<cl::Device::Info::Profile >();
const auto version = device.GetInfo<cl::Device::Info::Version >();
const auto vendor = device.GetInfo<cl::Device::Info::Vendor >();
const auto name = device.GetInfo<cl::Device::Info::Name >();
const auto extensions = device.GetInfo<cl::Device::Info::Extensions >();
const auto vendorID = device.GetInfo<cl::Device::Info::VendorID >();
const auto driverVersion = device.GetInfo<cl::Device::Info::DriverVersion>();
}
void GetInfo (const cl::Context& context)
{
const auto numDevices = context.GetInfo<cl::Context::Info::NumDevices >();
const auto refCount = context.GetInfo<cl::Context::Info::ReferenceCount>();
}
int main ()
{
const auto platforms = cl::GetPlatforms();
for (const auto& platform : platforms)
{
GetInfo(platform);
const auto devices = platform.GetDevices();
for (const auto& device : devices)
{
GetInfo(device);
}
const auto context = cl::Context { platform, devices };
GetInfo(context);
for (const auto& device : devices)
{
const auto commandQueue = cl::CommandQueue { context, device };
}
auto program = cl::Program
{
context,
"__kernel void cl_main \n"
"( \n"
" __global const float* firstInput, \n"
" __global const float* secondInput, \n"
" __global float* output \n"
") \n"
"{ \n"
" int globalID = get_global_id(0); \n"
" \n"
" output[globalID] = firstInput[globalID] + secondInput[globalID]; \n"
"} \n"
};
program.Build();
auto kernel = cl::Kernel { program, "cl_main" };
const auto firstSrcMemory = cl::Memory
{
context,
cl::Memory::DeviceAccess::ReadOnly,
cl::Memory::HostAccess::ReadWrite,
cl::Memory::Alloc::Device,
std::vector<float>
{
1.5f, 7.6f, 8.1f, 1.5f, 1.7f, 2.4f, 9.0f, 3.5f,
},
};
const auto secondSrcMemory = cl::Memory
{
context,
cl::Memory::DeviceAccess::ReadOnly,
cl::Memory::HostAccess::ReadWrite,
cl::Memory::Alloc::Device,
std::vector<float>
{
3.6f, 7.0f, 0.8f, 4.3f, 2.7f, 6.5f, 2.8f, 1.4f,
},
};
const auto dstMemory = cl::Memory
{
context,
cl::Memory::DeviceAccess::WriteOnly,
cl::Memory::HostAccess::ReadWrite,
cl::Memory::Alloc::Device,
8
};
kernel.SetArg(0, firstSrcMemory);
kernel.SetArg(1, secondSrcMemory);
kernel.SetArg(2, dstMemory);
}
return 0;
}
<|endoftext|> |
<commit_before>/*******************************************************************************************
* This file is created to implement the class Duck for our game called PapraGame. *
* This file will allow us to have all the method to control the duck for the game. *
* This file are under licence Mozilla Public License Version 2.0 *
* Author : Barbier Julien, julien.barbier@utbm.fr *
* Date of creation : 01/19/2016 *
* *****************************************************************************************/
#ifndef MAP_HPP_INCLUDED
#define MAP_HPP_INCLUDED
#include <Coord>
#include <SFML/Graphics>
#include <enum>
#define NB_TEXTURE 8
class Map {
public :
/**
* @brief Destroy the class Map
*/
~Map();
/**
* @brief Creation of Map by default.
*/
Map () {};
/**
* @brief Creation of map with all the parametre needed.
* @param x The lenght of the map
* @param y The width of the map
* @param smap[x][y] The map himself with the lenght and the width.
* @param texture[NB_TEXTURE] Array which will contain the texture for this game.
* @param egg_texture Contain the texture of the egg.
*/
Map(unsigned char x, unsigned char y, Area smap[x][y], const String& texture[NB_TEXTURE], const String& egg_texture);
/**
* @brief Change the coordinates of the egg and print him.
* @param egg_coord The coordinate of the egg to initialize coordinate_egg(Map) and
*/
void popEgg (Coord egg_coord);
/**
* @brief Print a send case in the screen.
* @param coord The coordinate of the case we want to convert.
*/
void print(Coord coord);
/**
* @brief printAll Print all the map.
*/
void printAll();
private :
unsigned char x_size;
unsigned char y_size;
sf::Texture sprites[NB_TEXTURE];
Coord coordinate_egg;
sf::Texture egg_sprite;
Area map [] [];
};
#endif /* MAPP_HPP_INCLUDED*/
<commit_msg>magic of tabs<commit_after>/*******************************************************************************************
* This file is created to implement the class Duck for our game called PapraGame. *
* This file will allow us to have all the method to control the duck for the game. *
* This file are under licence Mozilla Public License Version 2.0 *
* Author : Barbier Julien, julien.barbier@utbm.fr *
* Date of creation : 01/19/2016 *
* *****************************************************************************************/
#ifndef MAP_HPP_INCLUDED
#define MAP_HPP_INCLUDED
#include <Coord>
#include <SFML/Graphics>
#include <enum>
#define NB_TEXTURE 8
class Map {
public :
/**
* @brief Destroy the class Map
*/
~Map();
/**
* @brief Creation of Map by default.
*/
Map () {};
/**
* @brief Creation of map with all the parametre needed.
* @param x The lenght of the map
* @param y The width of the map
* @param smap[x][y] The map himself with the lenght and the width.
* @param texture[NB_TEXTURE] Array which will contain the texture for this game.
* @param egg_texture Contain the texture of the egg.
*/
Map(unsigned char x, unsigned char y, Area smap[x][y], const String& texture[NB_TEXTURE], const String& egg_texture);
/**
* @brief Change the coordinates of the egg and print him.
* @param egg_coord The coordinate of the egg to initialize coordinate_egg(Map) and
*/
void popEgg (Coord egg_coord);
/**
* @brief Print a send case in the screen.
* @param coord The coordinate of the case we want to convert.
*/
void print(Coord coord);
/**
* @brief printAll Print all the map.
*/
void printAll();
private :
unsigned char x_size;
unsigned char y_size;
sf::Texture sprites[NB_TEXTURE];
Coord coordinate_egg;
sf::Texture egg_sprite;
Area map [] [];
};
#endif /* MAPP_HPP_INCLUDED*/
<|endoftext|> |
<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <vector>
#include <string>
#include <cmath>
#include <map>
#include <fstream>
#include <utils.hpp>
#include <Observation.hpp>
#ifndef SNR_HPP
#define SNR_HPP
namespace PulsarSearch {
class snrConf {
public:
snrConf();
~snrConf();
// Get
unsigned int getNrThreadsD0() const;
unsigned int getNrItemsD0() const;
// Set
void setNrThreadsD0(unsigned int threads);
void setNrItemsD0(unsigned int items);
// utils
std::string print() const;
private:
unsigned int nrThreadsD0;
unsigned int nrItemsD0;
};
typedef std::map< std::string, std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrConf * > * > * > tunedSNRConf;
// OpenCL SNR
template< typename T > std::string * getSNRDMsSamplesOpenCL(const snrConf & conf, const std::string & dataName, const unsigned int nrSamples, const unsigned int padding);
template< typename T > std::string * getSNRSamplesDMsOpenCL(const snrConf & conf, const std::string & dataName, const AstroData::Observation & observation, const unsigned int padding);
// Read configuration files
void readTunedSNRConf(tunedSNRConf & tunedSNR, const std::string & snrFilename);
// Implementations
inline unsigned int snrConf::getNrThreadsD0() const {
return nrThreadsD0;
}
inline unsigned int snrConf::getNrItemsD0() const {
return nrItemsD0;
}
inline void snrConf::setNrThreadsD0(unsigned int threads) {
nrThreadsD0 = threads;
}
inline void snrConf::setNrItemsD0(unsigned int items) {
nrItemsD0 = items;
}
template< typename T > std::string * getSNRDMsSamplesOpenCL(const snrConf & conf, const std::string & dataName, const unsigned int nrSamples, const unsigned int padding) {
std::string * code = new std::string();
// Begin kernel's template
*code = "__kernel void snrDMsSamples" + isa::utils::toString(nrSamples) + "(__global const " + dataName + " * const restrict input, __global float * const restrict output) {\n"
"unsigned int dm = get_group_id(1);\n"
"float delta = 0.0f;\n"
"__local float reductionCOU[" + isa::utils::toString(isa::utils::pad(conf.getNrThreadsD0(), padding / sizeof(T))) + "];\n"
"__local " + dataName + " reductionMAX[" + isa::utils::toString(isa::utils::pad(conf.getNrThreadsD0(), padding / sizeof(T))) + "];\n"
"__local float reductionMEA[" + isa::utils::toString(isa::utils::pad(conf.getNrThreadsD0(), padding / sizeof(T))) + "];\n"
"__local float reductionVAR[" + isa::utils::toString(isa::utils::pad(conf.getNrThreadsD0(), padding / sizeof(T))) + "];\n"
"<%DEF%>"
"\n"
"// Compute phase\n"
"for ( unsigned int sample = get_local_id(0) + " + isa::utils::toString(conf.getNrThreadsD0() * conf.getNrItemsD0()) + "; sample < " + isa::utils::toString(nrSamples) + "; sample += " + isa::utils::toString(conf.getNrThreadsD0() * conf.getNrItemsD0()) + " ) {\n"
+ dataName + " item = 0;\n"
"<%COMPUTE%>"
"}\n"
"// In-thread reduce\n"
"<%REDUCE%>"
"// Local memory store\n"
"reductionCOU[get_local_id(0)] = counter0;\n"
"reductionMAX[get_local_id(0)] = max0;\n"
"reductionMEA[get_local_id(0)] = mean0;\n"
"reductionVAR[get_local_id(0)] = variance0;\n"
"barrier(CLK_LOCAL_MEM_FENCE);\n"
"// Reduce phase\n"
"unsigned int threshold = " + isa::utils::toString(conf.getNrThreadsD0() / 2) + ";\n"
"for ( unsigned int sample = get_local_id(0); threshold > 0; threshold /= 2 ) {\n"
"if ( sample < threshold ) {\n"
"delta = reductionMEA[sample + threshold] - mean0;\n"
"counter0 += reductionCOU[sample + threshold];\n"
"max0 = fmax(max0, reductionMAX[sample + threshold]);\n"
"mean0 = ((reductionCOU[sample] * mean0) + (reductionCOU[sample + threshold] * reductionMEA[sample + threshold])) / counter0;\n"
"variance0 += reductionVAR[sample + threshold] + ((delta * delta) * ((reductionCOU[sample] * reductionCOU[sample + threshold]) / counter0));\n"
"reductionCOU[get_local_id(0)] = counter0;\n"
"reductionMAX[get_local_id(0)] = max0;\n"
"reductionMEA[get_local_id(0)] = mean0;\n"
"reductionVAR[get_local_id(0)] = variance0;\n"
"}\n"
"barrier(CLK_LOCAL_MEM_FENCE);\n"
"}\n"
"// Store\n"
"if ( get_local_id(0) == 0 ) {\n"
"output[dm] = (max0 - mean0) / native_sqrt(variance0 * " + isa::utils::toString(1.0f / (nrSamples - 1)) + "f);\n"
"}\n"
"}\n";
std::string def_sTemplate = "float counter<%NUM%> = 1.0f;\n"
+ dataName + " max<%NUM%> = input[(dm * " + isa::utils::toString(isa::utils::pad(nrSamples, padding / sizeof(T))) + ") + (get_local_id(0) + <%OFFSET%>)];\n"
"float variance<%NUM%> = 0.0f;\n"
"float mean<%NUM%> = max<%NUM%>;\n";
std::string compute_sTemplate = "item = input[(dm * " + isa::utils::toString(isa::utils::pad(nrSamples, padding / sizeof(T))) + ") + (sample + <%OFFSET%>)];\n"
"counter<%NUM%> += 1.0f;\n"
"delta = item - mean<%NUM%>;\n"
"max<%NUM%> = fmax(max<%NUM%>, item);\n"
"mean<%NUM%> += delta / counter<%NUM%>;\n"
"variance<%NUM%> += delta * (item - mean<%NUM%>);\n";
std::string reduce_sTemplate = "delta = mean<%NUM%> - mean0;\n"
"counter0 += counter<%NUM%>;\n"
"max0 = fmax(max0, max<%NUM%>);\n"
"mean0 = (((counter0 - counter<%NUM%>) * mean0) + (counter<%NUM%> * mean<%NUM%>)) / counter0;\n"
"variance0 += variance<%NUM%> + ((delta * delta) * (((counter0 - counter<%NUM%>) * counter<%NUM%>) / counter0));\n";
// End kernel's template
std::string * def_s = new std::string();
std::string * compute_s = new std::string();
std::string * reduce_s = new std::string();
for ( unsigned int sample = 0; sample < conf.getNrItemsD0(); sample++ ) {
std::string sample_s = isa::utils::toString(sample);
std::string offset_s = isa::utils::toString(conf.getNrThreadsD0() * sample);
std::string * temp = 0;
temp = isa::utils::replace(&def_sTemplate, "<%NUM%>", sample_s);
if ( sample == 0 ) {
std::string empty_s("");
temp = isa::utils::replace(temp, " + <%OFFSET%>", empty_s, true);
} else {
temp = isa::utils::replace(temp, "<%OFFSET%>", offset_s, true);
}
def_s->append(*temp);
delete temp;
temp = isa::utils::replace(&compute_sTemplate, "<%NUM%>", sample_s);
if ( sample == 0 ) {
std::string empty_s("");
temp = isa::utils::replace(temp, " + <%OFFSET%>", empty_s, true);
} else {
temp = isa::utils::replace(temp, "<%OFFSET%>", offset_s, true);
}
compute_s->append(*temp);
delete temp;
if ( sample == 0 ) {
continue;
}
temp = isa::utils::replace(&reduce_sTemplate, "<%NUM%>", sample_s);
reduce_s->append(*temp);
delete temp;
}
code = isa::utils::replace(code, "<%DEF%>", *def_s, true);
code = isa::utils::replace(code, "<%COMPUTE%>", *compute_s, true);
code = isa::utils::replace(code, "<%REDUCE%>", *reduce_s, true);
delete def_s;
delete compute_s;
delete reduce_s;
return code;
}
template< typename T > std::string * getSNRSamplesDMsOpenCL(const snrConf & conf, const std::string & dataName, const AstroData::Observation & observation, const unsigned int padding) {
std::string * code = new std::string();
// Begin kernel's template
*code = "__kernel void snrSamplesDMs" + isa::utils::toString(observation.getNrDMs()) + "(__global const " + dataName + " * const restrict input, __global float * const restrict output) {\n"
"unsigned int dm = (" + isa::utils::toString(conf.getNrThreadsD0() * conf.getNrItemsD0()) + ") + get_local_id(0);\n"
"<%DEF%>"
"\n"
"for ( unsigned int sample = 1; sample < " + isa::utils::toString(observation.getNrSamplesPerSecond()) + "; sample++ ) {\n"
+ dataName + " item = 0;\n"
"<%COMPUTE%>"
"}\n"
"<%STORE%>"
"}\n";
std::string def_sTemplate = "float counter<%NUM%> = 1.0f;\n"
+ dataName + " max<%NUM%> = input[dm + <%OFFSET%>];\n"
"float variance<%NUM%> = 0.0f;\n"
"float mean<%NUM%> = max<%NUM%>;\n";
std::string compute_sTemplate = "item = input[(sample * " + isa::utils::toString(observation.getNrPaddedDMs(padding / sizeof(T))) + " + (dm + <%OFFSET%>)];\n"
"counter<%NUM%> += 1.0f;\n"
"delta = item - mean<%NUM%>;\n"
"max<%NUM%> = fmax(max<%NUM%>, item);\n"
"mean<%NUM%> += delta / counter<%NUM%>;\n"
"variance<%NUM%> += delta * (item - mean<%NUM%>);\n";
std::string store_sTemplate;
if ( dataName == "double" ) {
store_sTemplate = "output[dm + <%OFFSET%>] = (max<%NUM%> - mean<%NUM%>) / native_sqrt(variance<%NUM%> * " + isa::utils::toString(1.0 / (observation.getNrSamplesPerSecond() - 1)) + ");\n";
} else if ( dataName == "float" ) {
store_sTemplate = "output[dm + <%OFFSET%>] = (max<%NUM%> - mean<%NUM%>) / native_sqrt(variance<%NUM%> * " + isa::utils::toString(1.0f / (observation.getNrSamplesPerSecond() - 1)) + "f);\n";
} else {
store_sTemplate = "output[dm + <%OFFSET%>] = (max<%NUM%> - mean<%NUM%>) / native_sqrt(variance<%NUM%> / " + isa::utils::toString(observation.getNrSamplesPerSecond() - 1) + "f);\n";
}
// End kernel's template
std::string * def_s = new std::string();
std::string * compute_s = new std::string();
std::string * store_s = new std::string();
for ( unsigned int dm = 0; dm < conf.getNrItemsD0(); dm++ ) {
std::string dm_s = isa::utils::toString(dm);
std::string offset_s = isa::utils::toString(conf.getNrThreadsD0() * dm);
std::string * temp = 0;
temp = isa::utils::replace(&def_sTemplate, "<%NUM%>", dm_s);
if ( dm == 0 ) {
std::string empty_s("");
temp = isa::utils::replace(temp, " + <%OFFSET%>", empty_s, true);
} else {
temp = isa::utils::replace(temp, "<%OFFSET%>", offset_s, true);
}
def_s->append(*temp);
delete temp;
temp = isa::utils::replace(&compute_sTemplate, "<%NUM%>", dm_s);
if ( dm == 0 ) {
std::string empty_s("");
temp = isa::utils::replace(temp, " + <%OFFSET%>", empty_s, true);
} else {
temp = isa::utils::replace(temp, "<%OFFSET%>", offset_s, true);
}
compute_s->append(*temp);
delete temp;
temp = isa::utils::replace(&store_sTemplate, "<%NUM%>", dm_s);
if ( dm == 0 ) {
std::string empty_s("");
temp = isa::utils::replace(temp, " + <%OFFSET%>", empty_s, true);
} else {
temp = isa::utils::replace(temp, "<%OFFSET%>", offset_s, true);
}
store_s->append(*temp);
delete temp;
}
code = isa::utils::replace(code, "<%DEF%>", *def_s, true);
code = isa::utils::replace(code, "<%COMPUTE%>", *compute_s, true);
code = isa::utils::replace(code, "<%STORE%>", *store_s, true);
delete def_s;
delete compute_s;
delete store_s;
return code;
}
} // PulsarSearch
#endif // SNR_HPP
<commit_msg>Fixed a couple bugs in the OpenCL code.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <vector>
#include <string>
#include <cmath>
#include <map>
#include <fstream>
#include <utils.hpp>
#include <Observation.hpp>
#ifndef SNR_HPP
#define SNR_HPP
namespace PulsarSearch {
class snrConf {
public:
snrConf();
~snrConf();
// Get
unsigned int getNrThreadsD0() const;
unsigned int getNrItemsD0() const;
// Set
void setNrThreadsD0(unsigned int threads);
void setNrItemsD0(unsigned int items);
// utils
std::string print() const;
private:
unsigned int nrThreadsD0;
unsigned int nrItemsD0;
};
typedef std::map< std::string, std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrConf * > * > * > tunedSNRConf;
// OpenCL SNR
template< typename T > std::string * getSNRDMsSamplesOpenCL(const snrConf & conf, const std::string & dataName, const unsigned int nrSamples, const unsigned int padding);
template< typename T > std::string * getSNRSamplesDMsOpenCL(const snrConf & conf, const std::string & dataName, const AstroData::Observation & observation, const unsigned int padding);
// Read configuration files
void readTunedSNRConf(tunedSNRConf & tunedSNR, const std::string & snrFilename);
// Implementations
inline unsigned int snrConf::getNrThreadsD0() const {
return nrThreadsD0;
}
inline unsigned int snrConf::getNrItemsD0() const {
return nrItemsD0;
}
inline void snrConf::setNrThreadsD0(unsigned int threads) {
nrThreadsD0 = threads;
}
inline void snrConf::setNrItemsD0(unsigned int items) {
nrItemsD0 = items;
}
template< typename T > std::string * getSNRDMsSamplesOpenCL(const snrConf & conf, const std::string & dataName, const unsigned int nrSamples, const unsigned int padding) {
std::string * code = new std::string();
// Begin kernel's template
*code = "__kernel void snrDMsSamples" + isa::utils::toString(nrSamples) + "(__global const " + dataName + " * const restrict input, __global float * const restrict output) {\n"
"unsigned int dm = get_group_id(1);\n"
"float delta = 0.0f;\n"
"__local float reductionCOU[" + isa::utils::toString(isa::utils::pad(conf.getNrThreadsD0(), padding / sizeof(T))) + "];\n"
"__local " + dataName + " reductionMAX[" + isa::utils::toString(isa::utils::pad(conf.getNrThreadsD0(), padding / sizeof(T))) + "];\n"
"__local float reductionMEA[" + isa::utils::toString(isa::utils::pad(conf.getNrThreadsD0(), padding / sizeof(T))) + "];\n"
"__local float reductionVAR[" + isa::utils::toString(isa::utils::pad(conf.getNrThreadsD0(), padding / sizeof(T))) + "];\n"
"<%DEF%>"
"\n"
"// Compute phase\n"
"for ( unsigned int sample = get_local_id(0) + " + isa::utils::toString(conf.getNrThreadsD0() * conf.getNrItemsD0()) + "; sample < " + isa::utils::toString(nrSamples) + "; sample += " + isa::utils::toString(conf.getNrThreadsD0() * conf.getNrItemsD0()) + " ) {\n"
+ dataName + " item = 0;\n"
"<%COMPUTE%>"
"}\n"
"// In-thread reduce\n"
"<%REDUCE%>"
"// Local memory store\n"
"reductionCOU[get_local_id(0)] = counter0;\n"
"reductionMAX[get_local_id(0)] = max0;\n"
"reductionMEA[get_local_id(0)] = mean0;\n"
"reductionVAR[get_local_id(0)] = variance0;\n"
"barrier(CLK_LOCAL_MEM_FENCE);\n"
"// Reduce phase\n"
"unsigned int threshold = " + isa::utils::toString(conf.getNrThreadsD0() / 2) + ";\n"
"for ( unsigned int sample = get_local_id(0); threshold > 0; threshold /= 2 ) {\n"
"if ( sample < threshold ) {\n"
"delta = reductionMEA[sample + threshold] - mean0;\n"
"counter0 += reductionCOU[sample + threshold];\n"
"max0 = fmax(max0, reductionMAX[sample + threshold]);\n"
"mean0 = ((reductionCOU[sample] * mean0) + (reductionCOU[sample + threshold] * reductionMEA[sample + threshold])) / counter0;\n"
"variance0 += reductionVAR[sample + threshold] + ((delta * delta) * ((reductionCOU[sample] * reductionCOU[sample + threshold]) / counter0));\n"
"reductionCOU[get_local_id(0)] = counter0;\n"
"reductionMAX[get_local_id(0)] = max0;\n"
"reductionMEA[get_local_id(0)] = mean0;\n"
"reductionVAR[get_local_id(0)] = variance0;\n"
"}\n"
"barrier(CLK_LOCAL_MEM_FENCE);\n"
"}\n"
"// Store\n"
"if ( get_local_id(0) == 0 ) {\n"
"output[dm] = (max0 - mean0) / native_sqrt(variance0 * " + isa::utils::toString(1.0f / (nrSamples - 1)) + "f);\n"
"}\n"
"}\n";
std::string def_sTemplate = "float counter<%NUM%> = 1.0f;\n"
+ dataName + " max<%NUM%> = input[(dm * " + isa::utils::toString(isa::utils::pad(nrSamples, padding / sizeof(T))) + ") + (get_local_id(0) + <%OFFSET%>)];\n"
"float variance<%NUM%> = 0.0f;\n"
"float mean<%NUM%> = max<%NUM%>;\n";
std::string compute_sTemplate = "item = input[(dm * " + isa::utils::toString(isa::utils::pad(nrSamples, padding / sizeof(T))) + ") + (sample + <%OFFSET%>)];\n"
"counter<%NUM%> += 1.0f;\n"
"delta = item - mean<%NUM%>;\n"
"max<%NUM%> = fmax(max<%NUM%>, item);\n"
"mean<%NUM%> += delta / counter<%NUM%>;\n"
"variance<%NUM%> += delta * (item - mean<%NUM%>);\n";
std::string reduce_sTemplate = "delta = mean<%NUM%> - mean0;\n"
"counter0 += counter<%NUM%>;\n"
"max0 = fmax(max0, max<%NUM%>);\n"
"mean0 = (((counter0 - counter<%NUM%>) * mean0) + (counter<%NUM%> * mean<%NUM%>)) / counter0;\n"
"variance0 += variance<%NUM%> + ((delta * delta) * (((counter0 - counter<%NUM%>) * counter<%NUM%>) / counter0));\n";
// End kernel's template
std::string * def_s = new std::string();
std::string * compute_s = new std::string();
std::string * reduce_s = new std::string();
for ( unsigned int sample = 0; sample < conf.getNrItemsD0(); sample++ ) {
std::string sample_s = isa::utils::toString(sample);
std::string offset_s = isa::utils::toString(conf.getNrThreadsD0() * sample);
std::string * temp = 0;
temp = isa::utils::replace(&def_sTemplate, "<%NUM%>", sample_s);
if ( sample == 0 ) {
std::string empty_s("");
temp = isa::utils::replace(temp, " + <%OFFSET%>", empty_s, true);
} else {
temp = isa::utils::replace(temp, "<%OFFSET%>", offset_s, true);
}
def_s->append(*temp);
delete temp;
temp = isa::utils::replace(&compute_sTemplate, "<%NUM%>", sample_s);
if ( sample == 0 ) {
std::string empty_s("");
temp = isa::utils::replace(temp, " + <%OFFSET%>", empty_s, true);
} else {
temp = isa::utils::replace(temp, "<%OFFSET%>", offset_s, true);
}
compute_s->append(*temp);
delete temp;
if ( sample == 0 ) {
continue;
}
temp = isa::utils::replace(&reduce_sTemplate, "<%NUM%>", sample_s);
reduce_s->append(*temp);
delete temp;
}
code = isa::utils::replace(code, "<%DEF%>", *def_s, true);
code = isa::utils::replace(code, "<%COMPUTE%>", *compute_s, true);
code = isa::utils::replace(code, "<%REDUCE%>", *reduce_s, true);
delete def_s;
delete compute_s;
delete reduce_s;
return code;
}
template< typename T > std::string * getSNRSamplesDMsOpenCL(const snrConf & conf, const std::string & dataName, const AstroData::Observation & observation, const unsigned int padding) {
std::string * code = new std::string();
// Begin kernel's template
*code = "__kernel void snrSamplesDMs" + isa::utils::toString(observation.getNrDMs()) + "(__global const " + dataName + " * const restrict input, __global float * const restrict output) {\n"
"unsigned int dm = (" + isa::utils::toString(conf.getNrThreadsD0() * conf.getNrItemsD0()) + ") + get_local_id(0);\n"
"float delta = 0.0f;\n"
"<%DEF%>"
"\n"
"for ( unsigned int sample = 1; sample < " + isa::utils::toString(observation.getNrSamplesPerSecond()) + "; sample++ ) {\n"
+ dataName + " item = 0;\n"
"<%COMPUTE%>"
"}\n"
"<%STORE%>"
"}\n";
std::string def_sTemplate = "float counter<%NUM%> = 1.0f;\n"
+ dataName + " max<%NUM%> = input[dm + <%OFFSET%>];\n"
"float variance<%NUM%> = 0.0f;\n"
"float mean<%NUM%> = max<%NUM%>;\n";
std::string compute_sTemplate = "item = input[(sample * " + isa::utils::toString(observation.getNrPaddedDMs(padding / sizeof(T))) + ") + (dm + <%OFFSET%>)];\n"
"counter<%NUM%> += 1.0f;\n"
"delta = item - mean<%NUM%>;\n"
"max<%NUM%> = fmax(max<%NUM%>, item);\n"
"mean<%NUM%> += delta / counter<%NUM%>;\n"
"variance<%NUM%> += delta * (item - mean<%NUM%>);\n";
std::string store_sTemplate;
if ( dataName == "double" ) {
store_sTemplate = "output[dm + <%OFFSET%>] = (max<%NUM%> - mean<%NUM%>) / native_sqrt(variance<%NUM%> * " + isa::utils::toString(1.0 / (observation.getNrSamplesPerSecond() - 1)) + ");\n";
} else if ( dataName == "float" ) {
store_sTemplate = "output[dm + <%OFFSET%>] = (max<%NUM%> - mean<%NUM%>) / native_sqrt(variance<%NUM%> * " + isa::utils::toString(1.0f / (observation.getNrSamplesPerSecond() - 1)) + "f);\n";
} else {
store_sTemplate = "output[dm + <%OFFSET%>] = (max<%NUM%> - mean<%NUM%>) / native_sqrt(variance<%NUM%> / " + isa::utils::toString(observation.getNrSamplesPerSecond() - 1) + "f);\n";
}
// End kernel's template
std::string * def_s = new std::string();
std::string * compute_s = new std::string();
std::string * store_s = new std::string();
for ( unsigned int dm = 0; dm < conf.getNrItemsD0(); dm++ ) {
std::string dm_s = isa::utils::toString(dm);
std::string offset_s = isa::utils::toString(conf.getNrThreadsD0() * dm);
std::string * temp = 0;
temp = isa::utils::replace(&def_sTemplate, "<%NUM%>", dm_s);
if ( dm == 0 ) {
std::string empty_s("");
temp = isa::utils::replace(temp, " + <%OFFSET%>", empty_s, true);
} else {
temp = isa::utils::replace(temp, "<%OFFSET%>", offset_s, true);
}
def_s->append(*temp);
delete temp;
temp = isa::utils::replace(&compute_sTemplate, "<%NUM%>", dm_s);
if ( dm == 0 ) {
std::string empty_s("");
temp = isa::utils::replace(temp, " + <%OFFSET%>", empty_s, true);
} else {
temp = isa::utils::replace(temp, "<%OFFSET%>", offset_s, true);
}
compute_s->append(*temp);
delete temp;
temp = isa::utils::replace(&store_sTemplate, "<%NUM%>", dm_s);
if ( dm == 0 ) {
std::string empty_s("");
temp = isa::utils::replace(temp, " + <%OFFSET%>", empty_s, true);
} else {
temp = isa::utils::replace(temp, "<%OFFSET%>", offset_s, true);
}
store_s->append(*temp);
delete temp;
}
code = isa::utils::replace(code, "<%DEF%>", *def_s, true);
code = isa::utils::replace(code, "<%COMPUTE%>", *compute_s, true);
code = isa::utils::replace(code, "<%STORE%>", *store_s, true);
delete def_s;
delete compute_s;
delete store_s;
return code;
}
} // PulsarSearch
#endif // SNR_HPP
<|endoftext|> |
<commit_before>#pragma once
#include <cstddef>
#include <functional>
#include <arbor/common_types.hpp>
#include <arbor/util/any_ptr.hpp>
namespace arb {
using cell_member_predicate = std::function<bool (cell_member_type)>;
static cell_member_predicate all_probes = [](cell_member_type pid) { return true; };
static inline cell_member_predicate one_probe(cell_member_type pid) {
return [pid](cell_member_type x) { return pid==x; };
}
struct sample_record {
time_type time;
util::any_ptr data;
};
using sampler_function = std::function<void (cell_member_type, probe_tag, std::size_t, const sample_record*)>;
using sampler_association_handle = std::size_t;
enum class sampling_policy {
lax,
// interpolated, // placeholder: unsupported
// exact // placeholder: unsupported
};
} // namespace arb
<commit_msg>Workaround for Juwels link error. (#747)<commit_after>#pragma once
#include <cstddef>
#include <functional>
#include <arbor/common_types.hpp>
#include <arbor/util/any_ptr.hpp>
namespace arb {
using cell_member_predicate = std::function<bool (cell_member_type)>;
static cell_member_predicate all_probes = [](cell_member_type pid) { return true; };
inline cell_member_predicate one_probe(cell_member_type pid) {
return [pid](cell_member_type x) { return pid==x; };
}
struct sample_record {
time_type time;
util::any_ptr data;
};
using sampler_function = std::function<void (cell_member_type, probe_tag, std::size_t, const sample_record*)>;
using sampler_association_handle = std::size_t;
enum class sampling_policy {
lax,
// interpolated, // placeholder: unsupported
// exact // placeholder: unsupported
};
} // namespace arb
<|endoftext|> |
<commit_before>#include <iostream>
#include <stdio.h>
#include <pthread.h>
using namespace std;
// bool RequestToSend = false;
bool ArrivalNotificationSenderSide = false;
// bool TimeOut = false;
// bool ArrivalNotificationReceiverSide = false;
// int Sw = pow(2, m-1);
// int Sf = 0;
// int Sn = 0;
int Rn = 0;
bool NakSent = false;
bool AckNeeded = false;
//ssh test
int scount = 0;
int rcount = 0;
void * sending(void* arg){
//spawn three event threads
while(true){
scount++;
printf("sending.....%d\n",scount);
// if(RequestToSend == true){
// if(Sn -Sf >= Sw){
// Sleep();
// }
// if(Sn - Sf < Sw){
// GetData();
// MakeFrame(Sn);
// StoreFrame(Sn);
// SendFrame(Sn);
// Sn = Sn + 1;
// StartTimer(Sn);
// }
// }
// if(ArrivalNotificationSenderSide == true){
// Receive(frame);
// if(corrupted(frame))
// Sleep();
// else{
// if(FrameType == NAK){
// if(nakNo >= Sf && nakNo <= Sn){
// resend(nakNo);
// StartTimer(nakNo);
// }
// }
// if(FrameType == ACK){
// if(ackNo >= Sf && ackNo <= Sn){
// while(Sf < ackNo){
// Purge(Sf);
// StopTimer(Sf);
// Sf = Sf + 1;
// }
// }
// }
// }
// }
// if(TimeOut == true){
// StartTimer(t);
// SendFrame(t)
// }
}
}
bool corrupted(char frame)
{
return true;
}
void * waitforevent(void * argv){
if(data successfully received)
ArrivalNotificationReceiverSide=true;
}
void * receiving(void *arg){
pthread_t receivertestthread;
pthread_create(&receivertestthread,NULL,waitforevent,NULL);
while(true){
rcount++;
printf("receiving.....%d\n",rcount);
if(ArrivalNotificationReceiverSide == true){
ArrivalNotificationReceiverSide=false;
Receive(Frame);
if(corrupted(Frame) && (! NakSent)){
SendNAK(Rn);
NakSent = true;
//sleep();
}
if((seqNo != Rn){
if(! NakSent){
SendNAK(Rn);
NakSent = true;
}
if((seqNo in window) && (!Marked(seqNo))){
StoreFrame(seqNo);
Marked(seqNo) = true; }
}
else{
Marked(Rn)=true;
while(Marked(Rn)){
DeliverData(Rn);
Purge(Rn);
Rn = Rn + 1;
AckNeeded = true;
}
if(AckNeeded == true){
sendAck(Rn);
AckNeeded = false;
NakSent = false;
}
}
}
}
pthread_join(receivertestthread,NULL);
}
int main(){
//Spawn two threads which do the
//sending and receiving
pthread_t sendingThread, receivingThread;
pthread_create(&sendingThread, NULL, sending, NULL);
pthread_create(&receivingThread, NULL, receiving, NULL);
pthread_join(sendingThread, NULL);
pthread_join(receivingThread, NULL);
pthread_exit(NULL);
return 0;
}<commit_msg>basic framework<commit_after>#include <iostream>
#include <stdio.h>
#include <pthread.h>
using namespace std;
class Frame{
public:
char seqNo;
char value;
char crcRemainder;
};
// bool RequestToSend = false;
bool ArrivalNotificationSenderSide = false;
// bool TimeOut = false;
// bool ArrivalNotificationReceiverSide = false;
// int Sw = pow(2, m-1);
// int Sf = 0;
// int Sn = 0;
int Rn = 0;
bool NakSent = false;
bool AckNeeded = false;
//ssh test
int scount = 0;
int rcount = 0;
void * sending(void* arg){
//spawn three event threads
while(true){
scount++;
printf("sending.....%d\n",scount);
// if(RequestToSend == true){
// if(Sn -Sf >= Sw){
// Sleep();
// }
// if(Sn - Sf < Sw){
// GetData();
// MakeFrame(Sn);
// StoreFrame(Sn);
// SendFrame(Sn);
// Sn = Sn + 1;
// StartTimer(Sn);
// }
// }
// if(ArrivalNotificationSenderSide == true){
// Receive(frame);
// if(corrupted(frame))
// Sleep();
// else{
// if(FrameType == NAK){
// if(nakNo >= Sf && nakNo <= Sn){
// resend(nakNo);
// StartTimer(nakNo);
// }
// }
// if(FrameType == ACK){
// if(ackNo >= Sf && ackNo <= Sn){
// while(Sf < ackNo){
// Purge(Sf);
// StopTimer(Sf);
// Sf = Sf + 1;
// }
// }
// }
// }
// }
// if(TimeOut == true){
// StartTimer(t);
// SendFrame(t)
// }
}
}
bool check=false;
int ReceiveIndex=0;
char data[1000];
bool Marked[8];
int TempArray[8];
char DataReceived;
bool corrupted(int a,int b)
{
if(a%b == 0)
return true;
else
return false;
}
void * waitforevent(void * argv){
if(data successfully received and check!=true)
ArrivalNotificationReceiverSide=true;
}
void SendNAK(int n)
{
//socket for sending NAK
}
void sendAck(int n)
{
//socket for sending Ack
}
void DeliverData(int n)
{
if(TempArray[n]!= -1 )
data[ReceiveIndex++]=TempArray[n];
else
data[ReceiveIndex++]=DataReceived;
}
void Purge(int n){
TempArray[n]=-1;
Marked[n]=false;
}
void * receiving(void *arg){
for(int i=0;i<8;i++)
Marked[i]=false;
pthread_t receivertestthread;
pthread_create(&receivertestthread,NULL,waitforevent,NULL);
while(true){
rcount++;
printf("receiving.....%d\n",rcount);
if(ArrivalNotificationReceiverSide == true){
check=true;
Receive(Frame);
if(corrupted(Frame) && (! NakSent)){
SendNAK(Rn);
NakSent = true;
//sleep();
}
if((seqNo != Rn){
if(!NakSent){
SendNAK(Rn);
NakSent = true;
}
if(( 0<=seqNo && seqNo<=7 ) && (!Marked[seqNo])){
StoreFrame(seqNo);
TempArray[seqNo]=frame.data;
Marked[seqNo] = true;
}
}
else{
Marked[Rn]=true;
while(Marked[Rn]){
DeliverData(Rn);
Purge(Rn);
Rn = Rn + 1;
AckNeeded = true;
}
if(AckNeeded == true){
sendAck(Rn);
AckNeeded = false;
NakSent = false;
}
}
check=false;
ArrivalNotificationReceiverSide=false;
}
}
pthread_join(receivertestthread,NULL);
}
int main(){
//Spawn two threads which do the
//sending and receiving
pthread_t sendingThread, receivingThread;
pthread_create(&sendingThread, NULL, sending, NULL);
pthread_create(&receivingThread, NULL, receiving, NULL);
pthread_join(sendingThread, NULL);
pthread_join(receivingThread, NULL);
pthread_exit(NULL);
return 0;
}<|endoftext|> |
<commit_before>/*
* Copyright 2015 Kevin Murray <spam@kdmurray.id.au>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// This file is a demonstration of how to parse reads with libqc++
// It's also used to test the parsing code.
#include <iostream>
#include <string>
#include "qcpp.hh"
#include "qc-length.hh"
int
main (int argc, char *argv[])
{
qcpp::Read r;
qcpp::ReadParser rp;
qcpp::ReadProcessorPipeline pipe;
if (argc != 2) {
std::cerr << "USAGE: " << argv[0] << " <read_file>" << std::endl;
return EXIT_FAILURE;
}
rp.open(argv[1]);
pipe.append_processor<qcpp::ReadLenCounter>("Count length");
while (rp.parse_read(r)) {
pipe.process_read(r);
}
std::cout << pipe.report();
return EXIT_SUCCESS;
}
<commit_msg>Remove util/qclencount.cc<commit_after><|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.