text stringlengths 54 60.6k |
|---|
<commit_before>/******************************************************************************
* Copyright (c) 2000-2016 Ericsson Telecom AB
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Balasko, Jeno
* Raduly, Csaba
* Szabo, Janos Zoltan – initial implementation
*
******************************************************************************/
#include "dbgnew.hh"
#include <stddef.h>
#undef new
static void *dummy = NULL;
void *operator new(size_t size) throw (std::bad_alloc)
{
return Malloc(size);
}
void *operator new[](size_t size) throw (std::bad_alloc)
{
if (size == 0) return &dummy;
else return Malloc(size);
}
void operator delete(void *ptr) throw()
{
Free(ptr);
}
void operator delete[](void *ptr) throw()
{
if (ptr != (void*)&dummy) Free(ptr);
}
/**************************************************************************/
#ifdef MEMORY_DEBUG
// overloads for memory debug
void* operator new(size_t size, const char* file, int line)
{
return Malloc_dbg(file, line, size);
}
void* operator new[](size_t size, const char* file, int line)
{
if (size == 0) return &dummy;
else return Malloc_dbg(file, line, size);
}
void* operator new(size_t size, const std::nothrow_t&, const char* file, int line)
{
return Malloc_dbg(file, line, size);
}
void* operator new[](size_t size, const std::nothrow_t&, const char* file, int line)
{
if (size == 0) return &dummy;
else return Malloc_dbg(file, line, size);
}
int debug_new_counter_t::count = 0; // initial value
#if defined(__CYGWIN__) || defined(INTERIX)
extern char**__argv;
#else
const char * __argv [] __attribute__((weak)) =
{
"program"
};
#endif
const char * debug_new_counter_t::progname = __argv[0];
debug_new_counter_t::debug_new_counter_t()
{
++count;
}
debug_new_counter_t::~debug_new_counter_t()
{
if (--count == 0) {
check_mem_leak(progname);
}
}
void debug_new_counter_t::set_program_name(const char * pgn)
{
progname = pgn;
}
#endif // MEMORY_DEBUG
<commit_msg>build experiment: lets use GNU -s solution for handling C++ standard's throw related changes (needs to be tested on many platforms)<commit_after>/******************************************************************************
* Copyright (c) 2000-2016 Ericsson Telecom AB
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Balasko, Jeno
* Raduly, Csaba
* Szabo, Janos Zoltan – initial implementation
*
******************************************************************************/
#include "dbgnew.hh"
#include <stddef.h>
#undef new
static void *dummy = NULL;
void *operator new(size_t size) _GLIBCXX_THROW (std::bad_alloc)
{
return Malloc(size);
}
void *operator new[](size_t size) _GLIBCXX_THROW (std::bad_alloc)
{
if (size == 0) return &dummy;
else return Malloc(size);
}
void operator delete(void *ptr) _GLIBCXX_USE_NOEXCEPT
{
Free(ptr);
}
void operator delete[](void *ptr) _GLIBCXX_USE_NOEXCEPT
{
if (ptr != (void*)&dummy) Free(ptr);
}
/**************************************************************************/
#ifdef MEMORY_DEBUG
// overloads for memory debug
void* operator new(size_t size, const char* file, int line)
{
return Malloc_dbg(file, line, size);
}
void* operator new[](size_t size, const char* file, int line)
{
if (size == 0) return &dummy;
else return Malloc_dbg(file, line, size);
}
void* operator new(size_t size, const std::nothrow_t&, const char* file, int line)
{
return Malloc_dbg(file, line, size);
}
void* operator new[](size_t size, const std::nothrow_t&, const char* file, int line)
{
if (size == 0) return &dummy;
else return Malloc_dbg(file, line, size);
}
int debug_new_counter_t::count = 0; // initial value
#if defined(__CYGWIN__) || defined(INTERIX)
extern char**__argv;
#else
const char * __argv [] __attribute__((weak)) =
{
"program"
};
#endif
const char * debug_new_counter_t::progname = __argv[0];
debug_new_counter_t::debug_new_counter_t()
{
++count;
}
debug_new_counter_t::~debug_new_counter_t()
{
if (--count == 0) {
check_mem_leak(progname);
}
}
void debug_new_counter_t::set_program_name(const char * pgn)
{
progname = pgn;
}
#endif // MEMORY_DEBUG
<|endoftext|> |
<commit_before>#include <atma/string.hpp>
#include <atma/intrusive_ptr.hpp>
#include <atma/math/vector4f.hpp>
#include <atma/algorithm.hpp>
#include <atma/enable_if.hpp>
#include <atma/math/intersection.hpp>
#include <filesystem>
namespace shelf
{
enum class path_type_t
{
dir,
file,
symlink
};
struct path_t;
using path_ptr = std::unique_ptr<path_t>; // atma::intrusive_ptr<path_t>;
// path
struct path_t
{
path_t();
path_t(atma::string const&);
path_t(path_t const&);
auto to_string() const -> atma::string;
auto is_file() const -> bool;
private:
path_t(atma::string const&, atma::string::const_iterator const&);
private:
atma::string name_;
path_type_t type_;
path_ptr child_;
};
path_t::path_t()
{
}
path_t::path_t(atma::string const& str)
: path_t(str, str.begin())
{
}
path_t::path_t(atma::string const& str, atma::string::const_iterator const& begin)
{
char const* delims = "/\\";
auto end = atma::find_first_of(str, begin, delims);
if (end == str.end()) {
type_ = path_type_t::file;
}
else {
type_ = path_type_t::dir;
++end;
}
name_ = atma::string(begin, end);
if (end == begin)
return;
child_ = path_ptr(new path_t(str, end));
}
path_t::path_t(path_t const& rhs)
: name_(rhs.name_), type_(rhs.type_)
{
if (rhs.child_)
child_ = path_ptr(new path_t(*rhs.child_));
}
auto path_t::to_string() const -> atma::string
{
auto result = atma::string();
for (auto t = this; t != nullptr; t = t->child_.get())
{
result += t->name_;
}
return result;
}
inline auto operator == (path_t const& lhs, path_t const& rhs) -> bool
{
return lhs.to_string() == rhs.to_string();
}
inline auto operator != (path_t const& lhs, path_t const& rhs) -> bool
{
return !operator == (lhs, rhs);
}
struct filesystem_t
{
auto add_mount(path_t const& virtual_path, path_t const& host_path) -> void;
private:
struct node_t;
using node_ptr = atma::intrusive_ptr<node_t>;
using nodes_t = std::vector<node_ptr>;
struct mount_t;
struct node_t : atma::ref_counted
{
atma::string name;
path_type_t type;
node_t* parent;
nodes_t children;
};
struct mount_t
{
path_t host_path;
path_t mount_path;
node_ptr mount_node;
};
private:
auto merge_paths(node_t*, node_t*) -> node_ptr;
private:
typedef std::vector<mount_t> mounts_t;
mounts_t mounts_;
};
auto filesystem_t::add_mount(path_t const& mount_path, path_t const& host_path) -> void
{
#ifdef _DEBUG
atma::for_each(mounts_, [&](mount_t const& x) { ATMA_ASSERT(x.host_path != host_path); });
#endif
// do a thing?
// host_path = "relative/path/";
// host_path2 = "/absolute/path";
// host_path3 = "/absolute/different/path";
mounts_.push_back({
host_path,
mount_path,
// something??
});
}
}
namespace math = atma::math;
#include <array>
template <typename T>
struct default_octree_subdivider_t
{
auto subdivide(uint depth, atma::math::vector4f const& bounds, T const& x) -> void
{
}
};
struct octree_t
{
octree_t() {}
//auto add_triangle(T const&, math::vector4f const&, math::vector4f const&, math::vector4f const&) -> void;
auto insert_point(math::vector4f const&) -> bool;
struct node_t;
//node_t root_;
private:
private:
private:
};
#if 0
struct box_t
{
math::vector4f origin;
math::vector4f half_extents;
static auto from_minmax(math::vector4f const& min, math::vector4f const& max) -> box_t
{
return box_t{(min + max) / 2.f, (max - min) / 2.f};
}
};
auto intersect_aabb_box(math::vector4f const& aabb, box_t const& box) -> bool
{
return !(
aabb.x + aabb.w < box.origin.x - box.half_extents.x ||
aabb.x - aabb.w > box.origin.x + box.half_extents.x ||
aabb.y + aabb.w < box.origin.y - box.half_extents.y ||
aabb.y - aabb.w > box.origin.y + box.half_extents.y ||
aabb.z + aabb.w < box.origin.z - box.half_extents.z ||
aabb.z - aabb.w > box.origin.z + box.half_extents.z)
;
}
#endif
#if 0
struct octree_t::node_t
{
node_t()
: bounds(0.f, 0.f, 0.f, 0.5f)
, children_()
, datas_()
{
}
node_t(math::vector4f const& bounds)
: bounds(bounds)
, children_()
, datas_()
{
}
atma::math::vector4f bounds;
triangle_t data;
auto inbounds(math::vector4f const& point) -> bool;
auto insert(math::vector4f const& point, T const& data) -> bool;
private:
auto imem_allocate() -> void
{
children_ = (node_t*)new char[8 * sizeof(node_t)];
}
auto imem_deallocate() -> void;
auto oct_split() -> void
{
children_ = (node_t*)new char[8 * sizeof(node_t)];
for (auto i = 0u; i != 8u; ++i)
new (children_ + i) node_t( oct_subbound(bounds, i) );
for (auto i = 0u; i != 8u; ++i)
insert(dloc_[i], data_[i]);
}
auto oct_subbound(math::vector4f const&, uint) -> math::vector4f;
private:
node_t* children_;
std::array<T, 8> data_;
std::array<math::vector4f, 8> dloc_;
uint datas_;
};
auto octree_t::node_t::insert(triangle_t const& tri) -> bool
{
if (!inbounds(point))
{
return false;
}
// we are a full leaf node
if (!children_ && datas_ == 8)
{
oct_split();
}
if (children_)
{
return std::any_of(children_, children_ + 8, [&point, &data](node_t& node) {
return node.insert(point, data);
});
}
data_[datas_] = data;
dloc_[datas_] = point;
++datas_;
return true;
}
auto octree_t::node_t::inbounds(math::vector4f const& point) -> bool
{
return
point.x < bounds.x + bounds.w && point.x > bounds.x - bounds.w &&
point.y < bounds.y + bounds.w && point.y > bounds.y - bounds.w &&
point.z < bounds.z + bounds.w && point.z > bounds.z - bounds.w
;
}
auto octree_t::node_t::oct_subbound(math::vector4f const& bounds, uint idx) -> math::vector4f
{
return math::vector4f(
(0.5f - ((idx & 1) ) * 1.f) * bounds.w + bounds.x,
(0.5f - ((idx & 2) >> 1) * 1.f) * bounds.w + bounds.y,
(0.5f - ((idx & 4) >> 2) * 1.f) * bounds.w + bounds.z,
bounds.w * 0.5f);
}
#endif
int main()
{
auto numbers = std::vector<int>{1, 2, 3, 4};
auto is_even = [](int x) { return x % 2 == 0; };
auto filtered = atma::filter(is_even, numbers);
auto numbers2 = std::vector<int>(filtered.begin(), filtered.end());
auto plus_1 = [](int x) { return x + 1; };
auto mapped = atma::map(plus_1, filtered);
auto numbers3 = std::vector<int>(mapped.begin(), mapped.end());
//auto b = atma::xtm::curry(&is_even);
//auto t = b(2);
//auto t2 = atma::xtm::bind(&is_even, arg1)(2);
#if 0
auto oct = octree_t<int>();
for (float i = 0.f; i < 8.f; ++i)
oct.root_.insert(math::point4f(0.2f + i * 0.001f, 0.3f * 0.001f, 0.4f * 0.001f), (int)i);
#endif
}
<commit_msg>testing out a new event_t<commit_after>#include <atma/string.hpp>
#include <atma/intrusive_ptr.hpp>
#include <atma/math/vector4f.hpp>
#include <atma/algorithm.hpp>
#include <atma/enable_if.hpp>
#include <atma/math/intersection.hpp>
#include <filesystem>
namespace shelf
{
enum class path_type_t
{
dir,
file,
symlink
};
struct path_t;
using path_ptr = std::unique_ptr<path_t>; // atma::intrusive_ptr<path_t>;
// path
struct path_t
{
path_t();
path_t(atma::string const&);
path_t(path_t const&);
auto to_string() const -> atma::string;
auto is_file() const -> bool;
private:
path_t(atma::string const&, atma::string::const_iterator const&);
private:
atma::string name_;
path_type_t type_;
path_ptr child_;
};
path_t::path_t()
{
}
path_t::path_t(atma::string const& str)
: path_t(str, str.begin())
{
}
path_t::path_t(atma::string const& str, atma::string::const_iterator const& begin)
{
char const* delims = "/\\";
auto end = atma::find_first_of(str, begin, delims);
if (end == str.end()) {
type_ = path_type_t::file;
}
else {
type_ = path_type_t::dir;
++end;
}
name_ = atma::string(begin, end);
if (end == begin)
return;
child_ = path_ptr(new path_t(str, end));
}
path_t::path_t(path_t const& rhs)
: name_(rhs.name_), type_(rhs.type_)
{
if (rhs.child_)
child_ = path_ptr(new path_t(*rhs.child_));
}
auto path_t::to_string() const -> atma::string
{
auto result = atma::string();
for (auto t = this; t != nullptr; t = t->child_.get())
{
result += t->name_;
}
return result;
}
inline auto operator == (path_t const& lhs, path_t const& rhs) -> bool
{
return lhs.to_string() == rhs.to_string();
}
inline auto operator != (path_t const& lhs, path_t const& rhs) -> bool
{
return !operator == (lhs, rhs);
}
struct filesystem_t
{
auto add_mount(path_t const& virtual_path, path_t const& host_path) -> void;
private:
struct node_t;
using node_ptr = atma::intrusive_ptr<node_t>;
using nodes_t = std::vector<node_ptr>;
struct mount_t;
struct node_t : atma::ref_counted
{
atma::string name;
path_type_t type;
node_t* parent;
nodes_t children;
};
struct mount_t
{
path_t host_path;
path_t mount_path;
node_ptr mount_node;
};
private:
auto merge_paths(node_t*, node_t*) -> node_ptr;
private:
typedef std::vector<mount_t> mounts_t;
mounts_t mounts_;
};
auto filesystem_t::add_mount(path_t const& mount_path, path_t const& host_path) -> void
{
#ifdef _DEBUG
atma::for_each(mounts_, [&](mount_t const& x) { ATMA_ASSERT(x.host_path != host_path); });
#endif
// do a thing?
// host_path = "relative/path/";
// host_path2 = "/absolute/path";
// host_path3 = "/absolute/different/path";
mounts_.push_back({
host_path,
mount_path,
// something??
});
}
}
namespace math = atma::math;
#include <array>
template <typename T>
struct default_octree_subdivider_t
{
auto subdivide(uint depth, atma::math::vector4f const& bounds, T const& x) -> void
{
}
};
struct octree_t
{
octree_t() {}
//auto add_triangle(T const&, math::vector4f const&, math::vector4f const&, math::vector4f const&) -> void;
auto insert_point(math::vector4f const&) -> bool;
struct node_t;
//node_t root_;
private:
private:
private:
};
#if 0
struct box_t
{
math::vector4f origin;
math::vector4f half_extents;
static auto from_minmax(math::vector4f const& min, math::vector4f const& max) -> box_t
{
return box_t{(min + max) / 2.f, (max - min) / 2.f};
}
};
auto intersect_aabb_box(math::vector4f const& aabb, box_t const& box) -> bool
{
return !(
aabb.x + aabb.w < box.origin.x - box.half_extents.x ||
aabb.x - aabb.w > box.origin.x + box.half_extents.x ||
aabb.y + aabb.w < box.origin.y - box.half_extents.y ||
aabb.y - aabb.w > box.origin.y + box.half_extents.y ||
aabb.z + aabb.w < box.origin.z - box.half_extents.z ||
aabb.z - aabb.w > box.origin.z + box.half_extents.z)
;
}
#endif
#if 0
struct octree_t::node_t
{
node_t()
: bounds(0.f, 0.f, 0.f, 0.5f)
, children_()
, datas_()
{
}
node_t(math::vector4f const& bounds)
: bounds(bounds)
, children_()
, datas_()
{
}
atma::math::vector4f bounds;
triangle_t data;
auto inbounds(math::vector4f const& point) -> bool;
auto insert(math::vector4f const& point, T const& data) -> bool;
private:
auto imem_allocate() -> void
{
children_ = (node_t*)new char[8 * sizeof(node_t)];
}
auto imem_deallocate() -> void;
auto oct_split() -> void
{
children_ = (node_t*)new char[8 * sizeof(node_t)];
for (auto i = 0u; i != 8u; ++i)
new (children_ + i) node_t( oct_subbound(bounds, i) );
for (auto i = 0u; i != 8u; ++i)
insert(dloc_[i], data_[i]);
}
auto oct_subbound(math::vector4f const&, uint) -> math::vector4f;
private:
node_t* children_;
std::array<T, 8> data_;
std::array<math::vector4f, 8> dloc_;
uint datas_;
};
auto octree_t::node_t::insert(triangle_t const& tri) -> bool
{
if (!inbounds(point))
{
return false;
}
// we are a full leaf node
if (!children_ && datas_ == 8)
{
oct_split();
}
if (children_)
{
return std::any_of(children_, children_ + 8, [&point, &data](node_t& node) {
return node.insert(point, data);
});
}
data_[datas_] = data;
dloc_[datas_] = point;
++datas_;
return true;
}
auto octree_t::node_t::inbounds(math::vector4f const& point) -> bool
{
return
point.x < bounds.x + bounds.w && point.x > bounds.x - bounds.w &&
point.y < bounds.y + bounds.w && point.y > bounds.y - bounds.w &&
point.z < bounds.z + bounds.w && point.z > bounds.z - bounds.w
;
}
auto octree_t::node_t::oct_subbound(math::vector4f const& bounds, uint idx) -> math::vector4f
{
return math::vector4f(
(0.5f - ((idx & 1) ) * 1.f) * bounds.w + bounds.x,
(0.5f - ((idx & 2) >> 1) * 1.f) * bounds.w + bounds.y,
(0.5f - ((idx & 4) >> 2) * 1.f) * bounds.w + bounds.z,
bounds.w * 0.5f);
}
#endif
struct bb_y
{
template <typename T>
auto firde(T t) -> void
{
dynamic_cast<base_thing_t<T>*>(this)->fire_impl(t);
}
virtual ~bb_y() {}
};
template <typename T>
struct base_thing_t : virtual bb_y
{
auto fire_impl(T t) -> void {}
};
enum class things_t { lol, hooray };
enum class animals_t { giraffe, dragon };
struct sizing_events_t
{
int resize;
int resize_dc;
int move;
};
enum class sizing_event_type_t
{
resize,
resize_dc,
move,
};
#include <atma/event.hpp>
#include <functional>
#include <list>
#include <set>
#include <mutex>
template <typename T>
struct null_combiner_t
{
null_combiner_t()
: result_()
{}
using result_type = T;
auto reset() -> void { result_ = T(); }
auto push(T const& x) -> void { result_ += x; }
auto result() -> T { return result_; }
private:
T result_;
};
template <>
struct null_combiner_t<void>
{
null_combiner_t()
{}
using result_type = void;
auto reset() -> void {}
auto push(void) -> void { }
auto result() const -> void { return; }
};
template <typename T>
struct count_combiner_t
{
count_combiner_t()
: calls_()
{}
using result_type = uint;
auto reset() -> void { calls_ = 0u; }
template <typename Y> auto push(Y const&) -> void { ++calls_; }
auto push(void) -> void { ++calls_; }
auto result() -> uint { return calls_; }
private:
uint calls_;
};
namespace detail
{
template <typename FN>
using delegate_t = std::function<FN>;
template <typename FN>
using delegates_t = std::list<delegate_t<FN>>;
template <typename R, template <typename> class CMB, typename FN, typename... Args>
struct fire_impl_t
{
static auto go(CMB<R>& cmb, delegates_t<FN> const& delegates, Args&&... args) -> typename CMB<R>::result_type
{
cmb.reset();
for (auto const& x : delegates)
cmb.push(x(std::forward<Args>(args)...));
return cmb.result();
}
};
template <template <typename> class CMB, typename FN, typename... Args>
struct fire_impl_t<void, CMB, FN, Args...>
{
static auto go(CMB<void>& cmb, delegates_t<FN> const& delegates, Args&&... args) -> typename CMB<void>::result_type
{
cmb.reset();
for (auto const& x : delegates) {
x(std::forward<Args>(args)...);
cmb.push();
}
return cmb.result();
}
};
}
template <bool Use> struct maybe_mutex_t;
template <bool Use> struct maybe_scoped_lock_t;
template <>
struct maybe_mutex_t<true>
{
maybe_mutex_t() {}
maybe_mutex_t(maybe_mutex_t const&) = delete;
private:
std::mutex mutex;
friend struct maybe_scoped_lock_t<true>;
};
template <>
struct maybe_mutex_t<false>
{
maybe_mutex_t(maybe_mutex_t const&) = delete;
};
template <>
struct maybe_scoped_lock_t<true>
{
maybe_scoped_lock_t(maybe_mutex_t<true>& mtx)
: guard_(mtx.mutex)
{}
private:
std::lock_guard<std::mutex> guard_;
};
template <>
struct maybe_scoped_lock_t<false>
{
maybe_scoped_lock_t(maybe_mutex_t<false> const& mtx)
{}
};
template <typename FN, template <typename> class CMB = count_combiner_t, bool ThreadSafe = true>
struct event_t
{
using fnptr_type = std::decay_t<FN>;
using fn_result_type = typename atma::xtm::function_traits<fnptr_type>::result_type;
using delegate_t = std::function<FN>;
using delegates_t = detail::delegates_t<FN>;
using delegate_handle_t = typename delegates_t::const_iterator;
using combiner_t = CMB<fn_result_type>;
using result_type = typename combiner_t::result_type;
event_t()
{}
event_t(combiner_t const& cmb)
: combiner_{cmb}
{}
event_t(event_t const& rhs)
: combiner_{rhs.combiner_}, mutex_{}, delegates_(rhs.delegates_)
{}
template <typename... Args>
auto fire(Args&&... args) -> result_type
{
auto SL = maybe_scoped_lock_t<ThreadSafe>{mutex_};
return detail::fire_impl_t<fn_result_type, CMB, FN, Args...>::go(combiner_, delegates_, std::forward<Args>(args)...);
}
auto operator += (delegate_t const& fn) -> delegate_handle_t
{
auto SL = maybe_scoped_lock_t<ThreadSafe>{mutex_};
delegates_.push_back(fn);
return --delegates_.end();
}
auto operator -= (delegate_handle_t const& fn) -> void
{
auto SL = maybe_scoped_lock_t<ThreadSafe>{mutex_};
delegates_.erase(fn);
}
private:
private:
combiner_t combiner_;
delegates_t delegates_;
maybe_mutex_t<ThreadSafe> mutex_;
};
template <typename Range, typename C, typename M, typename T>
struct propper_t;
template <typename Range, typename C, typename M, typename... Args>
struct propper_t<Range, C, M, std::tuple<Args...>>
{
static auto go(Range&& range, M C::*member, Args... args) -> typename M::result_type
{
for (auto&& x : range)
(x.*member).fire(std::forward<Args>(args)...);
return typename M::result_type();
}
};
template <typename Range, typename C, typename M>
auto broadcast_across(Range&& range, M C::*member)
-> typename M::delegate_t
{
using params = typename atma::xtm::function_traits<typename M::fnptr_type>::tupled_params_type;
return atma::xtm::curry(&propper_t<Range, C, M, params>::go, std::ref(range), member);
}
struct dragon_t
{
dragon_t() {}
event_t<int(int)> on_breathe_fire;
std::vector<dragon_t> children_;
};
int main()
{
event_t<int(int, int), null_combiner_t> e;
e += [](int x, int y) -> int { return x + y; };
e += [](int x, int y) -> int { return x * y; };
auto r = e.fire(4, 5);
event_t<void(int, int)> e2;
int z = 0;
e += [&](int x, int y) { return z = x + y; };
{
auto d = dragon_t{};
d.children_.push_back(dragon_t());
d.children_.back().on_breathe_fire += [](int g) -> int { std::cout << g << std::endl; return 0; };
d.children_.back().on_breathe_fire += [](int g) -> int { std::cout << "lulz" << std::endl; return 0; };
d.children_.back().on_breathe_fire += [](int g) -> int { std::cout << "zomg" << std::endl; return 0; };
d.children_.back().on_breathe_fire += [](int g) -> int { std::cout << "stop setting things on fire" << std::endl; return 0; };
d.children_.back().on_breathe_fire.fire(88);
d.on_breathe_fire += broadcast_across(d.children_, &dragon_t::on_breathe_fire);
d.on_breathe_fire.fire(8);
}
auto numbers = std::vector<int>{1, 2, 3, 4};
auto is_even = [](int x) { return x % 2 == 0; };
auto filtered = atma::filter(is_even, numbers);
auto numbers2 = std::vector<int>(filtered.begin(), filtered.end());
auto plus_1 = [](int x) { return x + 1; };
auto mapped = atma::map(plus_1, filtered);
auto numbers3 = std::vector<int>(mapped.begin(), mapped.end());
//auto b = atma::xtm::curry(&is_even);
//auto t = b(2);
//auto t2 = atma::xtm::bind(&is_even, arg1)(2);
#if 0
auto oct = octree_t<int>();
for (float i = 0.f; i < 8.f; ++i)
oct.root_.insert(math::point4f(0.2f + i * 0.001f, 0.3f * 0.001f, 0.4f * 0.001f), (int)i);
#endif
}
<|endoftext|> |
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License
Copyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld
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 "flusspferd/system.hpp"
#include "flusspferd/object.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/version.hpp"
#include "flusspferd/io/stream.hpp"
#include <iostream>
#include <ostream>
#if defined(__APPLE__)
# include <crt_externs.h>
# define environ (*_NSGetEnviron())
#elif defined(XP_WIN)
extern char** _environ;
# define environ _environ
#else
extern char** environ;
# endif
using namespace flusspferd;
// The class for sys.env
FLUSSPFERD_CLASS_DESCRIPTION(
environment,
(constructor_name, "Environment")
(full_name, "system.Environment")
(custom_enumerate, true)
(methods,
("toString", bind, to_string)
)
)
{
public:
environment(object const &obj, call_context &);
string to_string();
protected:
boost::any enumerate_start(int &n);
value enumerate_next(boost::any &iter);
bool property_resolve(value const &id, unsigned access);
};
void flusspferd::load_system_module(object &context) {
object exports = context.get_property_object("exports");
context.call("require", "io");
exports.define_property(
"stdout",
create_native_object<io::stream>(object(), std::cout.rdbuf()),
read_only_property | permanent_property);
exports.define_property(
"stderr",
create_native_object<io::stream>(object(), std::cerr.rdbuf()),
read_only_property | permanent_property);
exports.define_property(
"stdin",
create_native_object<io::stream>(object(), std::cin.rdbuf()),
read_only_property | permanent_property);
load_class<environment>(create_object());
call_context x;
exports.define_property(
"env",
create_native_object<environment>(object(), boost::ref(x)),
read_only_property | permanent_property
);
exports.define_property(
"args",
create_array(),
read_only_property | permanent_property);
exports.define_property(
"platform",
value("flusspferd"),
read_only_property | permanent_property);
exports.define_property(
"xFlusspferdVersion",
value(flusspferd::version()),
read_only_property | permanent_property);
}
environment::environment(object const &obj, call_context &)
: base_type(obj)
{
}
bool environment::property_resolve(value const &id, unsigned)
{
string name = id.to_string();
if (name == "__iterator__")
return false;
char *val = getenv(name.c_str());
if (!val)
return false;
define_property(name, string(val));
return true;
}
boost::any environment::enumerate_start(int &n) {
n = 0; // We dont know how many
return boost::any(environ);
}
value environment::enumerate_next(boost::any &iter) {
char **env = boost::any_cast<char**>(iter);
if (*env == 0)
return value();
char* eq_c = strchr(*env, '=');
string s = string(*env, eq_c - *env);
iter = ++env;
return s;
}
string environment::to_string() {
return "[object sys.Environment]";
}
<commit_msg>core/system: add some properties depending on RELOCATABLE<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License
Copyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld
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 "flusspferd/system.hpp"
#include "flusspferd/object.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/version.hpp"
#include "flusspferd/io/stream.hpp"
#include <iostream>
#include <ostream>
#if defined(__APPLE__)
# include <crt_externs.h>
# define environ (*_NSGetEnviron())
#elif defined(XP_WIN)
extern char** _environ;
# define environ _environ
#else
extern char** environ;
# endif
using namespace flusspferd;
// The class for sys.env
FLUSSPFERD_CLASS_DESCRIPTION(
environment,
(constructor_name, "Environment")
(full_name, "system.Environment")
(custom_enumerate, true)
(methods,
("toString", bind, to_string)
)
)
{
public:
environment(object const &obj, call_context &);
string to_string();
protected:
boost::any enumerate_start(int &n);
value enumerate_next(boost::any &iter);
bool property_resolve(value const &id, unsigned access);
};
void flusspferd::load_system_module(object &context) {
object exports = context.get_property_object("exports");
context.call("require", "io");
exports.define_property(
"stdout",
create_native_object<io::stream>(object(), std::cout.rdbuf()),
read_only_property | permanent_property);
exports.define_property(
"stderr",
create_native_object<io::stream>(object(), std::cerr.rdbuf()),
read_only_property | permanent_property);
exports.define_property(
"stdin",
create_native_object<io::stream>(object(), std::cin.rdbuf()),
read_only_property | permanent_property);
load_class<environment>(create_object());
call_context x;
exports.define_property(
"env",
create_native_object<environment>(object(), boost::ref(x)),
read_only_property | permanent_property
);
exports.define_property(
"args",
create_array(),
read_only_property | permanent_property);
exports.define_property(
"platform",
value("flusspferd"),
read_only_property | permanent_property);
exports.define_property(
"xFlusspferdVersion",
value(flusspferd::version()),
read_only_property | permanent_property);
#ifndef XX_FLUSSPFERD_RELOCATABLE
exports.define_property(
"xFlusspferdRelocatable",
value(false),
read_only_property | permanent_property);
exports.define_property(
"xFlusspferdPrefix",
value(INSTALL_PREFIX),
read_only_property | permanent_property);
#else
exports.define_property(
"xFlusspferdRelocatable",
value(true),
read_only_property | permanent_property);
#endif
}
environment::environment(object const &obj, call_context &)
: base_type(obj)
{
}
bool environment::property_resolve(value const &id, unsigned)
{
string name = id.to_string();
if (name == "__iterator__")
return false;
char *val = getenv(name.c_str());
if (!val)
return false;
define_property(name, string(val));
return true;
}
boost::any environment::enumerate_start(int &n) {
n = 0; // We dont know how many
return boost::any(environ);
}
value environment::enumerate_next(boost::any &iter) {
char **env = boost::any_cast<char**>(iter);
if (*env == 0)
return value();
char* eq_c = strchr(*env, '=');
string s = string(*env, eq_c - *env);
iter = ++env;
return s;
}
string environment::to_string() {
return "[object sys.Environment]";
}
<|endoftext|> |
<commit_before>#include "tests-base.hpp"
extern "C" {
#include "../internal/database.h"
#include "../internal/streaming.h"
}
#include "helpers-normalization.hpp"
#include "helpers-strings.hpp"
TEST(Streaming, Initialized)
{
const char* i = "loneliness";
size_t il = strlen(i);
StreamState state;
stream_initialize(&state, &i, &il, UnicodeProperty_Normalization_Compose);
EXPECT_EQ(i, *state.src);
EXPECT_EQ(&il, state.src_size);
EXPECT_EQ(UnicodeProperty_Normalization_Compose, state.property);
EXPECT_EQ(0, state.current);
EXPECT_EQ(1, state.stable);
EXPECT_EQ(ReorderResult_Next, state.stage);
}
TEST(Streaming, TwoFlushes)
{
unicode_t input[] = { 0x0061, 0x0315, 0x0300, 0x05AE, 0x0300, 0x0062 };
std::string converted = helpers::utf8(input, sizeof(input));
const char* i = converted.c_str();
size_t il = converted.length();
StreamState state;
stream_initialize(&state, &i, &il, UnicodeProperty_Normalization_Compose);
stream_execute(&state);
EXPECT_EQ(5, state.current);
EXPECT_UTF8EQ("a\\u5AE\\u300\\u300\\u315", helpers::identifiable(state.codepoint, state.current * sizeof(unicode_t)).c_str());
stream_execute(&state);
EXPECT_EQ(1, state.current);
EXPECT_UTF8EQ("b", helpers::identifiable(state.codepoint, state.current * sizeof(unicode_t)).c_str());
}<commit_msg>suite-streaming: Added tests for single and multiple reorderings.<commit_after>#include "tests-base.hpp"
extern "C" {
#include "../internal/database.h"
#include "../internal/streaming.h"
}
#include "helpers-normalization.hpp"
#include "helpers-strings.hpp"
TEST(Streaming, Initialized)
{
const char* i = "loneliness";
size_t il = strlen(i);
StreamState state;
stream_initialize(&state, &i, &il, UnicodeProperty_Normalization_Compose);
EXPECT_EQ(i, *state.src);
EXPECT_EQ(&il, state.src_size);
EXPECT_EQ(UnicodeProperty_Normalization_Compose, state.property);
EXPECT_EQ(0, state.current);
EXPECT_EQ(1, state.stable);
EXPECT_EQ(ReorderResult_Next, state.stage);
}
TEST(Streaming, SingleNoChange)
{
const char* i = "A\xCC\x83";
size_t il = strlen(i);
StreamState state;
stream_initialize(&state, &i, &il, UnicodeProperty_Normalization_Compose);
stream_execute(&state);
EXPECT_EQ(2, state.current);
EXPECT_UTF8EQ("A\xCC\x83", helpers::utf8(state.codepoint, state.current * sizeof(unicode_t)).c_str());
}
TEST(Streaming, SingleReorder)
{
const char* i = "A\xCC\x83\xCC\x82";
size_t il = strlen(i);
StreamState state;
stream_initialize(&state, &i, &il, UnicodeProperty_Normalization_Compose);
stream_execute(&state);
EXPECT_EQ(3, state.current);
EXPECT_UTF8EQ("A\xCC\x83\xCC\x82", helpers::utf8(state.codepoint, state.current * sizeof(unicode_t)).c_str());
}
TEST(Streaming, SingleInvalidCodepoint)
{
const char* i = "\xF4";
size_t il = strlen(i);
StreamState state;
stream_initialize(&state, &i, &il, UnicodeProperty_Normalization_Compose);
stream_execute(&state);
EXPECT_EQ(1, state.current);
EXPECT_UTF8EQ("\xEF\xBF\xBD", helpers::utf8(state.codepoint, state.current * sizeof(unicode_t)).c_str());
}
TEST(Streaming, MultipleNoChange)
{
const char* i = "a\xCC\x80\xCC\x81" "E\xCC\x8C";
size_t il = strlen(i);
StreamState state;
stream_initialize(&state, &i, &il, UnicodeProperty_Normalization_Compose);
stream_execute(&state);
EXPECT_EQ(3, state.current);
EXPECT_UTF8EQ("a\xCC\x80\xCC\x81", helpers::utf8(state.codepoint, state.current * sizeof(unicode_t)).c_str());
stream_execute(&state);
EXPECT_EQ(2, state.current);
EXPECT_UTF8EQ("E\xCC\x8C", helpers::utf8(state.codepoint, state.current * sizeof(unicode_t)).c_str());
}
TEST(Streaming, MultipleReorder)
{
const char* i = "a\xCC\x95\xCC\x80\xD6\xAE\xCC\x80" "b";
size_t il = strlen(i);
StreamState state;
stream_initialize(&state, &i, &il, UnicodeProperty_Normalization_Compose);
stream_execute(&state);
EXPECT_EQ(5, state.current);
EXPECT_UTF8EQ("a\xD6\xAE\xCC\x80\xCC\x80\xCC\x95", helpers::utf8(state.codepoint, state.current * sizeof(unicode_t)).c_str());
stream_execute(&state);
EXPECT_EQ(1, state.current);
EXPECT_UTF8EQ("b", helpers::utf8(state.codepoint, state.current * sizeof(unicode_t)).c_str());
}
TEST(Streaming, MultipleInvalidCodepoint)
{
const char* i = "\xF4\xDE\xF2";
size_t il = strlen(i);
StreamState state;
stream_initialize(&state, &i, &il, UnicodeProperty_Normalization_Compose);
stream_execute(&state);
EXPECT_EQ(1, state.current);
EXPECT_UTF8EQ("\xEF\xBF\xBD", helpers::utf8(state.codepoint, state.current * sizeof(unicode_t)).c_str());
stream_execute(&state);
EXPECT_EQ(1, state.current);
EXPECT_UTF8EQ("\xEF\xBF\xBD", helpers::utf8(state.codepoint, state.current * sizeof(unicode_t)).c_str());
}<|endoftext|> |
<commit_before>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "ModuleSlice.h"
#include "DataSource.h"
#include "Utilities.h"
#include <vtkAlgorithm.h>
#include <vtkCommand.h>
#include <vtkDataObject.h>
#include <vtkImageData.h>
#include <vtkNew.h>
#include <vtkNonOrthoImagePlaneWidget.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkScalarsToColors.h>
#include <pqCoreUtilities.h>
#include <pqDoubleVectorPropertyWidget.h>
#include <pqLineEdit.h>
#include <pqProxiesWidget.h>
#include <vtkPVArrayInformation.h>
#include <vtkPVDataInformation.h>
#include <vtkPVDataSetAttributesInformation.h>
#include <vtkSMPVRepresentationProxy.h>
#include <vtkSMParaViewPipelineControllerWithRendering.h>
#include <vtkSMPropertyHelper.h>
#include <vtkSMRenderViewProxy.h>
#include <vtkSMSessionProxyManager.h>
#include <vtkSMSourceProxy.h>
#include <vtkSMTransferFunctionManager.h>
#include <vtkSMTransferFunctionProxy.h>
#include <vtkSMViewProxy.h>
#include <QCheckBox>
#include <QDebug>
#include <QDoubleValidator>
#include <QHBoxLayout>
#include <QLabel>
#include <QVBoxLayout>
namespace tomviz {
ModuleSlice::ModuleSlice(QObject* parentObject) : Module(parentObject)
{
}
ModuleSlice::~ModuleSlice()
{
finalize();
}
QIcon ModuleSlice::icon() const
{
return QIcon(":/icons/pqSlice.png");
}
bool ModuleSlice::initialize(DataSource* data, vtkSMViewProxy* vtkView)
{
if (!Module::initialize(data, vtkView)) {
return false;
}
vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;
auto producer = data->proxy();
auto pxm = producer->GetSessionProxyManager();
// Create the pass through filter.
vtkSmartPointer<vtkSMProxy> proxy;
proxy.TakeReference(pxm->NewProxy("filters", "PassThrough"));
// Create the Properties panel proxy
m_propsPanelProxy.TakeReference(
pxm->NewProxy("tomviz_proxies", "NonOrthogonalSlice"));
pqCoreUtilities::connect(m_propsPanelProxy, vtkCommand::PropertyModifiedEvent,
this, SLOT(onPropertyChanged()));
m_passThrough = vtkSMSourceProxy::SafeDownCast(proxy);
Q_ASSERT(m_passThrough);
controller->PreInitializeProxy(m_passThrough);
vtkSMPropertyHelper(m_passThrough, "Input").Set(producer);
controller->PostInitializeProxy(m_passThrough);
controller->RegisterPipelineProxy(m_passThrough);
// Give the proxy a friendly name for the GUI/Python world.
if (auto p = convert<pqProxy*>(proxy)) {
p->rename(label());
}
const bool widgetSetup = setupWidget(vtkView, producer);
if (widgetSetup) {
m_widget->On();
m_widget->InteractionOn();
m_widget->SetDisplayOffset(data->displayPosition());
pqCoreUtilities::connect(m_widget, vtkCommand::InteractionEvent, this,
SLOT(onPlaneChanged()));
connect(data, SIGNAL(dataChanged()), this, SLOT(dataUpdated()));
}
Q_ASSERT(m_widget);
return widgetSetup;
}
// Should only be called from initialize after the PassThrough has been setup
bool ModuleSlice::setupWidget(vtkSMViewProxy* vtkView,
vtkSMSourceProxy* producer)
{
vtkAlgorithm* passThroughAlg =
vtkAlgorithm::SafeDownCast(m_passThrough->GetClientSideObject());
vtkRenderWindowInteractor* rwi = vtkView->GetRenderWindow()->GetInteractor();
// Determine the name of the property we are coloring by
const char* propertyName = producer->GetDataInformation()
->GetPointDataInformation()
->GetArrayInformation(0)
->GetName();
if (!rwi || !passThroughAlg || !propertyName) {
return false;
}
m_widget = vtkSmartPointer<vtkNonOrthoImagePlaneWidget>::New();
// Set the interactor on the widget to be what the current
// render window is using.
m_widget->SetInteractor(rwi);
// Setup the color of the border of the widget.
{
double color[3] = { 1, 0, 0 };
m_widget->GetPlaneProperty()->SetColor(color);
}
// Turn texture interpolation to be linear.
m_widget->TextureInterpolateOn();
m_widget->SetResliceInterpolateToLinear();
// Construct the transfer function proxy for the widget.
vtkSMProxy* lut = colorMap();
// Set the widgets lookup table to be the one that the transfer function
// manager is using.
vtkScalarsToColors* stc =
vtkScalarsToColors::SafeDownCast(lut->GetClientSideObject());
m_widget->SetLookupTable(stc);
// Lastly we set up the input connection.
m_widget->SetInputConnection(passThroughAlg->GetOutputPort());
Q_ASSERT(rwi);
Q_ASSERT(passThroughAlg);
onPlaneChanged();
return true;
}
void ModuleSlice::updateColorMap()
{
Q_ASSERT(m_widget);
// Construct the transfer function proxy for the widget
vtkSMProxy* lut = colorMap();
// set the widgets lookup table to be the one that the transfer function
// manager is using
vtkScalarsToColors* stc =
vtkScalarsToColors::SafeDownCast(lut->GetClientSideObject());
m_widget->SetLookupTable(stc);
}
bool ModuleSlice::finalize()
{
vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;
controller->UnRegisterProxy(m_passThrough);
m_passThrough = nullptr;
if (m_widget != nullptr) {
m_widget->InteractionOff();
m_widget->Off();
}
return true;
}
bool ModuleSlice::setVisibility(bool val)
{
Q_ASSERT(m_widget);
m_widget->SetEnabled(val ? 1 : 0);
// update the state of the arrow as well since it cannot update when the
// widget is not enabled
if (val) {
vtkSMPropertyHelper showProperty(m_propsPanelProxy, "ShowArrow");
// Not this: it hides the plane as well as the arrow...
// Widget->SetEnabled(showProperty.GetAsInt());
m_widget->SetArrowVisibility(showProperty.GetAsInt());
m_widget->SetInteraction(showProperty.GetAsInt());
}
return true;
}
bool ModuleSlice::visibility() const
{
if (m_widget) {
return m_widget->GetEnabled() != 0;
} else {
return false;
}
}
void ModuleSlice::addToPanel(QWidget* panel)
{
if (panel->layout()) {
delete panel->layout();
}
QVBoxLayout* layout = new QVBoxLayout;
QCheckBox* showArrow = new QCheckBox("Show Arrow");
layout->addWidget(showArrow);
m_Links.addPropertyLink(showArrow, "checked", SIGNAL(toggled(bool)),
m_propsPanelProxy,
m_propsPanelProxy->GetProperty("ShowArrow"), 0);
connect(showArrow, &QCheckBox::toggled, this, &ModuleSlice::dataUpdated);
QLabel* label = new QLabel("Point on Plane");
layout->addWidget(label);
QHBoxLayout* row = new QHBoxLayout;
const char* labels[] = { "X:", "Y:", "Z:" };
for (int i = 0; i < 3; ++i) {
label = new QLabel(labels[i]);
row->addWidget(label);
pqLineEdit* inputBox = new pqLineEdit;
inputBox->setValidator(new QDoubleValidator(inputBox));
m_Links.addPropertyLink(
inputBox, "text2", SIGNAL(textChanged(const QString&)), m_propsPanelProxy,
m_propsPanelProxy->GetProperty("PointOnPlane"), i);
connect(inputBox, &pqLineEdit::textChangedAndEditingFinished, this,
&ModuleSlice::dataUpdated);
row->addWidget(inputBox);
}
layout->addItem(row);
label = new QLabel("Plane Normal");
layout->addWidget(label);
row = new QHBoxLayout;
for (int i = 0; i < 3; ++i) {
label = new QLabel(labels[i]);
row->addWidget(label);
pqLineEdit* inputBox = new pqLineEdit;
inputBox->setValidator(new QDoubleValidator(inputBox));
m_Links.addPropertyLink(
inputBox, "text2", SIGNAL(textChanged(const QString&)), m_propsPanelProxy,
m_propsPanelProxy->GetProperty("PlaneNormal"), i);
connect(inputBox, &pqLineEdit::textChangedAndEditingFinished, this,
&ModuleSlice::dataUpdated);
row->addWidget(inputBox);
}
layout->addItem(row);
QCheckBox* mapScalarsCheckBox = new QCheckBox("Color Map Data");
layout->addWidget(mapScalarsCheckBox);
m_Links.addPropertyLink(mapScalarsCheckBox, "checked", SIGNAL(toggled(bool)),
m_propsPanelProxy,
m_propsPanelProxy->GetProperty("MapScalars"), 0);
connect(mapScalarsCheckBox, SIGNAL(toggled(bool)), this, SLOT(dataUpdated()));
layout->addStretch();
panel->setLayout(layout);
}
void ModuleSlice::dataUpdated()
{
m_Links.accept();
m_widget->SetMapScalars(
vtkSMPropertyHelper(m_propsPanelProxy->GetProperty("MapScalars"), 1)
.GetAsInt());
m_widget->UpdatePlacement();
emit renderNeeded();
}
bool ModuleSlice::serialize(pugi::xml_node& ns) const
{
// Save the state of the arrow's visibility
vtkSMPropertyHelper showProperty(m_propsPanelProxy, "ShowArrow");
ns.append_attribute("show_arrow").set_value(showProperty.GetAsInt());
// Serialize the plane
double point[3];
pugi::xml_node plane = ns.append_child("Plane");
pugi::xml_node pointNode;
m_widget->GetOrigin(point);
// Origin of plane
pointNode = plane.append_child("Point");
pointNode.append_attribute("index").set_value(0);
pointNode.append_attribute("x").set_value(point[0]);
pointNode.append_attribute("y").set_value(point[1]);
pointNode.append_attribute("z").set_value(point[2]);
// Point 1 of plane
m_widget->GetPoint1(point);
pointNode = plane.append_child("Point");
pointNode.append_attribute("index").set_value(1);
pointNode.append_attribute("x").set_value(point[0]);
pointNode.append_attribute("y").set_value(point[1]);
pointNode.append_attribute("z").set_value(point[2]);
// Point 2 of plane
m_widget->GetPoint2(point);
pointNode = plane.append_child("Point");
pointNode.append_attribute("index").set_value(2);
pointNode.append_attribute("x").set_value(point[0]);
pointNode.append_attribute("y").set_value(point[1]);
pointNode.append_attribute("z").set_value(point[2]);
// Map colors
pugi::xml_node mapScalars = ns.append_child("MapScalars");
mapScalars.append_attribute("value").set_value(m_widget->GetMapScalars() ==
1);
// Let the superclass do its thing
return Module::serialize(ns);
}
bool ModuleSlice::deserialize(const pugi::xml_node& ns)
{
pugi::xml_node plane = ns.child("Plane");
if (!plane) {
// We are reading an older state file from before the change that added
// the ability to save these...
return Module::deserialize(ns);
}
// Deserialize the show arrow state
vtkSMPropertyHelper showProperty(m_propsPanelProxy, "ShowArrow");
showProperty.Set(ns.attribute("show_arrow").as_int());
// Deserialize the plane
double point[3];
for (pugi::xml_node pointNode = plane.child("Point"); pointNode;
pointNode = pointNode.next_sibling("Point")) {
point[0] = pointNode.attribute("x").as_double();
point[1] = pointNode.attribute("y").as_double();
point[2] = pointNode.attribute("z").as_double();
int index = pointNode.attribute("index").as_int();
if (index == 0) {
m_widget->SetOrigin(point);
} else if (index == 1) {
m_widget->SetPoint1(point);
} else if (index == 2) {
m_widget->SetPoint2(point);
} else {
qCritical("Unknown point index for slice plane point");
return false;
}
}
pugi::xml_node mapScalars = ns.child("MapScalars");
m_widget->SetMapScalars(mapScalars.attribute("value").as_bool() ? 1 : 0);
m_widget->UpdatePlacement();
onPlaneChanged();
// Let the superclass do its thing
return Module::deserialize(ns);
}
void ModuleSlice::onPropertyChanged()
{
// Avoid recursive clobbering of the plane position
if (m_ignoreSignals) {
return;
}
m_ignoreSignals = true;
vtkSMPropertyHelper showProperty(m_propsPanelProxy, "ShowArrow");
if (m_widget->GetEnabled()) {
// Not this: it hides the plane as well as the arrow...
// Widget->SetEnabled(showProperty.GetAsInt());
m_widget->SetArrowVisibility(showProperty.GetAsInt());
m_widget->SetInteraction(showProperty.GetAsInt());
}
vtkSMPropertyHelper pointProperty(m_propsPanelProxy, "PointOnPlane");
std::vector<double> centerPoint = pointProperty.GetDoubleArray();
m_widget->SetCenter(¢erPoint[0]);
vtkSMPropertyHelper normalProperty(m_propsPanelProxy, "PlaneNormal");
std::vector<double> normalVector = normalProperty.GetDoubleArray();
m_widget->SetNormal(&normalVector[0]);
m_widget->UpdatePlacement();
m_ignoreSignals = false;
}
void ModuleSlice::onPlaneChanged()
{
// Avoid recursive clobbering of the plane position
if (m_ignoreSignals) {
return;
}
m_ignoreSignals = true;
vtkSMPropertyHelper pointProperty(m_propsPanelProxy, "PointOnPlane");
double* centerPoint = m_widget->GetCenter();
pointProperty.Set(centerPoint, 3);
vtkSMPropertyHelper normalProperty(m_propsPanelProxy, "PlaneNormal");
double* normalVector = m_widget->GetNormal();
normalProperty.Set(normalVector, 3);
vtkSMPropertyHelper mapScalarsProperty(m_propsPanelProxy, "MapScalars");
int mapScalars = m_widget->GetMapScalars();
mapScalarsProperty.Set(mapScalars);
m_ignoreSignals = false;
}
void ModuleSlice::dataSourceMoved(double newX, double newY, double newZ)
{
double pos[3] = { newX, newY, newZ };
m_widget->SetDisplayOffset(pos);
}
vtkSmartPointer<vtkDataObject> ModuleSlice::getDataToExport()
{
return m_widget->GetResliceOutput();
}
bool ModuleSlice::isProxyPartOfModule(vtkSMProxy* proxy)
{
return (proxy == m_passThrough.Get()) || (proxy == m_propsPanelProxy.Get());
}
std::string ModuleSlice::getStringForProxy(vtkSMProxy* proxy)
{
if (proxy == m_passThrough.Get()) {
return "PassThrough";
} else if (proxy == m_propsPanelProxy.Get()) {
return "NonOrthoSlice";
} else {
qWarning(
"Unknown proxy passed to module non-ortho-slice in save animation");
return "";
}
}
vtkSMProxy* ModuleSlice::getProxyForString(const std::string& str)
{
if (str == "PassThrough") {
return m_passThrough.Get();
} else if (str == "NonOrthoSlice") {
return m_propsPanelProxy.Get();
} else {
return nullptr;
}
}
}
<commit_msg>Reorder initialization of slice widget<commit_after>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "ModuleSlice.h"
#include "DataSource.h"
#include "Utilities.h"
#include <vtkAlgorithm.h>
#include <vtkCommand.h>
#include <vtkDataObject.h>
#include <vtkImageData.h>
#include <vtkNew.h>
#include <vtkNonOrthoImagePlaneWidget.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkScalarsToColors.h>
#include <pqCoreUtilities.h>
#include <pqDoubleVectorPropertyWidget.h>
#include <pqLineEdit.h>
#include <pqProxiesWidget.h>
#include <vtkPVArrayInformation.h>
#include <vtkPVDataInformation.h>
#include <vtkPVDataSetAttributesInformation.h>
#include <vtkSMPVRepresentationProxy.h>
#include <vtkSMParaViewPipelineControllerWithRendering.h>
#include <vtkSMPropertyHelper.h>
#include <vtkSMRenderViewProxy.h>
#include <vtkSMSessionProxyManager.h>
#include <vtkSMSourceProxy.h>
#include <vtkSMTransferFunctionManager.h>
#include <vtkSMTransferFunctionProxy.h>
#include <vtkSMViewProxy.h>
#include <QCheckBox>
#include <QDebug>
#include <QDoubleValidator>
#include <QHBoxLayout>
#include <QLabel>
#include <QVBoxLayout>
namespace tomviz {
ModuleSlice::ModuleSlice(QObject* parentObject) : Module(parentObject)
{
}
ModuleSlice::~ModuleSlice()
{
finalize();
}
QIcon ModuleSlice::icon() const
{
return QIcon(":/icons/pqSlice.png");
}
bool ModuleSlice::initialize(DataSource* data, vtkSMViewProxy* vtkView)
{
if (!Module::initialize(data, vtkView)) {
return false;
}
vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;
auto producer = data->proxy();
auto pxm = producer->GetSessionProxyManager();
// Create the pass through filter.
vtkSmartPointer<vtkSMProxy> proxy;
proxy.TakeReference(pxm->NewProxy("filters", "PassThrough"));
// Create the Properties panel proxy
m_propsPanelProxy.TakeReference(
pxm->NewProxy("tomviz_proxies", "NonOrthogonalSlice"));
pqCoreUtilities::connect(m_propsPanelProxy, vtkCommand::PropertyModifiedEvent,
this, SLOT(onPropertyChanged()));
m_passThrough = vtkSMSourceProxy::SafeDownCast(proxy);
Q_ASSERT(m_passThrough);
controller->PreInitializeProxy(m_passThrough);
vtkSMPropertyHelper(m_passThrough, "Input").Set(producer);
controller->PostInitializeProxy(m_passThrough);
controller->RegisterPipelineProxy(m_passThrough);
// Give the proxy a friendly name for the GUI/Python world.
if (auto p = convert<pqProxy*>(proxy)) {
p->rename(label());
}
const bool widgetSetup = setupWidget(vtkView, producer);
if (widgetSetup) {
m_widget->SetDisplayOffset(data->displayPosition());
m_widget->On();
m_widget->InteractionOn();
pqCoreUtilities::connect(m_widget, vtkCommand::InteractionEvent, this,
SLOT(onPlaneChanged()));
connect(data, SIGNAL(dataChanged()), this, SLOT(dataUpdated()));
}
Q_ASSERT(m_widget);
return widgetSetup;
}
// Should only be called from initialize after the PassThrough has been setup
bool ModuleSlice::setupWidget(vtkSMViewProxy* vtkView,
vtkSMSourceProxy* producer)
{
vtkAlgorithm* passThroughAlg =
vtkAlgorithm::SafeDownCast(m_passThrough->GetClientSideObject());
vtkRenderWindowInteractor* rwi = vtkView->GetRenderWindow()->GetInteractor();
// Determine the name of the property we are coloring by
const char* propertyName = producer->GetDataInformation()
->GetPointDataInformation()
->GetArrayInformation(0)
->GetName();
if (!rwi || !passThroughAlg || !propertyName) {
return false;
}
m_widget = vtkSmartPointer<vtkNonOrthoImagePlaneWidget>::New();
// Set the interactor on the widget to be what the current
// render window is using.
m_widget->SetInteractor(rwi);
// Setup the color of the border of the widget.
{
double color[3] = { 1, 0, 0 };
m_widget->GetPlaneProperty()->SetColor(color);
}
// Turn texture interpolation to be linear.
m_widget->TextureInterpolateOn();
m_widget->SetResliceInterpolateToLinear();
// Construct the transfer function proxy for the widget.
vtkSMProxy* lut = colorMap();
// Set the widgets lookup table to be the one that the transfer function
// manager is using.
vtkScalarsToColors* stc =
vtkScalarsToColors::SafeDownCast(lut->GetClientSideObject());
m_widget->SetLookupTable(stc);
// Lastly we set up the input connection.
m_widget->SetInputConnection(passThroughAlg->GetOutputPort());
Q_ASSERT(rwi);
Q_ASSERT(passThroughAlg);
onPlaneChanged();
return true;
}
void ModuleSlice::updateColorMap()
{
Q_ASSERT(m_widget);
// Construct the transfer function proxy for the widget
vtkSMProxy* lut = colorMap();
// set the widgets lookup table to be the one that the transfer function
// manager is using
vtkScalarsToColors* stc =
vtkScalarsToColors::SafeDownCast(lut->GetClientSideObject());
m_widget->SetLookupTable(stc);
}
bool ModuleSlice::finalize()
{
vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;
controller->UnRegisterProxy(m_passThrough);
m_passThrough = nullptr;
if (m_widget != nullptr) {
m_widget->InteractionOff();
m_widget->Off();
}
return true;
}
bool ModuleSlice::setVisibility(bool val)
{
Q_ASSERT(m_widget);
m_widget->SetEnabled(val ? 1 : 0);
// update the state of the arrow as well since it cannot update when the
// widget is not enabled
if (val) {
vtkSMPropertyHelper showProperty(m_propsPanelProxy, "ShowArrow");
// Not this: it hides the plane as well as the arrow...
// Widget->SetEnabled(showProperty.GetAsInt());
m_widget->SetArrowVisibility(showProperty.GetAsInt());
m_widget->SetInteraction(showProperty.GetAsInt());
}
return true;
}
bool ModuleSlice::visibility() const
{
if (m_widget) {
return m_widget->GetEnabled() != 0;
} else {
return false;
}
}
void ModuleSlice::addToPanel(QWidget* panel)
{
if (panel->layout()) {
delete panel->layout();
}
QVBoxLayout* layout = new QVBoxLayout;
QCheckBox* showArrow = new QCheckBox("Show Arrow");
layout->addWidget(showArrow);
m_Links.addPropertyLink(showArrow, "checked", SIGNAL(toggled(bool)),
m_propsPanelProxy,
m_propsPanelProxy->GetProperty("ShowArrow"), 0);
connect(showArrow, &QCheckBox::toggled, this, &ModuleSlice::dataUpdated);
QLabel* label = new QLabel("Point on Plane");
layout->addWidget(label);
QHBoxLayout* row = new QHBoxLayout;
const char* labels[] = { "X:", "Y:", "Z:" };
for (int i = 0; i < 3; ++i) {
label = new QLabel(labels[i]);
row->addWidget(label);
pqLineEdit* inputBox = new pqLineEdit;
inputBox->setValidator(new QDoubleValidator(inputBox));
m_Links.addPropertyLink(
inputBox, "text2", SIGNAL(textChanged(const QString&)), m_propsPanelProxy,
m_propsPanelProxy->GetProperty("PointOnPlane"), i);
connect(inputBox, &pqLineEdit::textChangedAndEditingFinished, this,
&ModuleSlice::dataUpdated);
row->addWidget(inputBox);
}
layout->addItem(row);
label = new QLabel("Plane Normal");
layout->addWidget(label);
row = new QHBoxLayout;
for (int i = 0; i < 3; ++i) {
label = new QLabel(labels[i]);
row->addWidget(label);
pqLineEdit* inputBox = new pqLineEdit;
inputBox->setValidator(new QDoubleValidator(inputBox));
m_Links.addPropertyLink(
inputBox, "text2", SIGNAL(textChanged(const QString&)), m_propsPanelProxy,
m_propsPanelProxy->GetProperty("PlaneNormal"), i);
connect(inputBox, &pqLineEdit::textChangedAndEditingFinished, this,
&ModuleSlice::dataUpdated);
row->addWidget(inputBox);
}
layout->addItem(row);
QCheckBox* mapScalarsCheckBox = new QCheckBox("Color Map Data");
layout->addWidget(mapScalarsCheckBox);
m_Links.addPropertyLink(mapScalarsCheckBox, "checked", SIGNAL(toggled(bool)),
m_propsPanelProxy,
m_propsPanelProxy->GetProperty("MapScalars"), 0);
connect(mapScalarsCheckBox, SIGNAL(toggled(bool)), this, SLOT(dataUpdated()));
layout->addStretch();
panel->setLayout(layout);
}
void ModuleSlice::dataUpdated()
{
m_Links.accept();
m_widget->SetMapScalars(
vtkSMPropertyHelper(m_propsPanelProxy->GetProperty("MapScalars"), 1)
.GetAsInt());
m_widget->UpdatePlacement();
emit renderNeeded();
}
bool ModuleSlice::serialize(pugi::xml_node& ns) const
{
// Save the state of the arrow's visibility
vtkSMPropertyHelper showProperty(m_propsPanelProxy, "ShowArrow");
ns.append_attribute("show_arrow").set_value(showProperty.GetAsInt());
// Serialize the plane
double point[3];
pugi::xml_node plane = ns.append_child("Plane");
pugi::xml_node pointNode;
m_widget->GetOrigin(point);
// Origin of plane
pointNode = plane.append_child("Point");
pointNode.append_attribute("index").set_value(0);
pointNode.append_attribute("x").set_value(point[0]);
pointNode.append_attribute("y").set_value(point[1]);
pointNode.append_attribute("z").set_value(point[2]);
// Point 1 of plane
m_widget->GetPoint1(point);
pointNode = plane.append_child("Point");
pointNode.append_attribute("index").set_value(1);
pointNode.append_attribute("x").set_value(point[0]);
pointNode.append_attribute("y").set_value(point[1]);
pointNode.append_attribute("z").set_value(point[2]);
// Point 2 of plane
m_widget->GetPoint2(point);
pointNode = plane.append_child("Point");
pointNode.append_attribute("index").set_value(2);
pointNode.append_attribute("x").set_value(point[0]);
pointNode.append_attribute("y").set_value(point[1]);
pointNode.append_attribute("z").set_value(point[2]);
// Map colors
pugi::xml_node mapScalars = ns.append_child("MapScalars");
mapScalars.append_attribute("value").set_value(m_widget->GetMapScalars() ==
1);
// Let the superclass do its thing
return Module::serialize(ns);
}
bool ModuleSlice::deserialize(const pugi::xml_node& ns)
{
pugi::xml_node plane = ns.child("Plane");
if (!plane) {
// We are reading an older state file from before the change that added
// the ability to save these...
return Module::deserialize(ns);
}
// Deserialize the show arrow state
vtkSMPropertyHelper showProperty(m_propsPanelProxy, "ShowArrow");
showProperty.Set(ns.attribute("show_arrow").as_int());
// Deserialize the plane
double point[3];
for (pugi::xml_node pointNode = plane.child("Point"); pointNode;
pointNode = pointNode.next_sibling("Point")) {
point[0] = pointNode.attribute("x").as_double();
point[1] = pointNode.attribute("y").as_double();
point[2] = pointNode.attribute("z").as_double();
int index = pointNode.attribute("index").as_int();
if (index == 0) {
m_widget->SetOrigin(point);
} else if (index == 1) {
m_widget->SetPoint1(point);
} else if (index == 2) {
m_widget->SetPoint2(point);
} else {
qCritical("Unknown point index for slice plane point");
return false;
}
}
pugi::xml_node mapScalars = ns.child("MapScalars");
m_widget->SetMapScalars(mapScalars.attribute("value").as_bool() ? 1 : 0);
m_widget->UpdatePlacement();
onPlaneChanged();
// Let the superclass do its thing
return Module::deserialize(ns);
}
void ModuleSlice::onPropertyChanged()
{
// Avoid recursive clobbering of the plane position
if (m_ignoreSignals) {
return;
}
m_ignoreSignals = true;
vtkSMPropertyHelper showProperty(m_propsPanelProxy, "ShowArrow");
if (m_widget->GetEnabled()) {
// Not this: it hides the plane as well as the arrow...
// Widget->SetEnabled(showProperty.GetAsInt());
m_widget->SetArrowVisibility(showProperty.GetAsInt());
m_widget->SetInteraction(showProperty.GetAsInt());
}
vtkSMPropertyHelper pointProperty(m_propsPanelProxy, "PointOnPlane");
std::vector<double> centerPoint = pointProperty.GetDoubleArray();
m_widget->SetCenter(¢erPoint[0]);
vtkSMPropertyHelper normalProperty(m_propsPanelProxy, "PlaneNormal");
std::vector<double> normalVector = normalProperty.GetDoubleArray();
m_widget->SetNormal(&normalVector[0]);
m_widget->UpdatePlacement();
m_ignoreSignals = false;
}
void ModuleSlice::onPlaneChanged()
{
// Avoid recursive clobbering of the plane position
if (m_ignoreSignals) {
return;
}
m_ignoreSignals = true;
vtkSMPropertyHelper pointProperty(m_propsPanelProxy, "PointOnPlane");
double* centerPoint = m_widget->GetCenter();
pointProperty.Set(centerPoint, 3);
vtkSMPropertyHelper normalProperty(m_propsPanelProxy, "PlaneNormal");
double* normalVector = m_widget->GetNormal();
normalProperty.Set(normalVector, 3);
vtkSMPropertyHelper mapScalarsProperty(m_propsPanelProxy, "MapScalars");
int mapScalars = m_widget->GetMapScalars();
mapScalarsProperty.Set(mapScalars);
m_ignoreSignals = false;
}
void ModuleSlice::dataSourceMoved(double newX, double newY, double newZ)
{
double pos[3] = { newX, newY, newZ };
m_widget->SetDisplayOffset(pos);
}
vtkSmartPointer<vtkDataObject> ModuleSlice::getDataToExport()
{
return m_widget->GetResliceOutput();
}
bool ModuleSlice::isProxyPartOfModule(vtkSMProxy* proxy)
{
return (proxy == m_passThrough.Get()) || (proxy == m_propsPanelProxy.Get());
}
std::string ModuleSlice::getStringForProxy(vtkSMProxy* proxy)
{
if (proxy == m_passThrough.Get()) {
return "PassThrough";
} else if (proxy == m_propsPanelProxy.Get()) {
return "NonOrthoSlice";
} else {
qWarning(
"Unknown proxy passed to module non-ortho-slice in save animation");
return "";
}
}
vtkSMProxy* ModuleSlice::getProxyForString(const std::string& str)
{
if (str == "PassThrough") {
return m_passThrough.Get();
} else if (str == "NonOrthoSlice") {
return m_propsPanelProxy.Get();
} else {
return nullptr;
}
}
}
<|endoftext|> |
<commit_before>#include <fastrtps/log/Log.h>
#include <fastrtps/log/StdoutConsumer.h>
#include <iostream>
using namespace std;
namespace eprosima {
namespace fastrtps {
struct Log::Resources Log::mResources;
Log::Resources::Resources():
mDefaultConsumer(new StdoutConsumer),
mLogging(false),
mWork(false),
mFilenames(false),
mFunctions(true),
mVerbosity(Log::Error)
{
}
Log::Resources::~Resources()
{
Log::KillThread();
}
void Log::RegisterConsumer(std::unique_ptr<LogConsumer> consumer)
{
std::unique_lock<std::mutex> guard(mResources.mConfigMutex);
mResources.mConsumers.emplace_back(std::move(consumer));
}
void Log::Reset()
{
std::unique_lock<std::mutex> configGuard(mResources.mConfigMutex);
mResources.mCategoryFilter.reset();
mResources.mFilenameFilter.reset();
mResources.mErrorStringFilter.reset();
mResources.mFilenames = false;
mResources.mFunctions = true;
mResources.mVerbosity = Log::Error;
mResources.mConsumers.clear();
}
void Log::Run()
{
std::unique_lock<std::mutex> guard(mResources.mCvMutex);
while (mResources.mLogging)
{
while (mResources.mWork)
{
mResources.mWork = false;
guard.unlock();
mResources.mLogs.Swap();
while (!mResources.mLogs.Empty())
{
std::unique_lock<std::mutex> configGuard(mResources.mConfigMutex);
if (Preprocess(mResources.mLogs.Front()))
{
for (auto& consumer: mResources.mConsumers)
consumer->Consume(mResources.mLogs.Front());
mResources.mDefaultConsumer->Consume(mResources.mLogs.Front());
}
mResources.mLogs.Pop();
}
guard.lock();
}
if (mResources.mLogging)
mResources.mCv.wait(guard);
}
}
void Log::ReportFilenames(bool report)
{
std::unique_lock<std::mutex> configGuard(mResources.mConfigMutex);
mResources.mFilenames = report;
}
void Log::ReportFunctions(bool report)
{
std::unique_lock<std::mutex> configGuard(mResources.mConfigMutex);
mResources.mFunctions = report;
}
bool Log::Preprocess(Log::Entry& entry)
{
if (mResources.mCategoryFilter && !regex_search(entry.context.category, *mResources.mCategoryFilter))
return false;
if (mResources.mFilenameFilter && !regex_search(entry.context.filename, *mResources.mFilenameFilter))
return false;
if (mResources.mErrorStringFilter && !regex_search(entry.message, *mResources.mErrorStringFilter))
return false;
if (!mResources.mFilenames)
entry.context.filename = nullptr;
if (!mResources.mFunctions)
entry.context.function = nullptr;
return true;
}
void Log::KillThread()
{
{
std::unique_lock<std::mutex> guard(mResources.mCvMutex);
mResources.mLogging = false;
mResources.mWork = false;
}
if (mResources.mLoggingThread)
{
// The #ifdef workaround here is due to an unsolved MSVC bug, which Microsoft has announced
// they have no intention of solving: https://connect.microsoft.com/VisualStudio/feedback/details/747145
// Each VS version deals with post-main deallocation of threads in a very different way.
#if !defined(_WIN32) || defined(FASTRTPS_STATIC_LINK)
mResources.mCv.notify_all();
#if !(defined(_MSC_VER) && _MSC_VER == 1800)
mResources.mLoggingThread->join();
#endif
#endif
mResources.mLoggingThread.reset();
}
}
void Log::QueueLog(const std::string& message, const Log::Context& context, Log::Kind kind)
{
{
std::unique_lock<std::mutex> guard(mResources.mCvMutex);
if (!mResources.mLogging && !mResources.mLoggingThread)
{
mResources.mLogging = true;
mResources.mLoggingThread.reset(new thread(Log::Run));
}
}
mResources.mLogs.Push(Log::Entry{message, context, kind});
{
std::unique_lock<std::mutex> guard(mResources.mCvMutex);
mResources.mWork = true;
}
mResources.mCv.notify_all();
}
Log::Kind Log::GetVerbosity()
{
return mResources.mVerbosity;
}
void Log::SetVerbosity(Log::Kind kind)
{
std::unique_lock<std::mutex> configGuard(mResources.mConfigMutex);
mResources.mVerbosity = kind;
}
void Log::SetCategoryFilter(const std::regex& filter)
{
std::unique_lock<std::mutex> configGuard(mResources.mConfigMutex);
mResources.mCategoryFilter.reset(new std::regex(filter));
}
void Log::SetFilenameFilter(const std::regex& filter)
{
std::unique_lock<std::mutex> configGuard(mResources.mConfigMutex);
mResources.mFilenameFilter.reset(new std::regex(filter));
}
void Log::SetErrorStringFilter(const std::regex& filter)
{
std::unique_lock<std::mutex> configGuard(mResources.mConfigMutex);
mResources.mErrorStringFilter.reset(new std::regex(filter));
}
} //namespace fastrtps
} //namespace eprosima
<commit_msg>More VS workaroundS<commit_after>#include <fastrtps/log/Log.h>
#include <fastrtps/log/StdoutConsumer.h>
#include <iostream>
using namespace std;
namespace eprosima {
namespace fastrtps {
struct Log::Resources Log::mResources;
Log::Resources::Resources():
mDefaultConsumer(new StdoutConsumer),
mLogging(false),
mWork(false),
mFilenames(false),
mFunctions(true),
mVerbosity(Log::Error)
{
}
Log::Resources::~Resources()
{
Log::KillThread();
}
void Log::RegisterConsumer(std::unique_ptr<LogConsumer> consumer)
{
std::unique_lock<std::mutex> guard(mResources.mConfigMutex);
mResources.mConsumers.emplace_back(std::move(consumer));
}
void Log::Reset()
{
std::unique_lock<std::mutex> configGuard(mResources.mConfigMutex);
mResources.mCategoryFilter.reset();
mResources.mFilenameFilter.reset();
mResources.mErrorStringFilter.reset();
mResources.mFilenames = false;
mResources.mFunctions = true;
mResources.mVerbosity = Log::Error;
mResources.mConsumers.clear();
}
void Log::Run()
{
std::unique_lock<std::mutex> guard(mResources.mCvMutex);
while (mResources.mLogging)
{
while (mResources.mWork)
{
mResources.mWork = false;
guard.unlock();
mResources.mLogs.Swap();
while (!mResources.mLogs.Empty())
{
std::unique_lock<std::mutex> configGuard(mResources.mConfigMutex);
if (Preprocess(mResources.mLogs.Front()))
{
for (auto& consumer: mResources.mConsumers)
consumer->Consume(mResources.mLogs.Front());
mResources.mDefaultConsumer->Consume(mResources.mLogs.Front());
}
mResources.mLogs.Pop();
}
guard.lock();
}
if (mResources.mLogging)
mResources.mCv.wait(guard);
}
}
void Log::ReportFilenames(bool report)
{
std::unique_lock<std::mutex> configGuard(mResources.mConfigMutex);
mResources.mFilenames = report;
}
void Log::ReportFunctions(bool report)
{
std::unique_lock<std::mutex> configGuard(mResources.mConfigMutex);
mResources.mFunctions = report;
}
bool Log::Preprocess(Log::Entry& entry)
{
if (mResources.mCategoryFilter && !regex_search(entry.context.category, *mResources.mCategoryFilter))
return false;
if (mResources.mFilenameFilter && !regex_search(entry.context.filename, *mResources.mFilenameFilter))
return false;
if (mResources.mErrorStringFilter && !regex_search(entry.message, *mResources.mErrorStringFilter))
return false;
if (!mResources.mFilenames)
entry.context.filename = nullptr;
if (!mResources.mFunctions)
entry.context.function = nullptr;
return true;
}
void Log::KillThread()
{
{
std::unique_lock<std::mutex> guard(mResources.mCvMutex);
mResources.mLogging = false;
mResources.mWork = false;
}
if (mResources.mLoggingThread)
{
// The #ifdef workaround here is due to an unsolved MSVC bug, which Microsoft has announced
// they have no intention of solving: https://connect.microsoft.com/VisualStudio/feedback/details/747145
// Each VS version deals with post-main deallocation of threads in a very different way.
#if !defined(_WIN32) || defined(FASTRTPS_STATIC_LINK)
mResources.mCv.notify_all();
#if !(defined(_MSC_VER) && _MSC_VER == 1800)
mResources.mLoggingThread->join();
#else
std::this_thread::sleep_for(std::chrono::milliseconds(100));
#endif
#endif
mResources.mLoggingThread.reset();
}
}
void Log::QueueLog(const std::string& message, const Log::Context& context, Log::Kind kind)
{
{
std::unique_lock<std::mutex> guard(mResources.mCvMutex);
if (!mResources.mLogging && !mResources.mLoggingThread)
{
mResources.mLogging = true;
mResources.mLoggingThread.reset(new thread(Log::Run));
}
}
mResources.mLogs.Push(Log::Entry{message, context, kind});
{
std::unique_lock<std::mutex> guard(mResources.mCvMutex);
mResources.mWork = true;
}
mResources.mCv.notify_all();
}
Log::Kind Log::GetVerbosity()
{
return mResources.mVerbosity;
}
void Log::SetVerbosity(Log::Kind kind)
{
std::unique_lock<std::mutex> configGuard(mResources.mConfigMutex);
mResources.mVerbosity = kind;
}
void Log::SetCategoryFilter(const std::regex& filter)
{
std::unique_lock<std::mutex> configGuard(mResources.mConfigMutex);
mResources.mCategoryFilter.reset(new std::regex(filter));
}
void Log::SetFilenameFilter(const std::regex& filter)
{
std::unique_lock<std::mutex> configGuard(mResources.mConfigMutex);
mResources.mFilenameFilter.reset(new std::regex(filter));
}
void Log::SetErrorStringFilter(const std::regex& filter)
{
std::unique_lock<std::mutex> configGuard(mResources.mConfigMutex);
mResources.mErrorStringFilter.reset(new std::regex(filter));
}
} //namespace fastrtps
} //namespace eprosima
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2001-2005 The Regents of The University of Michigan
* 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 holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
* Lisa Hsu
* Nathan Binkert
* Steve Raasch
*/
#include <iomanip>
#include "arch/isa_traits.hh"
#include "arch/utility.hh"
#include "base/loader/symtab.hh"
#include "config/the_isa.hh"
#include "cpu/base.hh"
#include "cpu/exetrace.hh"
#include "cpu/static_inst.hh"
#include "cpu/thread_context.hh"
#include "debug/ExecAll.hh"
#include "enums/OpClass.hh"
using namespace std;
using namespace TheISA;
namespace Trace {
void
ExeTracerRecord::dumpTicks(ostream &outs)
{
ccprintf(outs, "%7d: ", when);
}
void
Trace::ExeTracerRecord::traceInst(StaticInstPtr inst, bool ran)
{
ostream &outs = Trace::output();
if (!Debug::ExecUser || !Debug::ExecKernel) {
bool in_user_mode = TheISA::inUserMode(thread);
if (in_user_mode && !Debug::ExecUser) return;
if (!in_user_mode && !Debug::ExecKernel) return;
}
if (Debug::ExecTicks)
dumpTicks(outs);
outs << thread->getCpuPtr()->name() << " ";
if (Debug::ExecSpeculative)
outs << (misspeculating ? "-" : "+") << " ";
if (Debug::ExecAsid)
outs << "A" << dec << TheISA::getExecutingAsid(thread) << " ";
if (Debug::ExecThread)
outs << "T" << thread->threadId() << " : ";
std::string sym_str;
Addr sym_addr;
Addr cur_pc = pc.instAddr();
if (debugSymbolTable && Debug::ExecSymbol && !inUserMode(thread)
&& debugSymbolTable->findNearestSymbol(cur_pc, sym_str, sym_addr)) {
if (cur_pc != sym_addr)
sym_str += csprintf("+%d",cur_pc - sym_addr);
outs << "@" << sym_str;
} else {
outs << "0x" << hex << cur_pc;
}
if (inst->isMicroop()) {
outs << "." << setw(2) << dec << pc.microPC();
} else {
outs << " ";
}
outs << " : ";
//
// Print decoded instruction
//
outs << setw(26) << left;
outs << inst->disassemble(cur_pc, debugSymbolTable);
if (ran) {
outs << " : ";
if (Debug::ExecOpClass) {
outs << Enums::OpClassStrings[inst->opClass()] << " : ";
}
if (Debug::ExecResult && predicate == false) {
outs << "Predicated False";
}
if (Debug::ExecResult && data_status != DataInvalid) {
ccprintf(outs, " D=%#018x", data.as_int);
}
if (Debug::ExecEffAddr && addr_valid)
outs << " A=0x" << hex << addr;
if (Debug::ExecFetchSeq && fetch_seq_valid)
outs << " FetchSeq=" << dec << fetch_seq;
if (Debug::ExecCPSeq && cp_seq_valid)
outs << " CPSeq=" << dec << cp_seq;
}
//
// End of line...
//
outs << endl;
}
void
Trace::ExeTracerRecord::dump()
{
/*
* The behavior this check tries to achieve is that if ExecMacro is on,
* the macroop will be printed. If it's on and microops are also on, it's
* printed before the microops start printing to give context. If the
* microops aren't printed, then it's printed only when the final microop
* finishes. Macroops then behave like regular instructions and don't
* complete/print when they fault.
*/
if (Debug::ExecMacro && staticInst->isMicroop() &&
((Debug::ExecMicro &&
macroStaticInst && staticInst->isFirstMicroop()) ||
(!Debug::ExecMicro &&
macroStaticInst && staticInst->isLastMicroop()))) {
traceInst(macroStaticInst, false);
}
if (Debug::ExecMicro || !staticInst->isMicroop()) {
traceInst(staticInst, true);
}
}
} // namespace Trace
////////////////////////////////////////////////////////////////////////
//
// ExeTracer Simulation Object
//
Trace::ExeTracer *
ExeTracerParams::create()
{
return new Trace::ExeTracer(this);
}
<commit_msg>debug : Fixes the issue wherein Debug symbols were not getting dumped into trace files for SE mode<commit_after>/*
* Copyright (c) 2001-2005 The Regents of The University of Michigan
* 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 holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
* Lisa Hsu
* Nathan Binkert
* Steve Raasch
*/
#include <iomanip>
#include "arch/isa_traits.hh"
#include "arch/utility.hh"
#include "base/loader/symtab.hh"
#include "config/the_isa.hh"
#include "cpu/base.hh"
#include "cpu/exetrace.hh"
#include "cpu/static_inst.hh"
#include "cpu/thread_context.hh"
#include "debug/ExecAll.hh"
#include "enums/OpClass.hh"
using namespace std;
using namespace TheISA;
namespace Trace {
void
ExeTracerRecord::dumpTicks(ostream &outs)
{
ccprintf(outs, "%7d: ", when);
}
void
Trace::ExeTracerRecord::traceInst(StaticInstPtr inst, bool ran)
{
ostream &outs = Trace::output();
if (!Debug::ExecUser || !Debug::ExecKernel) {
bool in_user_mode = TheISA::inUserMode(thread);
if (in_user_mode && !Debug::ExecUser) return;
if (!in_user_mode && !Debug::ExecKernel) return;
}
if (Debug::ExecTicks)
dumpTicks(outs);
outs << thread->getCpuPtr()->name() << " ";
if (Debug::ExecSpeculative)
outs << (misspeculating ? "-" : "+") << " ";
if (Debug::ExecAsid)
outs << "A" << dec << TheISA::getExecutingAsid(thread) << " ";
if (Debug::ExecThread)
outs << "T" << thread->threadId() << " : ";
std::string sym_str;
Addr sym_addr;
Addr cur_pc = pc.instAddr();
if (debugSymbolTable && Debug::ExecSymbol &&
(!FullSystem || !inUserMode(thread)) &&
debugSymbolTable->findNearestSymbol(cur_pc, sym_str, sym_addr)) {
if (cur_pc != sym_addr)
sym_str += csprintf("+%d",cur_pc - sym_addr);
outs << "@" << sym_str;
} else {
outs << "0x" << hex << cur_pc;
}
if (inst->isMicroop()) {
outs << "." << setw(2) << dec << pc.microPC();
} else {
outs << " ";
}
outs << " : ";
//
// Print decoded instruction
//
outs << setw(26) << left;
outs << inst->disassemble(cur_pc, debugSymbolTable);
if (ran) {
outs << " : ";
if (Debug::ExecOpClass) {
outs << Enums::OpClassStrings[inst->opClass()] << " : ";
}
if (Debug::ExecResult && predicate == false) {
outs << "Predicated False";
}
if (Debug::ExecResult && data_status != DataInvalid) {
ccprintf(outs, " D=%#018x", data.as_int);
}
if (Debug::ExecEffAddr && addr_valid)
outs << " A=0x" << hex << addr;
if (Debug::ExecFetchSeq && fetch_seq_valid)
outs << " FetchSeq=" << dec << fetch_seq;
if (Debug::ExecCPSeq && cp_seq_valid)
outs << " CPSeq=" << dec << cp_seq;
}
//
// End of line...
//
outs << endl;
}
void
Trace::ExeTracerRecord::dump()
{
/*
* The behavior this check tries to achieve is that if ExecMacro is on,
* the macroop will be printed. If it's on and microops are also on, it's
* printed before the microops start printing to give context. If the
* microops aren't printed, then it's printed only when the final microop
* finishes. Macroops then behave like regular instructions and don't
* complete/print when they fault.
*/
if (Debug::ExecMacro && staticInst->isMicroop() &&
((Debug::ExecMicro &&
macroStaticInst && staticInst->isFirstMicroop()) ||
(!Debug::ExecMicro &&
macroStaticInst && staticInst->isLastMicroop()))) {
traceInst(macroStaticInst, false);
}
if (Debug::ExecMicro || !staticInst->isMicroop()) {
traceInst(staticInst, true);
}
}
} // namespace Trace
////////////////////////////////////////////////////////////////////////
//
// ExeTracer Simulation Object
//
Trace::ExeTracer *
ExeTracerParams::create()
{
return new Trace::ExeTracer(this);
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Lukasz Janyst <ljanyst@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Interpreter/Interpreter.h"
#include "cling/MetaProcessor/MetaProcessor.h"
#include "cling/UserInterface/UserInterface.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/ManagedStatic.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
int main( int argc, char **argv ) {
llvm::llvm_shutdown_obj shutdownTrigger;
//llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
//llvm::PrettyStackTraceProgram X(argc, argv);
// Set up the interpreter
cling::Interpreter interp(argc, argv);
if (interp.getOptions().Help) {
return 0;
}
clang::CompilerInstance* CI = interp.getCI();
interp.AddIncludePath(".");
for (size_t I = 0, N = interp.getOptions().LibsToLoad.size(); I < N; ++I) {
interp.loadFile(interp.getOptions().LibsToLoad[I]);
}
// Interactive means no input (or one input that's "-")
std::vector<std::string>& Inputs = interp.getOptions().Inputs;
bool Interactive = Inputs.empty() || (Inputs.size() == 1
&& Inputs[0] == "-");
cling::UserInterface ui(interp);
// If we are not interactive we're supposed to parse files
if (!Interactive) {
for (size_t I = 0, N = Inputs.size(); I < N; ++I) {
std::string cmd;
cling::Interpreter::CompilationResult compRes;
if (!interp.lookupFileOrLibrary(Inputs[I]).empty()) {
std::ifstream infile(interp.lookupFileOrLibrary(Inputs[I]));
std::string line;
std::getline(infile, line);
if (line[0] == '#' && line[1] == '!') {
// TODO: Check whether the filename specified after #! is the current
// executable.
while(std::getline(infile, line)) {
ui.getMetaProcessor()->process(line.c_str(), compRes, 0);
}
continue;
}
else
cmd += ".x ";
}
cmd += Inputs[I];
ui.getMetaProcessor()->process(cmd.c_str(), compRes, 0);
}
}
else {
ui.runInteractively(interp.getOptions().NoLogo);
}
bool ret = CI->getDiagnostics().getClient()->getNumErrors();
// if we are running with -verify a reported has to be returned as unsuccess.
// This is relevant especially for the test suite.
if (CI->getDiagnosticOpts().VerifyDiagnostics) {
// If there was an error that came from the verifier we must return 1 as
// an exit code for the process. This will make the test fail as expected.
clang::DiagnosticConsumer* client = CI->getDiagnostics().getClient();
client->EndSourceFile();
ret = client->getNumErrors();
// The interpreter expects BeginSourceFile/EndSourceFiles to be balanced.
client->BeginSourceFile(CI->getLangOpts(), &CI->getPreprocessor());
}
return ret;
}
<commit_msg>Enable stack trace & suppress error dialog on Windows.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Lukasz Janyst <ljanyst@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Interpreter/Interpreter.h"
#include "cling/MetaProcessor/MetaProcessor.h"
#include "cling/UserInterface/UserInterface.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/ManagedStatic.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#if defined(WIN32) && defined(_MSC_VER)
#include <crtdbg.h>
#endif
int main( int argc, char **argv ) {
llvm::llvm_shutdown_obj shutdownTrigger;
llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
llvm::PrettyStackTraceProgram X(argc, argv);
#if defined(_WIN32) && defined(_MSC_VER)
// Suppress error dialogs to avoid hangs on build nodes.
// One can use an environment variable (Cling_GuiOnAssert) to enable
// the error dialogs.
const char *EnablePopups = getenv("Cling_GuiOnAssert");
if (EnablePopups == nullptr || EnablePopups[0] == '0') {
::_set_error_mode(_OUT_TO_STDERR);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
}
#endif
// Set up the interpreter
cling::Interpreter interp(argc, argv);
if (interp.getOptions().Help) {
return 0;
}
clang::CompilerInstance* CI = interp.getCI();
interp.AddIncludePath(".");
for (size_t I = 0, N = interp.getOptions().LibsToLoad.size(); I < N; ++I) {
interp.loadFile(interp.getOptions().LibsToLoad[I]);
}
// Interactive means no input (or one input that's "-")
std::vector<std::string>& Inputs = interp.getOptions().Inputs;
bool Interactive = Inputs.empty() || (Inputs.size() == 1
&& Inputs[0] == "-");
cling::UserInterface ui(interp);
// If we are not interactive we're supposed to parse files
if (!Interactive) {
for (size_t I = 0, N = Inputs.size(); I < N; ++I) {
std::string cmd;
cling::Interpreter::CompilationResult compRes;
if (!interp.lookupFileOrLibrary(Inputs[I]).empty()) {
std::ifstream infile(interp.lookupFileOrLibrary(Inputs[I]));
std::string line;
std::getline(infile, line);
if (line[0] == '#' && line[1] == '!') {
// TODO: Check whether the filename specified after #! is the current
// executable.
while(std::getline(infile, line)) {
ui.getMetaProcessor()->process(line.c_str(), compRes, 0);
}
continue;
}
else
cmd += ".x ";
}
cmd += Inputs[I];
ui.getMetaProcessor()->process(cmd.c_str(), compRes, 0);
}
}
else {
ui.runInteractively(interp.getOptions().NoLogo);
}
bool ret = CI->getDiagnostics().getClient()->getNumErrors();
// if we are running with -verify a reported has to be returned as unsuccess.
// This is relevant especially for the test suite.
if (CI->getDiagnosticOpts().VerifyDiagnostics) {
// If there was an error that came from the verifier we must return 1 as
// an exit code for the process. This will make the test fail as expected.
clang::DiagnosticConsumer* client = CI->getDiagnostics().getClient();
client->EndSourceFile();
ret = client->getNumErrors();
// The interpreter expects BeginSourceFile/EndSourceFiles to be balanced.
client->BeginSourceFile(CI->getLangOpts(), &CI->getPreprocessor());
}
return ret;
}
<|endoftext|> |
<commit_before>// @(#)root/gl:$Id$
// Author: Olivier Couet 17/04/2007
/*************************************************************************
* Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "Riostream.h"
#include "TROOT.h"
#include "TGLIncludes.h"
#include "TGLUtil.h"
#include "TGLAxis.h"
#include "TGLText.h"
#include "TColor.h"
#include "TString.h"
#include "TMath.h"
#include "THLimitsFinder.h"
//______________________________________________________________________________
/* Begin_Html
<center><h2>GL Axis</h2></center>
To draw a 3D axis in a GL window. The labels are drawn using FTGL.
End_Html */
ClassImp(TGLAxis)
//______________________________________________________________________________
TGLAxis::TGLAxis(): TAttLine(1,1,1), TAttText(20,0.,1,42,0.04)
{
// Constructor.
Init();
}
//______________________________________________________________________________
void TGLAxis::Init()
{
// Default initialization.
fNDiv = fNDiv1 = fNDiv2 = fNDiv3 = 0;
fNTicks1 = fNTicks2 = 0;
fTicks1 = 0;
fTicks2 = 0;
fLabels = 0;
fText = 0;
fAngle1 = 90.;
fAngle2 = 0.;
fAngle3 = 0.;
fAxisLength = 0.;
fWmin = fWmax = 0.;
fTickMarksLength = 0.04; // % of fAxisLength
fTickMarksOrientation = 2; // can be 0, 1, 2, or 3
fLabelsOffset = 0.09; // % of fAxisLength
fLabelsSize = 0.06; // % of fAxisLength
fGridLength = 0.; // 0 means no grid
}
//______________________________________________________________________________
TGLAxis::~TGLAxis()
{
// Destructor.
if (fTicks1) delete [] fTicks1;
if (fTicks2) delete [] fTicks2;
if (fLabels) delete [] fLabels;
if (fText) delete fText;
}
//______________________________________________________________________________
void TGLAxis::PaintGLAxis(const Double_t p1[3], const Double_t p2[3],
Double_t wmin, Double_t wmax, Int_t ndiv,
Option_t *opt)
{
// Paint GL Axis.
//
// p1, p2 : Axis position in the 3D space.
// wmin, wmax : Minimum and maximum values along the axis. wmin < wmax.
// ndiv : Number of axis divisions. It is an integer in the form
// "ttsspp" where "tt" is the number of tertiary divisions,
// "ss" is the number of secondary divisions and "pp" the
// number of primary divisions.
// opt : Options.
// "N" - By default the number of divisions is optimized to
// get a nice labeling. When option "N" is given, the
// number of divisions is not optimized.
fNDiv = ndiv;
if (wmax<=wmin) {
fWmax = wmin;
fWmin = wmax;
} else {
fWmax = wmax;
fWmin = wmin;
}
// Compute the axis length.
Double_t x1 = p1[0], y1 = p1[1], z1 = p1[2];
Double_t x2 = p2[0], y2 = p2[1], z2 = p2[2];
fAxisLength = TMath::Sqrt((x2-x1)*(x2-x1)+
(y2-y1)*(y2-y1)+
(z2-z1)*(z2-z1));
TicksPositions(opt);
DoLabels();
// Paint using GL
glPushMatrix();
// Translation
glTranslatef(x1, y1, z1);
// Rotation in the Z plane
Double_t phi=0;
Double_t normal[3];
normal[0] = 0;
normal[1] = 1;
normal[2] = 0;
if (z1!=z2) {
if (y2==y1 && x2==x1) {
if (z2<z1) phi = 90;
else phi = 270;
} else {
Double_t p3[3];
p3[0] = p2[0]; p3[1] = p2[1]; p3[2] = 0;
TMath::Normal2Plane(p1, p2, p3, normal);
phi = TMath::ACos(TMath::Abs(z2-z1)/fAxisLength);
phi = -(90-(180/TMath::Pi())*phi);
}
glRotatef(phi, normal[0], normal[1], normal[2]);
}
// Rotation in the XY plane
Double_t theta = 0;
if (y2!=y1) {
if ((x2-x1)>0) {
theta = TMath::ATan((y2-y1)/(x2-x1));
theta = (180/TMath::Pi())*theta;
} else if ((x2-x1)<0) {
theta = TMath::ATan((y2-y1)/(x2-x1));
theta = 180+(180/TMath::Pi())*theta;
} else {
if (y2>y1) theta = 90;
else theta = 270;
}
} else {
if (x2<x1) theta = 180;
}
glRotatef(theta, 0., 0., 1.);
PaintGLAxisBody();
PaintGLAxisTickMarks();
PaintGLAxisLabels();
glPopMatrix();
}
//______________________________________________________________________________
void TGLAxis::PaintGLAxisBody()
{
// Paint horizontal axis body at position (0,0,0)
TColor *col;
Float_t red, green, blue;
col = gROOT->GetColor(GetLineColor());
col->GetRGB(red, green, blue);
glColor3d(red, green, blue);
TGLUtil::LineWidth(GetLineWidth());
glBegin(GL_LINES);
glVertex3d(0., 0., 0.);
glVertex3d(fAxisLength, 0., 0.);
glEnd();
}
//______________________________________________________________________________
void TGLAxis::PaintGLAxisTickMarks()
{
// Paint axis tick marks.
Int_t i;
// Ticks marks orientation;
Double_t yo=0, zo=0;
switch (fTickMarksOrientation) {
case 0:
yo = 0;
zo = 1;
break;
case 1:
yo = -1;
zo = 0;
break;
case 2:
yo = 0;
zo = -1;
break;
case 3:
yo = 1;
zo = 0;
break;
}
// Paint level 1 tick marks.
if (fTicks1) {
// Paint the tick marks, if needed.
if (fTickMarksLength) {
Double_t tl = fTickMarksLength*fAxisLength;
glBegin(GL_LINES);
for (i=0; i<fNTicks1 ; i++) {
glVertex3f( fTicks1[i], 0, 0);
glVertex3f( fTicks1[i], yo*tl, zo*tl);
}
glEnd();
}
// Paint the grid, if needed, on level 1 tick marks.
if (fGridLength) {
const UShort_t stipple = 0x8888;
glLineStipple(1, stipple);
glEnable(GL_LINE_STIPPLE);
glBegin(GL_LINES);
for (i=0; i<fNTicks1; i++) {
glVertex3f( fTicks1[i], 0, 0);
glVertex3f( fTicks1[i], -yo*fGridLength, -zo*fGridLength);
}
glEnd();
glDisable(GL_LINE_STIPPLE);
}
}
// Paint level 2 tick marks.
if (fTicks2) {
if (fTickMarksLength) {
Double_t tl = 0.5*fTickMarksLength*fAxisLength;
glBegin(GL_LINES);
for (i=0; i<fNTicks2; i++) {
glVertex3f( fTicks2[i], 0, 0);
glVertex3f( fTicks2[i], yo*tl, zo*tl);
}
glEnd();
}
}
}
//______________________________________________________________________________
void TGLAxis::PaintGLAxisLabels()
{
// Paint axis labels on the main tick marks.
if (!fLabelsSize) return;
Double_t x=0,y=0,z=0;
Int_t i;
if (!fText) {
fText = new TGLText();
fText->SetTextColor(GetTextColor());
fText->SetGLTextFont(GetTextFont());
fText->SetTextSize(fLabelsSize*fAxisLength);
fText->SetTextAlign(GetTextAlign());
}
fText->SetGLTextAngles(fAngle1, fAngle2, fAngle3);
switch (fTickMarksOrientation) {
case 0:
y = 0;
z = fLabelsOffset*fAxisLength;
break;
case 1:
y = -fLabelsOffset*fAxisLength;
z = 0;
break;
case 2:
y = 0;
z = -fLabelsOffset*fAxisLength;
break;
case 3:
y = fLabelsOffset*fAxisLength;
z = 0;
break;
}
for (i=0; i<fNDiv1+1 ; i++) {
x = fTicks1[i];
fText->PaintGLText(x,y,z,fLabels[i]);
}
}
//______________________________________________________________________________
void TGLAxis::TicksPositions(Option_t *opt)
{
// Compute ticks positions.
Bool_t optionNoopt, optionLog;
if (strchr(opt,'N')) optionNoopt = kTRUE; else optionNoopt = kFALSE;
if (strchr(opt,'G')) optionLog = kTRUE; else optionLog = kFALSE;
// Determine number of tick marks 1, 2 and 3.
fNDiv3 = fNDiv/10000;
fNDiv2 = (fNDiv-10000*fNDiv3)/100;
fNDiv1 = fNDiv%100;
// Clean the tick marks arrays if they exist.
if (fTicks1) {
delete [] fTicks1;
fTicks1 = 0;
}
if (fTicks2) {
delete [] fTicks2;
fTicks2 = 0;
}
// Compute the tick marks positions according to the options.
if (optionNoopt) {
TicksPositionsNoOpt();
} else {
TicksPositionsOpt();
}
}
//______________________________________________________________________________
void TGLAxis::TicksPositionsNoOpt()
{
// Compute ticks positions. Linear and not optimized.
Int_t i, j, k;
Double_t step1 = fAxisLength/(fNDiv1);
fNTicks1 = fNDiv1+1;
fTicks1 = new Double_t[fNTicks1];
// Level 1 tick marks.
for (i=0; i<fNTicks1; i++) fTicks1[i] = i*step1;
// Level 2 tick marks.
if (fNDiv2) {
Double_t t2;
Double_t step2 = step1/fNDiv2;
fNTicks2 = fNDiv1*(fNDiv2-1);
fTicks2 = new Double_t[fNTicks2];
k = 0;
for (i=0; i<fNTicks1-1; i++) {
t2 = fTicks1[i]+step2;
for (j=0; j<fNDiv2-1; j++) {
fTicks2[k] = t2;
k++;
t2 = t2+step2;
}
}
}
}
//______________________________________________________________________________
void TGLAxis::TicksPositionsOpt()
{
// Compute ticks positions. Linear and optimized.
Int_t i, j, k, nDivOpt;
Double_t step1=0, step2=0, wmin2=0, wmax2=0;
Double_t wmin = fWmin;
Double_t wmax = fWmax;
// Level 1 tick marks.
THLimitsFinder::Optimize(wmin, wmax, fNDiv1,
fWmin, fWmax, nDivOpt,
step1, "");
fNDiv1 = nDivOpt;
fNTicks1 = fNDiv1+1;
fTicks1 = new Double_t[fNTicks1];
Double_t r = fAxisLength/(wmax-wmin);
Double_t w = fWmin;
i = 0;
while (w<=fWmax) {
fTicks1[i] = r*(w-wmin);
i++;
w = w+step1;
}
// Level 2 tick marks.
if (fNDiv2) {
Double_t t2;
THLimitsFinder::Optimize(fWmin, fWmin+step1, fNDiv2,
wmin2, wmax2, nDivOpt,
step2, "");
fNDiv2 = nDivOpt;
step2 = TMath::Abs((fTicks1[1]-fTicks1[0])/fNDiv2);
Int_t nTickl = (Int_t)(fTicks1[0]/step2);
Int_t nTickr = (Int_t)((fAxisLength-fTicks1[fNTicks1-1])/step2);
fNTicks2 = fNDiv1*(fNDiv2-1)+nTickl+nTickr;
fTicks2 = new Double_t[fNTicks2];
k = 0;
for (i=0; i<fNTicks1-1; i++) {
t2 = fTicks1[i]+step2;
for (j=0; j<fNDiv2-1; j++) {
fTicks2[k] = t2;
k++;
t2 = t2+step2;
}
}
if (nTickl) {
t2 = fTicks1[0]-step2;
for (i=0; i<nTickl; i++) {
fTicks2[k] = t2;
k++;
t2 = t2-step2;
}
}
if (nTickr) {
t2 = fTicks1[fNTicks1-1]+step2;
for (i=0; i<nTickr; i++) {
fTicks2[k] = t2;
k++;
t2 = t2+step2;
}
}
}
}
//______________________________________________________________________________
void TGLAxis::DoLabels()
{
// Do labels.
if (fLabels) delete [] fLabels;
fLabels = new TString[fNTicks1];
Int_t i;
// Make regular labels between fWmin and fWmax.
Double_t dw = (fWmax-fWmin)/(fNDiv1);
for (i=0; i<fNTicks1; i++) {
fLabels[i] = Form("%g",fWmin+i*dw);
}
}
//______________________________________________________________________________
void TGLAxis::SetLabelsAngles(Double_t a1, Double_t a2, Double_t a3)
{
// Set labels' angles.
fAngle1 = a1;
fAngle2 = a2;
fAngle3 = a3;
}
<commit_msg>Coverity fix: result of gROOT->GetColor was not checked.<commit_after>// @(#)root/gl:$Id$
// Author: Olivier Couet 17/04/2007
/*************************************************************************
* Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "Riostream.h"
#include "TROOT.h"
#include "TGLIncludes.h"
#include "TGLUtil.h"
#include "TGLAxis.h"
#include "TGLText.h"
#include "TColor.h"
#include "TString.h"
#include "TMath.h"
#include "THLimitsFinder.h"
//______________________________________________________________________________
/* Begin_Html
<center><h2>GL Axis</h2></center>
To draw a 3D axis in a GL window. The labels are drawn using FTGL.
End_Html */
ClassImp(TGLAxis)
//______________________________________________________________________________
TGLAxis::TGLAxis(): TAttLine(1,1,1), TAttText(20,0.,1,42,0.04)
{
// Constructor.
Init();
}
//______________________________________________________________________________
void TGLAxis::Init()
{
// Default initialization.
fNDiv = fNDiv1 = fNDiv2 = fNDiv3 = 0;
fNTicks1 = fNTicks2 = 0;
fTicks1 = 0;
fTicks2 = 0;
fLabels = 0;
fText = 0;
fAngle1 = 90.;
fAngle2 = 0.;
fAngle3 = 0.;
fAxisLength = 0.;
fWmin = fWmax = 0.;
fTickMarksLength = 0.04; // % of fAxisLength
fTickMarksOrientation = 2; // can be 0, 1, 2, or 3
fLabelsOffset = 0.09; // % of fAxisLength
fLabelsSize = 0.06; // % of fAxisLength
fGridLength = 0.; // 0 means no grid
}
//______________________________________________________________________________
TGLAxis::~TGLAxis()
{
// Destructor.
if (fTicks1) delete [] fTicks1;
if (fTicks2) delete [] fTicks2;
if (fLabels) delete [] fLabels;
if (fText) delete fText;
}
//______________________________________________________________________________
void TGLAxis::PaintGLAxis(const Double_t p1[3], const Double_t p2[3],
Double_t wmin, Double_t wmax, Int_t ndiv,
Option_t *opt)
{
// Paint GL Axis.
//
// p1, p2 : Axis position in the 3D space.
// wmin, wmax : Minimum and maximum values along the axis. wmin < wmax.
// ndiv : Number of axis divisions. It is an integer in the form
// "ttsspp" where "tt" is the number of tertiary divisions,
// "ss" is the number of secondary divisions and "pp" the
// number of primary divisions.
// opt : Options.
// "N" - By default the number of divisions is optimized to
// get a nice labeling. When option "N" is given, the
// number of divisions is not optimized.
fNDiv = ndiv;
if (wmax<=wmin) {
fWmax = wmin;
fWmin = wmax;
} else {
fWmax = wmax;
fWmin = wmin;
}
// Compute the axis length.
Double_t x1 = p1[0], y1 = p1[1], z1 = p1[2];
Double_t x2 = p2[0], y2 = p2[1], z2 = p2[2];
fAxisLength = TMath::Sqrt((x2-x1)*(x2-x1)+
(y2-y1)*(y2-y1)+
(z2-z1)*(z2-z1));
TicksPositions(opt);
DoLabels();
// Paint using GL
glPushMatrix();
// Translation
glTranslatef(x1, y1, z1);
// Rotation in the Z plane
Double_t phi=0;
Double_t normal[3];
normal[0] = 0;
normal[1] = 1;
normal[2] = 0;
if (z1!=z2) {
if (y2==y1 && x2==x1) {
if (z2<z1) phi = 90;
else phi = 270;
} else {
Double_t p3[3];
p3[0] = p2[0]; p3[1] = p2[1]; p3[2] = 0;
TMath::Normal2Plane(p1, p2, p3, normal);
phi = TMath::ACos(TMath::Abs(z2-z1)/fAxisLength);
phi = -(90-(180/TMath::Pi())*phi);
}
glRotatef(phi, normal[0], normal[1], normal[2]);
}
// Rotation in the XY plane
Double_t theta = 0;
if (y2!=y1) {
if ((x2-x1)>0) {
theta = TMath::ATan((y2-y1)/(x2-x1));
theta = (180/TMath::Pi())*theta;
} else if ((x2-x1)<0) {
theta = TMath::ATan((y2-y1)/(x2-x1));
theta = 180+(180/TMath::Pi())*theta;
} else {
if (y2>y1) theta = 90;
else theta = 270;
}
} else {
if (x2<x1) theta = 180;
}
glRotatef(theta, 0., 0., 1.);
PaintGLAxisBody();
PaintGLAxisTickMarks();
PaintGLAxisLabels();
glPopMatrix();
}
//______________________________________________________________________________
void TGLAxis::PaintGLAxisBody()
{
// Paint horizontal axis body at position (0,0,0)
TColor *col;
Float_t red = 1.f, green = 1.f, blue = 1.f;
if ((col = gROOT->GetColor(GetLineColor())))
col->GetRGB(red, green, blue);
glColor3d(red, green, blue);
TGLUtil::LineWidth(GetLineWidth());
glBegin(GL_LINES);
glVertex3d(0., 0., 0.);
glVertex3d(fAxisLength, 0., 0.);
glEnd();
}
//______________________________________________________________________________
void TGLAxis::PaintGLAxisTickMarks()
{
// Paint axis tick marks.
Int_t i;
// Ticks marks orientation;
Double_t yo=0, zo=0;
switch (fTickMarksOrientation) {
case 0:
yo = 0;
zo = 1;
break;
case 1:
yo = -1;
zo = 0;
break;
case 2:
yo = 0;
zo = -1;
break;
case 3:
yo = 1;
zo = 0;
break;
}
// Paint level 1 tick marks.
if (fTicks1) {
// Paint the tick marks, if needed.
if (fTickMarksLength) {
Double_t tl = fTickMarksLength*fAxisLength;
glBegin(GL_LINES);
for (i=0; i<fNTicks1 ; i++) {
glVertex3f( fTicks1[i], 0, 0);
glVertex3f( fTicks1[i], yo*tl, zo*tl);
}
glEnd();
}
// Paint the grid, if needed, on level 1 tick marks.
if (fGridLength) {
const UShort_t stipple = 0x8888;
glLineStipple(1, stipple);
glEnable(GL_LINE_STIPPLE);
glBegin(GL_LINES);
for (i=0; i<fNTicks1; i++) {
glVertex3f( fTicks1[i], 0, 0);
glVertex3f( fTicks1[i], -yo*fGridLength, -zo*fGridLength);
}
glEnd();
glDisable(GL_LINE_STIPPLE);
}
}
// Paint level 2 tick marks.
if (fTicks2) {
if (fTickMarksLength) {
Double_t tl = 0.5*fTickMarksLength*fAxisLength;
glBegin(GL_LINES);
for (i=0; i<fNTicks2; i++) {
glVertex3f( fTicks2[i], 0, 0);
glVertex3f( fTicks2[i], yo*tl, zo*tl);
}
glEnd();
}
}
}
//______________________________________________________________________________
void TGLAxis::PaintGLAxisLabels()
{
// Paint axis labels on the main tick marks.
if (!fLabelsSize) return;
Double_t x=0,y=0,z=0;
Int_t i;
if (!fText) {
fText = new TGLText();
fText->SetTextColor(GetTextColor());
fText->SetGLTextFont(GetTextFont());
fText->SetTextSize(fLabelsSize*fAxisLength);
fText->SetTextAlign(GetTextAlign());
}
fText->SetGLTextAngles(fAngle1, fAngle2, fAngle3);
switch (fTickMarksOrientation) {
case 0:
y = 0;
z = fLabelsOffset*fAxisLength;
break;
case 1:
y = -fLabelsOffset*fAxisLength;
z = 0;
break;
case 2:
y = 0;
z = -fLabelsOffset*fAxisLength;
break;
case 3:
y = fLabelsOffset*fAxisLength;
z = 0;
break;
}
for (i=0; i<fNDiv1+1 ; i++) {
x = fTicks1[i];
fText->PaintGLText(x,y,z,fLabels[i]);
}
}
//______________________________________________________________________________
void TGLAxis::TicksPositions(Option_t *opt)
{
// Compute ticks positions.
Bool_t optionNoopt, optionLog;
if (strchr(opt,'N')) optionNoopt = kTRUE; else optionNoopt = kFALSE;
if (strchr(opt,'G')) optionLog = kTRUE; else optionLog = kFALSE;
// Determine number of tick marks 1, 2 and 3.
fNDiv3 = fNDiv/10000;
fNDiv2 = (fNDiv-10000*fNDiv3)/100;
fNDiv1 = fNDiv%100;
// Clean the tick marks arrays if they exist.
if (fTicks1) {
delete [] fTicks1;
fTicks1 = 0;
}
if (fTicks2) {
delete [] fTicks2;
fTicks2 = 0;
}
// Compute the tick marks positions according to the options.
if (optionNoopt) {
TicksPositionsNoOpt();
} else {
TicksPositionsOpt();
}
}
//______________________________________________________________________________
void TGLAxis::TicksPositionsNoOpt()
{
// Compute ticks positions. Linear and not optimized.
Int_t i, j, k;
Double_t step1 = fAxisLength/(fNDiv1);
fNTicks1 = fNDiv1+1;
fTicks1 = new Double_t[fNTicks1];
// Level 1 tick marks.
for (i=0; i<fNTicks1; i++) fTicks1[i] = i*step1;
// Level 2 tick marks.
if (fNDiv2) {
Double_t t2;
Double_t step2 = step1/fNDiv2;
fNTicks2 = fNDiv1*(fNDiv2-1);
fTicks2 = new Double_t[fNTicks2];
k = 0;
for (i=0; i<fNTicks1-1; i++) {
t2 = fTicks1[i]+step2;
for (j=0; j<fNDiv2-1; j++) {
fTicks2[k] = t2;
k++;
t2 = t2+step2;
}
}
}
}
//______________________________________________________________________________
void TGLAxis::TicksPositionsOpt()
{
// Compute ticks positions. Linear and optimized.
Int_t i, j, k, nDivOpt;
Double_t step1=0, step2=0, wmin2=0, wmax2=0;
Double_t wmin = fWmin;
Double_t wmax = fWmax;
// Level 1 tick marks.
THLimitsFinder::Optimize(wmin, wmax, fNDiv1,
fWmin, fWmax, nDivOpt,
step1, "");
fNDiv1 = nDivOpt;
fNTicks1 = fNDiv1+1;
fTicks1 = new Double_t[fNTicks1];
Double_t r = fAxisLength/(wmax-wmin);
Double_t w = fWmin;
i = 0;
while (w<=fWmax) {
fTicks1[i] = r*(w-wmin);
i++;
w = w+step1;
}
// Level 2 tick marks.
if (fNDiv2) {
Double_t t2;
THLimitsFinder::Optimize(fWmin, fWmin+step1, fNDiv2,
wmin2, wmax2, nDivOpt,
step2, "");
fNDiv2 = nDivOpt;
step2 = TMath::Abs((fTicks1[1]-fTicks1[0])/fNDiv2);
Int_t nTickl = (Int_t)(fTicks1[0]/step2);
Int_t nTickr = (Int_t)((fAxisLength-fTicks1[fNTicks1-1])/step2);
fNTicks2 = fNDiv1*(fNDiv2-1)+nTickl+nTickr;
fTicks2 = new Double_t[fNTicks2];
k = 0;
for (i=0; i<fNTicks1-1; i++) {
t2 = fTicks1[i]+step2;
for (j=0; j<fNDiv2-1; j++) {
fTicks2[k] = t2;
k++;
t2 = t2+step2;
}
}
if (nTickl) {
t2 = fTicks1[0]-step2;
for (i=0; i<nTickl; i++) {
fTicks2[k] = t2;
k++;
t2 = t2-step2;
}
}
if (nTickr) {
t2 = fTicks1[fNTicks1-1]+step2;
for (i=0; i<nTickr; i++) {
fTicks2[k] = t2;
k++;
t2 = t2+step2;
}
}
}
}
//______________________________________________________________________________
void TGLAxis::DoLabels()
{
// Do labels.
if (fLabels) delete [] fLabels;
fLabels = new TString[fNTicks1];
Int_t i;
// Make regular labels between fWmin and fWmax.
Double_t dw = (fWmax-fWmin)/(fNDiv1);
for (i=0; i<fNTicks1; i++) {
fLabels[i] = Form("%g",fWmin+i*dw);
}
}
//______________________________________________________________________________
void TGLAxis::SetLabelsAngles(Double_t a1, Double_t a2, Double_t a3)
{
// Set labels' angles.
fAngle1 = a1;
fAngle2 = a2;
fAngle3 = a3;
}
<|endoftext|> |
<commit_before>/// HEADER
#include <csapex/model/node.h>
/// PROJECT
#include <csapex/msg/io.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/model/node_modifier.h>
#include <csapex/msg/generic_value_message.hpp>
#include <csapex/msg/any_message.h>
#include <csapex/signal/event.h>
#include <csapex/model/token.h>
#include <csapex/serialization/message_serializer.h>
namespace csapex
{
namespace state
{
class MemoryCell : public Node
{
private:
class Cell {
public:
void setMessage(const connection_types::MessageConstPtr msg)
{
apex_assert(msg);
if(msg != message) {
message = msg;
changed(message);
}
}
public:
slim_signal::Signal<void (connection_types::MessageConstPtr)> changed;
private:
connection_types::MessageConstPtr message;
};
public:
MemoryCell()
{
}
void setupParameters(Parameterizable& parameters) override
{
parameters.addParameter(param::ParameterFactory::declareText("name", ""), [this](param::Parameter* p)
{
std::string name = p->as<std::string>();
if(name != name_) {
name_ = name;
Cell& c = getCell(name_);
connection_ = c.changed.connect([this](connection_types::MessageConstPtr new_val) {
updateValue(new_val);
});
}
});
parameters.addParameter(param::ParameterFactory::declareBool("show_content", false), show_content_);
parameters.addConditionalParameter(param::ParameterFactory::declareOutputText("text"), show_content_);
}
void setup(NodeModifier& modifier) override
{
modifier.addTypedSlot<csapex::connection_types::AnyMessage>("set", [this](const TokenPtr& token)
{
if(!name_.empty()) {
auto message = std::dynamic_pointer_cast<connection_types::Message const>(token->getTokenData());
getCell(name_).setMessage(message);
}
});
change_event_ = modifier.addEvent("changed");
}
void process()
{
}
private:
void updateValue(const connection_types::MessageConstPtr& new_val) {
TokenPtr token = std::make_shared<Token>(new_val);
change_event_->triggerWith(token);
if(show_content_) {
YAML::Node node;
node = MessageSerializer::serializeMessage(*new_val);
std::stringstream ss;
convert(ss, node, "");
setParameter("text", ss.str());
}
}
void convert(std::stringstream &ss, const YAML::Node &node, const std::string& prefix)
{
static const std::string PREFIX = " ";
if(node.IsMap()) {
std::vector<std::string> keys;
for(YAML::Node::const_iterator it = node.begin(); it != node.end(); ++it) {
keys.push_back(it->first.as<std::string>());
}
std::sort(keys.begin(), keys.end());
for(std::vector<std::string>::iterator key = keys.begin(); key != keys.end(); ++key) {
ss << prefix << *key << ": \n";
convert(ss, node[*key], prefix + PREFIX);
ss << "\n";
}
} else if(node.IsSequence()) {
std::size_t total = node.size();
std::size_t max_count = 16;
for(std::size_t i = 0, n = std::min(max_count, total); i < n; ++i) {
convert(ss, node[i], prefix + "|");
ss << "\n";
}
if(max_count < total) {
ss << "...\n";
}
} else if(node.Type() != YAML::NodeType::Null) {
ss << prefix << node.as<std::string>().substr(0, 1000);
}
}
static Cell& getCell(const std::string& name)
{
static std::mutex mutex;
std::lock_guard<std::mutex> lock(mutex);
static std::map<std::string, Cell> cache;
return cache[name];
}
private:
std::string name_;
bool show_content_;
Event* change_event_;
slim_signal::ScopedConnection connection_;
};
}
}
CSAPEX_REGISTER_CLASS(csapex::state::MemoryCell, csapex::Node)
<commit_msg>lots of fixes in memory cell<commit_after>/// HEADER
#include <csapex/model/node.h>
/// PROJECT
#include <csapex/msg/io.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/model/node_modifier.h>
#include <csapex/msg/generic_value_message.hpp>
#include <csapex/msg/any_message.h>
#include <csapex/signal/event.h>
#include <csapex/model/token.h>
#include <csapex/serialization/message_serializer.h>
namespace csapex
{
namespace state
{
class MemoryCell : public Node
{
private:
class Cell {
public:
void setMessage(const connection_types::MessageConstPtr msg)
{
apex_assert(msg);
if(msg != message) {
message = msg;
changed(message);
}
}
void clear()
{
if(message) {
message.reset();
changed(message);
}
}
public:
slim_signal::Signal<void (connection_types::MessageConstPtr)> changed;
private:
connection_types::MessageConstPtr message;
};
public:
MemoryCell()
: changed_(false)
{
}
void setupParameters(Parameterizable& parameters) override
{
parameters.addParameter(param::ParameterFactory::declareText("name", ""), [this](param::Parameter* p)
{
std::string name = p->as<std::string>();
if(name != name_) {
name_ = name;
Cell& c = getCell(name_);
connection_ = c.changed.connect([this](connection_types::MessageConstPtr new_val) {
updateValue(new_val);
});
}
});
parameters.addParameter(param::ParameterFactory::declareTrigger("export"), [this](param::Parameter*) {
std::unique_lock<std::recursive_mutex> lock(value_mutex_);
if(value_) {
TokenPtr token = std::make_shared<Token>(value_);
lock.unlock();
publish_event_->triggerWith(token);
} else {
lock.unlock();
empty_event_->trigger();
}
});
parameters.addParameter(param::ParameterFactory::declareTrigger("clear"), [this](param::Parameter*) {
if(!name_.empty()) {
getCell(name_).clear();
}
});
parameters.addParameter(param::ParameterFactory::declareBool("show_content", false), show_content_);
parameters.addConditionalParameter(param::ParameterFactory::declareOutputText("text"), show_content_);
}
void setup(NodeModifier& modifier) override
{
modifier.addTypedSlot<csapex::connection_types::AnyMessage>("set", [this](const TokenPtr& token)
{
if(!name_.empty()) {
auto message = std::dynamic_pointer_cast<connection_types::Message const>(token->getTokenData());
getCell(name_).setMessage(message);
}
});
change_event_ = modifier.addEvent("changed");
clear_event_ = modifier.addEvent("cleared");
publish_event_ = modifier.addEvent("published");
empty_event_ = modifier.addEvent("empty");
}
bool canProcess() const
{
return changed_;
}
void process()
{
if(changed_cell_) {
TokenPtr token;
{
std::unique_lock<std::recursive_mutex> lock(value_mutex_);
value_ = changed_cell_;
token = std::make_shared<Token>(value_->clone());
}
change_event_->triggerWith(token);
if(show_content_) {
YAML::Node node;
node = MessageSerializer::serializeMessage(*changed_cell_);
std::stringstream ss;
convert(ss, node, "");
setParameter("text", ss.str());
}
} else {
{
std::unique_lock<std::recursive_mutex> lock(value_mutex_);
value_.reset();
}
clear_event_->trigger();
if(show_content_) {
setParameter("text", std::string(""));
}
}
changed_cell_.reset();
changed_ = false;
}
private:
void updateValue(const connection_types::MessageConstPtr& new_val) {
changed_cell_ = new_val;
changed_ = true;
yield();
}
void convert(std::stringstream &ss, const YAML::Node &node, const std::string& prefix)
{
static const std::string PREFIX = " ";
if(node.IsMap()) {
std::vector<std::string> keys;
for(YAML::Node::const_iterator it = node.begin(); it != node.end(); ++it) {
keys.push_back(it->first.as<std::string>());
}
std::sort(keys.begin(), keys.end());
for(std::vector<std::string>::iterator key = keys.begin(); key != keys.end(); ++key) {
ss << prefix << *key << ": \n";
convert(ss, node[*key], prefix + PREFIX);
ss << "\n";
}
} else if(node.IsSequence()) {
std::size_t total = node.size();
std::size_t max_count = 16;
for(std::size_t i = 0, n = std::min(max_count, total); i < n; ++i) {
convert(ss, node[i], prefix + "|");
ss << "\n";
}
if(max_count < total) {
ss << "...\n";
}
} else if(node.Type() != YAML::NodeType::Null) {
ss << prefix << node.as<std::string>().substr(0, 1000);
}
}
static Cell& getCell(const std::string& name)
{
static std::mutex mutex;
std::lock_guard<std::mutex> lock(mutex);
static std::map<std::string, Cell> cache;
return cache[name];
}
private:
std::string name_;
bool show_content_;
bool changed_;
connection_types::MessageConstPtr changed_cell_;
Event* change_event_;
Event* clear_event_;
Event* publish_event_;
Event* empty_event_;
slim_signal::ScopedConnection connection_;
std::recursive_mutex value_mutex_;
connection_types::MessageConstPtr value_;
};
}
}
CSAPEX_REGISTER_CLASS(csapex::state::MemoryCell, csapex::Node)
<|endoftext|> |
<commit_before>#include "Nav.hpp"
namespace NAV
{
vector<Marker> FillMarkerList(std::vector<KeyDataPair> data)
{
vector<Marker> markers;
geometry_msgs::Pose p;
MarkerType t;
std::string name;
for (int i = 0; i < data.size(); i++)
{
if(data[i].key.compare(0,6,"Marker") == 0)
{
if(data[i].data[0].compare(0,3,"She") == 0)
{
t = Shelf;
}
else if(data[i].data[0].compare(0,3,"Wor") == 0)
{
t = Workstation;
}
else if(data[i].data[0].compare(0,3,"Con") == 0)
{
t = Conveyor;
}
else if(data[i].data[0].compare(0,3,"Way") == 0)
{
t = Waypoint;
}
else if(data[i].data[0].compare(0,3,"Pre") == 0)
{
t = Precision;
}
else
{
std::cout << data[i].data[0] << std::endl;
t = Robot;
}
}
else if (data[i].key.compare("position_x") == 0)
{
p.position.x = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("position_y") == 0)
{
p.position.y = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("position_z") == 0)
{
p.position.z = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("orientation_x") == 0)
{
p.orientation.x = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("orientation_y") == 0)
{
p.orientation.y = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("orientation_z") == 0)
{
p.orientation.z = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("orientation_w") == 0)
{
p.orientation.w = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("Name") == 0)
{
name = data[i].data[0];
}
else
{
ROS_ERROR("Unkown data!");
}
if(i == data.size() -1 || i < data.size() - 1 && data[i+1].key.compare(0,6,"Marker") == 0)
{
Marker m(p, t, name);
markers.push_back(m);
t = Robot;
p.position.x = 0;
p.position.y = 0;
p.position.z = 0;
p.orientation.x = 0;
p.orientation.y = 0;
p.orientation.z = 0;
p.orientation.w = 0;
name = "";
}
}
return markers;
}
vector<NoGoLine> FillLineList(std::vector<KeyDataPair> data, vector<NoGoLines> lines)
{
vector<NoGoLines lines;
double x1;
double x2;
double y1;
double y2;
std::string name;
for (int i = 0; i < data.size(); i++)
{
if (data[i].key.compare("x1") == 0)
{
x1 = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("x2") == 0)
{
x2 = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("y1") == 0)
{
y1 = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("y2") == 0)
{
y2 = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("Name") == 0)
{
name = data[i].data[0];
}
else
{
ROS_ERROR("Unkown data!");
}
if(i == data.size() -1 || i < data.size() - 1 && data[i+1].key.compare(0,8,"NoGoLine") == 0)
{
NoGoLine l(x1, y1, x2, y2, name);
lines.push_back(l);
x1 = 0;
x2 = 0;
y1 = 0;
y2 = 0;
name = "";
}
}
return lines;
}
std::vector<Marker> LoadMarkers(std::string filename){
YamlParser yamlp;
yamlp.loadYaml(filename);
return FillMarkerList(yamlp.GetParsedYaml());
}
std::vector<NoGoLine> LoadNoGoLines(std::string filename){
YamlParser yamlp;
yamlp.loadYaml(filename);
return FillLineList(yamlp.GetParsedYaml());
}
MapConfig LoadMap(std::string filename){
YamlParser yamlp;
yaml.loadYaml(filename);
MapConfig mapconfig;
mapConfig.setFullConfigData(yaml.GetParsedYaml());
return mapconfig;
}
void WriteMarkers(vector<Marker> markers, std::string filename){
yamlWriter.writeAllMarkers(markers, filename);
}
void WriteNoGoLines(vector<NoGoLine lines, std::string filename){
yamlWriter.writeAllLines(lines, filename);
}
}
<commit_msg>Cleaned build errors<commit_after>#include "nav_lib/Nav.hpp"
namespace NAV
{
std::vector<Marker> FillMarkerList(std::vector<KeyDataPair> data)
{
std::vector<Marker> markers;
geometry_msgs::Pose p;
MarkerType t;
std::string name;
for (int i = 0; i < data.size(); i++)
{
if(data[i].key.compare(0,6,"Marker") == 0)
{
if(data[i].data[0].compare(0,3,"She") == 0)
{
t = Shelf;
}
else if(data[i].data[0].compare(0,3,"Wor") == 0)
{
t = Workstation;
}
else if(data[i].data[0].compare(0,3,"Con") == 0)
{
t = Conveyor;
}
else if(data[i].data[0].compare(0,3,"Way") == 0)
{
t = Waypoint;
}
else if(data[i].data[0].compare(0,3,"Pre") == 0)
{
t = Precision;
}
else
{
std::cout << data[i].data[0] << std::endl;
t = Robot;
}
}
else if (data[i].key.compare("position_x") == 0)
{
p.position.x = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("position_y") == 0)
{
p.position.y = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("position_z") == 0)
{
p.position.z = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("orientation_x") == 0)
{
p.orientation.x = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("orientation_y") == 0)
{
p.orientation.y = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("orientation_z") == 0)
{
p.orientation.z = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("orientation_w") == 0)
{
p.orientation.w = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("Name") == 0)
{
name = data[i].data[0];
}
else
{
ROS_ERROR("Unkown data!");
}
if(i == data.size() -1 || i < data.size() - 1 && data[i+1].key.compare(0,6,"Marker") == 0)
{
Marker m(p, t, name);
markers.push_back(m);
t = Robot;
p.position.x = 0;
p.position.y = 0;
p.position.z = 0;
p.orientation.x = 0;
p.orientation.y = 0;
p.orientation.z = 0;
p.orientation.w = 0;
name = "";
}
}
return markers;
}
std::vector<NoGoLine> FillLineList(std::vector<KeyDataPair> data)//, std::vector<NoGoLine> lines)
{
std::vector<NoGoLine> lines;
double x1;
double x2;
double y1;
double y2;
std::string name;
for (int i = 0; i < data.size(); i++)
{
if (data[i].key.compare("x1") == 0)
{
x1 = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("x2") == 0)
{
x2 = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("y1") == 0)
{
y1 = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("y2") == 0)
{
y2 = std::atof(data[i].data[0].c_str());
}
else if (data[i].key.compare("Name") == 0)
{
name = data[i].data[0];
}
else
{
ROS_ERROR("Unkown data!");
}
if(i == data.size() -1 || i < data.size() - 1 && data[i+1].key.compare(0,8,"NoGoLine") == 0)
{
NoGoLine l(x1, y1, x2, y2, name);
lines.push_back(l);
x1 = 0;
x2 = 0;
y1 = 0;
y2 = 0;
name = "";
}
}
return lines;
}
std::vector<Marker> LoadMarkers(std::string filename){
YamlParser yamlp;
yamlp.loadYaml(filename);
return FillMarkerList(yamlp.GetParsedYaml());
}
std::vector<NoGoLine> LoadNoGoLines(std::string filename){
YamlParser yamlp;
yamlp.loadYaml(filename);
return FillLineList(yamlp.GetParsedYaml());
}
MapConfig LoadMap(std::string filename){
YamlParser yamlp;
yamlp.loadYaml(filename);
MapConfig mapconfig;
mapconfig.setFullConfigData(yamlp.GetParsedYaml());
return mapconfig;
}
void WriteMarkers(std::vector<Marker> markers, std::string filename){
YamlWriter yamlWriter;
yamlWriter.writeAllMarkers(markers, filename);
}
void WriteNoGoLines(std::vector<NoGoLine> lines, std::string filename){
YamlWriter yamlWriter;
yamlWriter.writeAllLines(lines, filename);
}
};
<|endoftext|> |
<commit_before>/* Copyright 2017 Istio Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/istio/mixerclient/attribute_compressor.h"
#include "google/protobuf/arena.h"
#include "include/istio/utils/protobuf.h"
#include "src/istio/mixerclient/global_dictionary.h"
using ::istio::mixer::v1::Attributes;
using ::istio::mixer::v1::Attributes_AttributeValue;
using ::istio::mixer::v1::Attributes_StringMap;
using ::istio::mixer::v1::CompressedAttributes;
namespace istio {
namespace mixerclient {
namespace {
// The size of first version of global dictionary.
// If any dictionary error, global dictionary will fall back to this version.
const int kGlobalDictionaryBaseSize = 111;
// Return per message dictionary index.
int MessageDictIndex(int idx) { return -(idx + 1); }
// Per message dictionary.
class MessageDictionary {
public:
MessageDictionary(const GlobalDictionary& global_dict)
: global_dict_(global_dict) {}
int GetIndex(const std::string& name) {
int index;
if (global_dict_.GetIndex(name, &index)) {
return index;
}
const auto& message_it = message_dict_.find(name);
if (message_it != message_dict_.end()) {
return MessageDictIndex(message_it->second);
}
index = message_words_.size();
message_words_.push_back(name);
message_dict_[name] = index;
return MessageDictIndex(index);
}
const std::vector<std::string>& GetWords() const { return message_words_; }
void Clear() {
message_words_.clear();
message_dict_.clear();
}
private:
const GlobalDictionary& global_dict_;
// Per message dictionary
std::vector<std::string> message_words_;
std::unordered_map<std::string, int> message_dict_;
};
::istio::mixer::v1::StringMap CreateStringMap(
const Attributes_StringMap& raw_map, MessageDictionary& dict) {
::istio::mixer::v1::StringMap compressed_map;
auto* map_pb = compressed_map.mutable_entries();
for (const auto& it : raw_map.entries()) {
(*map_pb)[dict.GetIndex(it.first)] = dict.GetIndex(it.second);
}
return compressed_map;
}
void CompressByDict(const Attributes& attributes, MessageDictionary& dict,
CompressedAttributes* pb) {
// Fill attributes.
for (const auto& it : attributes.attributes()) {
const std::string& name = it.first;
const Attributes_AttributeValue& value = it.second;
int index = dict.GetIndex(name);
// Fill the attribute to proper map.
switch (value.value_case()) {
case Attributes_AttributeValue::kStringValue:
(*pb->mutable_strings())[index] = dict.GetIndex(value.string_value());
break;
case Attributes_AttributeValue::kBytesValue:
(*pb->mutable_bytes())[index] = value.bytes_value();
break;
case Attributes_AttributeValue::kInt64Value:
(*pb->mutable_int64s())[index] = value.int64_value();
break;
case Attributes_AttributeValue::kDoubleValue:
(*pb->mutable_doubles())[index] = value.double_value();
break;
case Attributes_AttributeValue::kBoolValue:
(*pb->mutable_bools())[index] = value.bool_value();
break;
case Attributes_AttributeValue::kTimestampValue:
(*pb->mutable_timestamps())[index] = value.timestamp_value();
break;
case Attributes_AttributeValue::kDurationValue:
(*pb->mutable_durations())[index] = value.duration_value();
break;
case Attributes_AttributeValue::kStringMapValue:
(*pb->mutable_string_maps())[index] =
CreateStringMap(value.string_map_value(), dict);
break;
case Attributes_AttributeValue::VALUE_NOT_SET:
break;
}
}
}
class BatchCompressorImpl : public BatchCompressor {
public:
BatchCompressorImpl(const GlobalDictionary& global_dict)
: global_dict_(global_dict), dict_(global_dict) {
report_ = google::protobuf::Arena::CreateMessage<
::istio::mixer::v1::ReportRequest>(&arena_);
}
void Add(const Attributes& attributes) override {
CompressByDict(attributes, dict_, report_->add_attributes());
}
int size() const override { return report_->attributes_size(); }
const ::istio::mixer::v1::ReportRequest& Finish() override {
for (const std::string& word : dict_.GetWords()) {
report_->add_default_words(word);
}
report_->set_global_word_count(global_dict_.size());
return *report_;
}
void Clear() override {
dict_.Clear();
report_->Clear();
}
private:
const GlobalDictionary& global_dict_;
// protobuf arena
google::protobuf::Arena arena_;
MessageDictionary dict_;
::istio::mixer::v1::ReportRequest* report_;
};
} // namespace
GlobalDictionary::GlobalDictionary() {
const std::vector<std::string>& global_words = GetGlobalWords();
for (unsigned int i = 0; i < global_words.size(); i++) {
global_dict_[global_words[i]] = i;
}
top_index_ = global_words.size();
}
// Lookup the index, return true if found.
bool GlobalDictionary::GetIndex(const std::string name, int* index) const {
const auto& it = global_dict_.find(name);
if (it != global_dict_.end() && it->second < top_index_) {
// Return global dictionary index.
*index = it->second;
return true;
}
return false;
}
void GlobalDictionary::ShrinkToBase() {
if (top_index_ > kGlobalDictionaryBaseSize) {
top_index_ = kGlobalDictionaryBaseSize;
GOOGLE_LOG(INFO) << "Shrink global dictionary " << top_index_
<< " to base.";
}
}
void AttributeCompressor::Compress(
const Attributes& attributes,
::istio::mixer::v1::CompressedAttributes* pb) const {
MessageDictionary dict(global_dict_);
CompressByDict(attributes, dict, pb);
for (const std::string& word : dict.GetWords()) {
pb->add_words(word);
}
}
std::unique_ptr<BatchCompressor> AttributeCompressor::CreateBatchCompressor()
const {
return std::unique_ptr<BatchCompressor>(
new BatchCompressorImpl(global_dict_));
}
} // namespace mixerclient
} // namespace istio
<commit_msg>fix memory leak at report batching (#1988)<commit_after>/* Copyright 2017 Istio Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/istio/mixerclient/attribute_compressor.h"
#include "google/protobuf/arena.h"
#include "include/istio/utils/protobuf.h"
#include "src/istio/mixerclient/global_dictionary.h"
using ::istio::mixer::v1::Attributes;
using ::istio::mixer::v1::Attributes_AttributeValue;
using ::istio::mixer::v1::Attributes_StringMap;
using ::istio::mixer::v1::CompressedAttributes;
namespace istio {
namespace mixerclient {
namespace {
// The size of first version of global dictionary.
// If any dictionary error, global dictionary will fall back to this version.
const int kGlobalDictionaryBaseSize = 111;
// Return per message dictionary index.
int MessageDictIndex(int idx) { return -(idx + 1); }
// Per message dictionary.
class MessageDictionary {
public:
MessageDictionary(const GlobalDictionary& global_dict)
: global_dict_(global_dict) {}
int GetIndex(const std::string& name) {
int index;
if (global_dict_.GetIndex(name, &index)) {
return index;
}
const auto& message_it = message_dict_.find(name);
if (message_it != message_dict_.end()) {
return MessageDictIndex(message_it->second);
}
index = message_words_.size();
message_words_.push_back(name);
message_dict_[name] = index;
return MessageDictIndex(index);
}
const std::vector<std::string>& GetWords() const { return message_words_; }
void Clear() {
message_words_.clear();
message_dict_.clear();
}
private:
const GlobalDictionary& global_dict_;
// Per message dictionary
std::vector<std::string> message_words_;
std::unordered_map<std::string, int> message_dict_;
};
::istio::mixer::v1::StringMap CreateStringMap(
const Attributes_StringMap& raw_map, MessageDictionary& dict) {
::istio::mixer::v1::StringMap compressed_map;
auto* map_pb = compressed_map.mutable_entries();
for (const auto& it : raw_map.entries()) {
(*map_pb)[dict.GetIndex(it.first)] = dict.GetIndex(it.second);
}
return compressed_map;
}
void CompressByDict(const Attributes& attributes, MessageDictionary& dict,
CompressedAttributes* pb) {
// Fill attributes.
for (const auto& it : attributes.attributes()) {
const std::string& name = it.first;
const Attributes_AttributeValue& value = it.second;
int index = dict.GetIndex(name);
// Fill the attribute to proper map.
switch (value.value_case()) {
case Attributes_AttributeValue::kStringValue:
(*pb->mutable_strings())[index] = dict.GetIndex(value.string_value());
break;
case Attributes_AttributeValue::kBytesValue:
(*pb->mutable_bytes())[index] = value.bytes_value();
break;
case Attributes_AttributeValue::kInt64Value:
(*pb->mutable_int64s())[index] = value.int64_value();
break;
case Attributes_AttributeValue::kDoubleValue:
(*pb->mutable_doubles())[index] = value.double_value();
break;
case Attributes_AttributeValue::kBoolValue:
(*pb->mutable_bools())[index] = value.bool_value();
break;
case Attributes_AttributeValue::kTimestampValue:
(*pb->mutable_timestamps())[index] = value.timestamp_value();
break;
case Attributes_AttributeValue::kDurationValue:
(*pb->mutable_durations())[index] = value.duration_value();
break;
case Attributes_AttributeValue::kStringMapValue:
(*pb->mutable_string_maps())[index] =
CreateStringMap(value.string_map_value(), dict);
break;
case Attributes_AttributeValue::VALUE_NOT_SET:
break;
}
}
}
class BatchCompressorImpl : public BatchCompressor {
public:
BatchCompressorImpl(const GlobalDictionary& global_dict)
: global_dict_(global_dict), dict_(global_dict) {
AllocReportProtobuf();
}
void Add(const Attributes& attributes) override {
CompressByDict(attributes, dict_, report_->add_attributes());
}
int size() const override { return report_->attributes_size(); }
const ::istio::mixer::v1::ReportRequest& Finish() override {
for (const std::string& word : dict_.GetWords()) {
report_->add_default_words(word);
}
report_->set_global_word_count(global_dict_.size());
return *report_;
}
void Clear() override {
dict_.Clear();
AllocReportProtobuf();
}
private:
void AllocReportProtobuf() {
arena_.reset(new google::protobuf::Arena);
report_ = google::protobuf::Arena::CreateMessage<
::istio::mixer::v1::ReportRequest>(arena_.get());
}
const GlobalDictionary& global_dict_;
MessageDictionary dict_;
// protobuf arena
std::unique_ptr<google::protobuf::Arena> arena_;
::istio::mixer::v1::ReportRequest* report_;
};
} // namespace
GlobalDictionary::GlobalDictionary() {
const std::vector<std::string>& global_words = GetGlobalWords();
for (unsigned int i = 0; i < global_words.size(); i++) {
global_dict_[global_words[i]] = i;
}
top_index_ = global_words.size();
}
// Lookup the index, return true if found.
bool GlobalDictionary::GetIndex(const std::string name, int* index) const {
const auto& it = global_dict_.find(name);
if (it != global_dict_.end() && it->second < top_index_) {
// Return global dictionary index.
*index = it->second;
return true;
}
return false;
}
void GlobalDictionary::ShrinkToBase() {
if (top_index_ > kGlobalDictionaryBaseSize) {
top_index_ = kGlobalDictionaryBaseSize;
GOOGLE_LOG(INFO) << "Shrink global dictionary " << top_index_
<< " to base.";
}
}
void AttributeCompressor::Compress(
const Attributes& attributes,
::istio::mixer::v1::CompressedAttributes* pb) const {
MessageDictionary dict(global_dict_);
CompressByDict(attributes, dict, pb);
for (const std::string& word : dict.GetWords()) {
pb->add_words(word);
}
}
std::unique_ptr<BatchCompressor> AttributeCompressor::CreateBatchCompressor()
const {
return std::unique_ptr<BatchCompressor>(
new BatchCompressorImpl(global_dict_));
}
} // namespace mixerclient
} // namespace istio
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008 Barracuda Networks, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "gstthread.h"
#include <QStringList>
#include <QDir>
#include <QLibrary>
#include <QCoreApplication>
#include <QMutex>
#include <QWaitCondition>
#include <gst/gst.h>
#include "gstcustomelements/gstcustomelements.h"
#include "gstelements/static/gstelements.h"
namespace PsiMedia {
//----------------------------------------------------------------------------
// GstSession
//----------------------------------------------------------------------------
// converts Qt-ified commandline args back to C style
class CArgs
{
public:
int argc;
char **argv;
CArgs()
{
argc = 0;
argv = 0;
}
~CArgs()
{
if(count > 0)
{
for(int n = 0; n < count; ++n)
free(data[n]);
free(argv);
free(data);
}
}
void set(const QStringList &args)
{
count = args.count();
if(count == 0)
{
data = 0;
argc = 0;
argv = 0;
}
else
{
data = (char **)malloc(sizeof(char **) * count);
argv = (char **)malloc(sizeof(char **) * count);
for(int n = 0; n < count; ++n)
{
QByteArray cs = args[n].toLocal8Bit();
data[n] = (char *)qstrdup(cs.data());
argv[n] = data[n];
}
argc = count;
}
}
private:
int count;
char **data;
};
static void loadPlugins(const QString &pluginPath, bool print = false)
{
if(print)
printf("Loading plugins in [%s]\n", qPrintable(pluginPath));
QDir dir(pluginPath);
QStringList entryList = dir.entryList(QDir::Files);
foreach(QString entry, entryList)
{
if(!QLibrary::isLibrary(entry))
continue;
QString filePath = dir.filePath(entry);
GError *err = 0;
GstPlugin *plugin = gst_plugin_load_file(
filePath.toUtf8().data(), &err);
if(!plugin)
{
if(print)
{
printf("**FAIL**: %s: %s\n", qPrintable(entry),
err->message);
}
g_error_free(err);
continue;
}
if(print)
{
printf(" OK : %s name=[%s]\n", qPrintable(entry),
gst_plugin_get_name(plugin));
}
gst_object_unref(plugin);
}
if(print)
printf("\n");
}
static int compare_gst_version(int a1, int a2, int a3, int b1, int b2, int b3)
{
if(a1 > b1)
return 1;
else if(a1 < b1)
return -1;
if(a2 > b2)
return 1;
else if(a2 < b2)
return -1;
if(a3 > b3)
return 1;
else if(a3 < b3)
return -1;
return 0;
}
class GstSession
{
public:
CArgs args;
QString version;
bool success;
GstSession(const QString &pluginPath = QString())
{
args.set(QCoreApplication::instance()->arguments());
// make sure glib threads are available
if(!g_thread_supported())
g_thread_init(NULL);
// you can also use NULLs here if you don't want to pass args
GError *error;
if(!gst_init_check(&args.argc, &args.argv, &error))
{
success = false;
return;
}
guint major, minor, micro, nano;
gst_version(&major, &minor, µ, &nano);
QString nano_str;
if(nano == 1)
nano_str = " (CVS)";
else if(nano == 2)
nano_str = " (Prerelease)";
version.sprintf("%d.%d.%d%s", major, minor, micro,
!nano_str.isEmpty() ? qPrintable(nano_str) : "");
int need_maj = 0;
int need_min = 10;
int need_mic = 22;
if(compare_gst_version(major, minor, micro, need_maj, need_min, need_mic) < 0)
{
printf("Need GStreamer version %d.%d.%d\n", need_maj, need_min, need_mic);
success = false;
return;
}
// manually load plugins?
if(!pluginPath.isEmpty())
loadPlugins(pluginPath);
gstcustomelements_register();
gstelements_register();
QStringList reqelem = QStringList()
<< "speexenc" << "speexdec"
<< "vorbisenc" << "vorbisdec"
<< "theoraenc" << "theoradec"
<< "rtpspeexpay" << "rtpspeexdepay"
<< "rtpvorbispay" << "rtpvorbisdepay"
<< "rtptheorapay" << "rtptheoradepay"
<< "filesrc"
<< "decodebin"
<< "jpegdec"
<< "oggmux" << "oggdemux"
<< "audioconvert"
<< "audioresample"
<< "volume"
<< "level"
<< "ffmpegcolorspace"
<< "videorate"
<< "videomaxrate"
<< "videoscale"
<< "gstrtpjitterbuffer"
<< "liveadder";
#if defined(Q_OS_MAC)
reqelem
<< "osxaudiosrc" << "osxaudiosink"
<< "osxvideosrc";
#elif defined(Q_OS_LINUX)
reqelem
<< "alsasrc" << "alsasink"
<< "v4lsrc"
<< "v4l2src";
#elif defined(Q_OS_UNIX)
reqelem
<< "osssrc" << "osssink";
#elif defined(Q_OS_WIN)
reqelem
<< "directsoundsrc" << "directsoundsink"
<< "ksvideosrc";
#endif
foreach(const QString &name, reqelem)
{
GstElement *e = gst_element_factory_make(name.toLatin1().data(), NULL);
if(!e)
{
printf("Unable to load element '%s'.\n", qPrintable(name));
success = false;
return;
}
g_object_unref(G_OBJECT(e));
}
success = true;
}
~GstSession()
{
// nothing i guess. docs say to not bother with gst_deinit
//gst_deinit();
}
};
//----------------------------------------------------------------------------
// GstThread
//----------------------------------------------------------------------------
class GstThread::Private
{
public:
QString pluginPath;
GstSession *gstSession;
bool success;
GMainContext *mainContext;
GMainLoop *mainLoop;
QMutex m;
QWaitCondition w;
Private() :
mainContext(0),
mainLoop(0)
{
}
static gboolean cb_loop_started(gpointer data)
{
return ((Private *)data)->loop_started();
}
gboolean loop_started()
{
w.wakeOne();
m.unlock();
return FALSE;
}
};
GstThread::GstThread(QObject *parent) :
QThread(parent)
{
d = new Private;
}
GstThread::~GstThread()
{
stop();
delete d;
}
bool GstThread::start(const QString &pluginPath)
{
QMutexLocker locker(&d->m);
d->pluginPath = pluginPath;
QThread::start();
d->w.wait(&d->m);
return d->success;
}
void GstThread::stop()
{
QMutexLocker locker(&d->m);
if(d->mainLoop)
{
// thread-safe ?
g_main_loop_quit(d->mainLoop);
d->w.wait(&d->m);
}
wait();
}
QString GstThread::gstVersion() const
{
QMutexLocker locker(&d->m);
return d->gstSession->version;
}
GMainContext *GstThread::mainContext()
{
QMutexLocker locker(&d->m);
return d->mainContext;
}
void GstThread::run()
{
//printf("GStreamer thread started\n");
// this will be unlocked as soon as the mainloop runs
d->m.lock();
d->gstSession = new GstSession(d->pluginPath);
// report error
if(!d->gstSession->success)
{
d->success = false;
delete d->gstSession;
d->gstSession = 0;
d->w.wakeOne();
d->m.unlock();
//printf("GStreamer thread completed (error)\n");
return;
}
d->success = true;
//printf("Using GStreamer version %s\n", qPrintable(d->gstSession->version));
d->mainContext = g_main_context_new();
d->mainLoop = g_main_loop_new(d->mainContext, FALSE);
// deferred call to loop_started()
GSource *timer = g_timeout_source_new(0);
g_source_attach(timer, d->mainContext);
g_source_set_callback(timer, GstThread::Private::cb_loop_started, d, NULL);
// kick off the event loop
g_main_loop_run(d->mainLoop);
QMutexLocker locker(&d->m);
g_main_loop_unref(d->mainLoop);
d->mainLoop = 0;
g_main_context_unref(d->mainContext);
d->mainContext = 0;
delete d->gstSession;
d->gstSession = 0;
d->w.wakeOne();
//printf("GStreamer thread completed\n");
}
}
<commit_msg>unset GST_PLUGIN_PATH from the environment if manual plugin loading is used<commit_after>/*
* Copyright (C) 2008 Barracuda Networks, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "gstthread.h"
#include <QStringList>
#include <QDir>
#include <QLibrary>
#include <QCoreApplication>
#include <QMutex>
#include <QWaitCondition>
#include <gst/gst.h>
#include "gstcustomelements/gstcustomelements.h"
#include "gstelements/static/gstelements.h"
namespace PsiMedia {
//----------------------------------------------------------------------------
// GstSession
//----------------------------------------------------------------------------
// converts Qt-ified commandline args back to C style
class CArgs
{
public:
int argc;
char **argv;
CArgs()
{
argc = 0;
argv = 0;
}
~CArgs()
{
if(count > 0)
{
for(int n = 0; n < count; ++n)
free(data[n]);
free(argv);
free(data);
}
}
void set(const QStringList &args)
{
count = args.count();
if(count == 0)
{
data = 0;
argc = 0;
argv = 0;
}
else
{
data = (char **)malloc(sizeof(char **) * count);
argv = (char **)malloc(sizeof(char **) * count);
for(int n = 0; n < count; ++n)
{
QByteArray cs = args[n].toLocal8Bit();
data[n] = (char *)qstrdup(cs.data());
argv[n] = data[n];
}
argc = count;
}
}
private:
int count;
char **data;
};
static void loadPlugins(const QString &pluginPath, bool print = false)
{
if(print)
printf("Loading plugins in [%s]\n", qPrintable(pluginPath));
QDir dir(pluginPath);
QStringList entryList = dir.entryList(QDir::Files);
foreach(QString entry, entryList)
{
if(!QLibrary::isLibrary(entry))
continue;
QString filePath = dir.filePath(entry);
GError *err = 0;
GstPlugin *plugin = gst_plugin_load_file(
filePath.toUtf8().data(), &err);
if(!plugin)
{
if(print)
{
printf("**FAIL**: %s: %s\n", qPrintable(entry),
err->message);
}
g_error_free(err);
continue;
}
if(print)
{
printf(" OK : %s name=[%s]\n", qPrintable(entry),
gst_plugin_get_name(plugin));
}
gst_object_unref(plugin);
}
if(print)
printf("\n");
}
static int compare_gst_version(int a1, int a2, int a3, int b1, int b2, int b3)
{
if(a1 > b1)
return 1;
else if(a1 < b1)
return -1;
if(a2 > b2)
return 1;
else if(a2 < b2)
return -1;
if(a3 > b3)
return 1;
else if(a3 < b3)
return -1;
return 0;
}
class GstSession
{
public:
CArgs args;
QString version;
bool success;
GstSession(const QString &pluginPath = QString())
{
args.set(QCoreApplication::instance()->arguments());
// make sure glib threads are available
if(!g_thread_supported())
g_thread_init(NULL);
// you can also use NULLs here if you don't want to pass args
GError *error;
if(!gst_init_check(&args.argc, &args.argv, &error))
{
success = false;
return;
}
guint major, minor, micro, nano;
gst_version(&major, &minor, µ, &nano);
QString nano_str;
if(nano == 1)
nano_str = " (CVS)";
else if(nano == 2)
nano_str = " (Prerelease)";
version.sprintf("%d.%d.%d%s", major, minor, micro,
!nano_str.isEmpty() ? qPrintable(nano_str) : "");
int need_maj = 0;
int need_min = 10;
int need_mic = 22;
if(compare_gst_version(major, minor, micro, need_maj, need_min, need_mic) < 0)
{
printf("Need GStreamer version %d.%d.%d\n", need_maj, need_min, need_mic);
success = false;
return;
}
// manually load plugins?
if(!pluginPath.isEmpty())
{
// ignore "system" plugins
qputenv("GST_PLUGIN_PATH", "");
loadPlugins(pluginPath);
}
gstcustomelements_register();
gstelements_register();
QStringList reqelem = QStringList()
<< "speexenc" << "speexdec"
<< "vorbisenc" << "vorbisdec"
<< "theoraenc" << "theoradec"
<< "rtpspeexpay" << "rtpspeexdepay"
<< "rtpvorbispay" << "rtpvorbisdepay"
<< "rtptheorapay" << "rtptheoradepay"
<< "filesrc"
<< "decodebin"
<< "jpegdec"
<< "oggmux" << "oggdemux"
<< "audioconvert"
<< "audioresample"
<< "volume"
<< "level"
<< "ffmpegcolorspace"
<< "videorate"
<< "videomaxrate"
<< "videoscale"
<< "gstrtpjitterbuffer"
<< "liveadder";
#if defined(Q_OS_MAC)
reqelem
<< "osxaudiosrc" << "osxaudiosink"
<< "osxvideosrc";
#elif defined(Q_OS_LINUX)
reqelem
<< "alsasrc" << "alsasink"
<< "v4lsrc"
<< "v4l2src";
#elif defined(Q_OS_UNIX)
reqelem
<< "osssrc" << "osssink";
#elif defined(Q_OS_WIN)
reqelem
<< "directsoundsrc" << "directsoundsink"
<< "ksvideosrc";
#endif
foreach(const QString &name, reqelem)
{
GstElement *e = gst_element_factory_make(name.toLatin1().data(), NULL);
if(!e)
{
printf("Unable to load element '%s'.\n", qPrintable(name));
success = false;
return;
}
g_object_unref(G_OBJECT(e));
}
success = true;
}
~GstSession()
{
// nothing i guess. docs say to not bother with gst_deinit
//gst_deinit();
}
};
//----------------------------------------------------------------------------
// GstThread
//----------------------------------------------------------------------------
class GstThread::Private
{
public:
QString pluginPath;
GstSession *gstSession;
bool success;
GMainContext *mainContext;
GMainLoop *mainLoop;
QMutex m;
QWaitCondition w;
Private() :
mainContext(0),
mainLoop(0)
{
}
static gboolean cb_loop_started(gpointer data)
{
return ((Private *)data)->loop_started();
}
gboolean loop_started()
{
w.wakeOne();
m.unlock();
return FALSE;
}
};
GstThread::GstThread(QObject *parent) :
QThread(parent)
{
d = new Private;
}
GstThread::~GstThread()
{
stop();
delete d;
}
bool GstThread::start(const QString &pluginPath)
{
QMutexLocker locker(&d->m);
d->pluginPath = pluginPath;
QThread::start();
d->w.wait(&d->m);
return d->success;
}
void GstThread::stop()
{
QMutexLocker locker(&d->m);
if(d->mainLoop)
{
// thread-safe ?
g_main_loop_quit(d->mainLoop);
d->w.wait(&d->m);
}
wait();
}
QString GstThread::gstVersion() const
{
QMutexLocker locker(&d->m);
return d->gstSession->version;
}
GMainContext *GstThread::mainContext()
{
QMutexLocker locker(&d->m);
return d->mainContext;
}
void GstThread::run()
{
//printf("GStreamer thread started\n");
// this will be unlocked as soon as the mainloop runs
d->m.lock();
d->gstSession = new GstSession(d->pluginPath);
// report error
if(!d->gstSession->success)
{
d->success = false;
delete d->gstSession;
d->gstSession = 0;
d->w.wakeOne();
d->m.unlock();
//printf("GStreamer thread completed (error)\n");
return;
}
d->success = true;
//printf("Using GStreamer version %s\n", qPrintable(d->gstSession->version));
d->mainContext = g_main_context_new();
d->mainLoop = g_main_loop_new(d->mainContext, FALSE);
// deferred call to loop_started()
GSource *timer = g_timeout_source_new(0);
g_source_attach(timer, d->mainContext);
g_source_set_callback(timer, GstThread::Private::cb_loop_started, d, NULL);
// kick off the event loop
g_main_loop_run(d->mainLoop);
QMutexLocker locker(&d->m);
g_main_loop_unref(d->mainLoop);
d->mainLoop = 0;
g_main_context_unref(d->mainContext);
d->mainContext = 0;
delete d->gstSession;
d->gstSession = 0;
d->w.wakeOne();
//printf("GStreamer thread completed\n");
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008 Barracuda Networks, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "gstthread.h"
#include <QCoreApplication>
#include <QDir>
#include <QIcon>
#include <QLibrary>
#include <QMutex>
#include <QQueue>
#include <QStringList>
#include <QWaitCondition>
#include <gst/gst.h>
namespace PsiMedia {
//----------------------------------------------------------------------------
// GstSession
//----------------------------------------------------------------------------
// converts Qt-ified commandline args back to C style
class CArgs {
public:
int argc;
char **argv;
CArgs()
{
argc = 0;
argv = nullptr;
count = 0;
data = nullptr;
}
~CArgs()
{
if (count > 0) {
for (int n = 0; n < count; ++n)
delete[] data[n];
free(argv);
free(data);
}
}
void set(const QStringList &args)
{
count = args.count();
if (count == 0) {
data = nullptr;
argc = 0;
argv = nullptr;
} else {
data = static_cast<char **>(malloc(sizeof(char *) * quintptr(count)));
argv = static_cast<char **>(malloc(sizeof(char *) * quintptr(count)));
for (int n = 0; n < count; ++n) {
QByteArray cs = args[n].toLocal8Bit();
data[n] = static_cast<char *>(qstrdup(cs.data()));
argv[n] = data[n];
}
argc = count;
}
}
private:
int count;
char **data;
};
/*static void loadPlugins(const QString &pluginPath, bool print = false)
{
if (print)
qDebug("Loading plugins in [%s]", qPrintable(pluginPath));
QDir dir(pluginPath);
QStringList entryList = dir.entryList(QDir::Files);
foreach (QString entry, entryList) {
if (!QLibrary::isLibrary(entry))
continue;
QString filePath = dir.filePath(entry);
GError * err = nullptr;
GstPlugin *plugin = gst_plugin_load_file(filePath.toUtf8().data(), &err);
if (!plugin) {
if (print) {
qDebug("**FAIL**: %s: %s", qPrintable(entry), err->message);
}
g_error_free(err);
continue;
}
if (print) {
qDebug(" OK : %s name=[%s]", qPrintable(entry), gst_plugin_get_name(plugin));
}
gst_object_unref(plugin);
}
if (print)
qDebug("");
}*/
static int compare_gst_version(uint a1, uint a2, uint a3, uint b1, uint b2, uint b3)
{
if (a1 > b1)
return 1;
else if (a1 < b1)
return -1;
if (a2 > b2)
return 1;
else if (a2 < b2)
return -1;
if (a3 > b3)
return 1;
else if (a3 < b3)
return -1;
return 0;
}
class GstSession {
public:
CArgs args;
QString version;
bool success;
explicit GstSession(const QString &pluginPath = QString())
{
args.set(QCoreApplication::instance()->arguments());
// ignore "system" plugins
if (!qEnvironmentVariableIsSet("GST_PLUGIN_SYSTEM_PATH") && !pluginPath.isEmpty()) {
qputenv("GST_PLUGIN_SYSTEM_PATH", pluginPath.toLocal8Bit());
}
// you can also use NULLs here if you don't want to pass args
GError *error;
if (!gst_init_check(&args.argc, &args.argv, &error)) {
success = false;
return;
}
guint major, minor, micro, nano;
gst_version(&major, &minor, µ, &nano);
QString nano_str;
if (nano == 1)
nano_str = " (CVS)";
else if (nano == 2)
nano_str = " (Prerelease)";
version = QString("%1.%2.%3%4")
.arg(major)
.arg(minor)
.arg(micro)
.arg(!nano_str.isEmpty() ? qPrintable(nano_str) : "");
uint need_maj = 1;
uint need_min = 4;
uint need_mic = 0;
if (compare_gst_version(major, minor, micro, need_maj, need_min, need_mic) < 0) {
qDebug("Need GStreamer version %d.%d.%d", need_maj, need_min, need_mic);
success = false;
return;
}
// manually load plugins?
// if(!pluginPath.isEmpty())
// loadPlugins(pluginPath);
// gstcustomelements_register();
// gstelements_register();
QStringList reqelem
= { "opusenc", "opusdec", "vorbisenc", "vorbisdec", "theoraenc", "theoradec",
"rtpopuspay", "rtpopusdepay", "rtpvorbispay", "rtpvorbisdepay", "rtptheorapay", "rtptheoradepay",
"filesrc", "decodebin", "jpegdec", "oggmux", "oggdemux", "audioconvert",
"audioresample", "volume", "level", "videoconvert", "videorate", "videoscale",
"rtpjitterbuffer", "audiomixer", "appsink" };
#ifndef Q_OS_WIN
reqelem << "webrtcechoprobe";
#endif
#if defined(Q_OS_MAC)
reqelem << "osxaudiosrc"
<< "osxaudiosink";
#ifdef HAVE_OSXVIDIO
reqelem << "osxvideosrc";
#endif
#elif defined(Q_OS_LINUX)
reqelem << "v4l2src";
#elif defined(Q_OS_UNIX)
reqelem << "osssrc"
<< "osssink";
#elif defined(Q_OS_WIN)
reqelem << "directsoundsrc"
<< "directsoundsink"
<< "ksvideosrc";
#endif
foreach (const QString &name, reqelem) {
GstElement *e = gst_element_factory_make(name.toLatin1().data(), nullptr);
if (!e) {
qDebug("Unable to load element '%s'.", qPrintable(name));
success = false;
return;
}
g_object_unref(G_OBJECT(e));
}
success = true;
}
~GstSession()
{
// docs say to not bother with gst_deinit, but we'll do it
// anyway in case there's an issue with plugin unloading
// update: there could be other gstreamer users, so we
// probably shouldn't call this. also, it appears to crash
// on mac for at least one user.. maybe the function is
// not very well tested.
// gst_deinit();
}
};
//----------------------------------------------------------------------------
// GstMainLoop
//----------------------------------------------------------------------------
class GstMainLoop::Private {
public:
typedef struct {
GSource parent;
GstMainLoop::Private *d = nullptr;
} BridgeQueueSource;
GstMainLoop * q = nullptr;
QString pluginPath;
GstSession * gstSession = nullptr;
bool success = false;
GMainContext * mainContext = nullptr;
GMainLoop * mainLoop = nullptr;
QMutex queueMutex;
QMutex stateMutex;
QWaitCondition waitCond;
BridgeQueueSource * bridgeSource = nullptr;
guint bridgeId = 0;
QQueue<QPair<GstMainLoop::ContextCallback, void *>> bridgeQueue;
Private(GstMainLoop *q) : q(q) { }
static gboolean cb_loop_started(gpointer data) { return static_cast<Private *>(data)->loop_started(); }
gboolean loop_started()
{
success = true;
emit q->started();
return FALSE;
}
static gboolean bridge_callback(gpointer data)
{
auto d = static_cast<GstMainLoop::Private *>(data);
while (!d->bridgeQueue.empty()) {
d->queueMutex.lock();
QPair<GstMainLoop::ContextCallback, void *> p;
bool exist = !d->bridgeQueue.empty();
if (exist)
p = d->bridgeQueue.dequeue();
d->queueMutex.unlock();
if (exist)
p.first(p.second);
}
return d->mainLoop == nullptr ? FALSE : TRUE;
}
static gboolean bridge_prepare(GSource *source, gint *timeout_)
{
*timeout_ = -1;
auto d = reinterpret_cast<Private::BridgeQueueSource *>(source)->d;
QMutexLocker locker(&d->queueMutex);
return !d->bridgeQueue.empty() ? TRUE : FALSE;
}
static gboolean bridge_check(GSource *source)
{
auto d = reinterpret_cast<Private::BridgeQueueSource *>(source)->d;
QMutexLocker locker(&d->queueMutex);
return !d->bridgeQueue.empty() ? TRUE : FALSE;
}
static gboolean bridge_dispatch(GSource *source, GSourceFunc callback, gpointer user_data)
{
Q_UNUSED(source)
if (callback(user_data))
return TRUE;
else
return FALSE;
}
};
GstMainLoop::GstMainLoop(const QString &resPath) : QObject()
{
d = new Private(this);
d->pluginPath = resPath;
// create a variable of type GSourceFuncs
static GSourceFuncs bridgeFuncs
= { Private::bridge_prepare, Private::bridge_check, Private::bridge_dispatch, nullptr, nullptr, nullptr };
// create a new source
d->bridgeSource = reinterpret_cast<Private::BridgeQueueSource *>(
g_source_new(&bridgeFuncs, sizeof(Private::BridgeQueueSource)));
d->bridgeSource->d = d;
// HACK: if gstreamer initializes before certain Qt internal
// initialization occurs, then the app becomes unstable.
// I don't know what exactly needs to happen, or where the
// bug is, but if I fiddle with the default QStyle before
// initializing gstreamer, then this seems to solve it.
// it could be a bug in QCleanlooksStyle or QGtkStyle, which
// may conflict with separate Gtk initialization that may
// occur through gstreamer plugin loading.
//{
// QIcon icon = QApplication::style()->standardIcon(QStyle::SP_MessageBoxCritical, 0, 0);
//}
}
GstMainLoop::~GstMainLoop()
{
stop();
g_source_unref(&d->bridgeSource->parent);
delete d;
}
void GstMainLoop::stop()
{
bool stopped = execInContext(
[this](void *) {
g_main_loop_quit(d->mainLoop);
qDebug("g_main_loop_quit");
d->waitCond.wakeOne();
},
this);
if (stopped) {
d->stateMutex.lock();
d->waitCond.wait(&d->stateMutex);
d->stateMutex.unlock();
}
qDebug("GstMainLoop::stop() finished");
}
QString GstMainLoop::gstVersion() const { return d->gstSession->version; }
GMainContext *GstMainLoop::mainContext() { return d->mainContext; }
bool GstMainLoop::isInitialized() const { return d->success; }
bool GstMainLoop::execInContext(const ContextCallback &cb, void *userData)
{
if (d->mainLoop) {
QMutexLocker(&d->queueMutex);
d->bridgeQueue.enqueue({ cb, userData });
g_main_context_wakeup(d->mainContext);
return true;
}
return false;
}
bool GstMainLoop::start()
{
qDebug("GStreamer thread started");
// this will be unlocked as soon as the mainloop runs
// d->stateMutex.lock();
d->gstSession = new GstSession(d->pluginPath);
// report error
if (!d->gstSession->success) {
d->success = false;
delete d->gstSession;
d->gstSession = nullptr;
qWarning("GStreamer thread completed (error)");
// d->stateMutex.unlock();
return false;
}
// qDebug("Using GStreamer version %s", qPrintable(d->gstSession->version));
d->mainContext = g_main_context_ref_thread_default();
d->mainLoop = g_main_loop_new(d->mainContext, FALSE);
// attach bridge source to context
d->bridgeId = g_source_attach(&d->bridgeSource->parent, d->mainContext);
g_source_set_callback(&d->bridgeSource->parent, GstMainLoop::Private::bridge_callback, d, nullptr);
// deferred call to loop_started()
GSource *timer = g_timeout_source_new(0);
g_source_attach(timer, d->mainContext);
g_source_set_callback(timer, GstMainLoop::Private::cb_loop_started, d, nullptr);
// d->stateMutex.unlock();
qDebug("kick off glib event loop");
// kick off the event loop
g_main_loop_run(d->mainLoop);
g_source_destroy(timer);
g_source_unref(timer);
g_main_loop_unref(d->mainLoop);
d->mainLoop = nullptr;
g_main_context_unref(d->mainContext);
d->mainContext = nullptr;
delete d->gstSession;
d->gstSession = nullptr;
return true;
}
}
<commit_msg>Avoid double GMainLoop stop<commit_after>/*
* Copyright (C) 2008 Barracuda Networks, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "gstthread.h"
#include <QCoreApplication>
#include <QDir>
#include <QIcon>
#include <QLibrary>
#include <QMutex>
#include <QQueue>
#include <QStringList>
#include <QWaitCondition>
#include <gst/gst.h>
#include <atomic>
namespace PsiMedia {
//----------------------------------------------------------------------------
// GstSession
//----------------------------------------------------------------------------
// converts Qt-ified commandline args back to C style
class CArgs {
public:
int argc;
char **argv;
CArgs()
{
argc = 0;
argv = nullptr;
count = 0;
data = nullptr;
}
~CArgs()
{
if (count > 0) {
for (int n = 0; n < count; ++n)
delete[] data[n];
free(argv);
free(data);
}
}
void set(const QStringList &args)
{
count = args.count();
if (count == 0) {
data = nullptr;
argc = 0;
argv = nullptr;
} else {
data = static_cast<char **>(malloc(sizeof(char *) * quintptr(count)));
argv = static_cast<char **>(malloc(sizeof(char *) * quintptr(count)));
for (int n = 0; n < count; ++n) {
QByteArray cs = args[n].toLocal8Bit();
data[n] = static_cast<char *>(qstrdup(cs.data()));
argv[n] = data[n];
}
argc = count;
}
}
private:
int count;
char **data;
};
/*static void loadPlugins(const QString &pluginPath, bool print = false)
{
if (print)
qDebug("Loading plugins in [%s]", qPrintable(pluginPath));
QDir dir(pluginPath);
QStringList entryList = dir.entryList(QDir::Files);
foreach (QString entry, entryList) {
if (!QLibrary::isLibrary(entry))
continue;
QString filePath = dir.filePath(entry);
GError * err = nullptr;
GstPlugin *plugin = gst_plugin_load_file(filePath.toUtf8().data(), &err);
if (!plugin) {
if (print) {
qDebug("**FAIL**: %s: %s", qPrintable(entry), err->message);
}
g_error_free(err);
continue;
}
if (print) {
qDebug(" OK : %s name=[%s]", qPrintable(entry), gst_plugin_get_name(plugin));
}
gst_object_unref(plugin);
}
if (print)
qDebug("");
}*/
static int compare_gst_version(uint a1, uint a2, uint a3, uint b1, uint b2, uint b3)
{
if (a1 > b1)
return 1;
else if (a1 < b1)
return -1;
if (a2 > b2)
return 1;
else if (a2 < b2)
return -1;
if (a3 > b3)
return 1;
else if (a3 < b3)
return -1;
return 0;
}
class GstSession {
public:
CArgs args;
QString version;
bool success;
explicit GstSession(const QString &pluginPath = QString())
{
args.set(QCoreApplication::instance()->arguments());
// ignore "system" plugins
if (!qEnvironmentVariableIsSet("GST_PLUGIN_SYSTEM_PATH") && !pluginPath.isEmpty()) {
qputenv("GST_PLUGIN_SYSTEM_PATH", pluginPath.toLocal8Bit());
}
// you can also use NULLs here if you don't want to pass args
GError *error;
if (!gst_init_check(&args.argc, &args.argv, &error)) {
success = false;
return;
}
guint major, minor, micro, nano;
gst_version(&major, &minor, µ, &nano);
QString nano_str;
if (nano == 1)
nano_str = " (CVS)";
else if (nano == 2)
nano_str = " (Prerelease)";
version = QString("%1.%2.%3%4")
.arg(major)
.arg(minor)
.arg(micro)
.arg(!nano_str.isEmpty() ? qPrintable(nano_str) : "");
uint need_maj = 1;
uint need_min = 4;
uint need_mic = 0;
if (compare_gst_version(major, minor, micro, need_maj, need_min, need_mic) < 0) {
qDebug("Need GStreamer version %d.%d.%d", need_maj, need_min, need_mic);
success = false;
return;
}
// manually load plugins?
// if(!pluginPath.isEmpty())
// loadPlugins(pluginPath);
// gstcustomelements_register();
// gstelements_register();
QStringList reqelem
= { "opusenc", "opusdec", "vorbisenc", "vorbisdec", "theoraenc", "theoradec",
"rtpopuspay", "rtpopusdepay", "rtpvorbispay", "rtpvorbisdepay", "rtptheorapay", "rtptheoradepay",
"filesrc", "decodebin", "jpegdec", "oggmux", "oggdemux", "audioconvert",
"audioresample", "volume", "level", "videoconvert", "videorate", "videoscale",
"rtpjitterbuffer", "audiomixer", "appsink" };
#ifndef Q_OS_WIN
reqelem << "webrtcechoprobe";
#endif
#if defined(Q_OS_MAC)
reqelem << "osxaudiosrc"
<< "osxaudiosink";
#ifdef HAVE_OSXVIDIO
reqelem << "osxvideosrc";
#endif
#elif defined(Q_OS_LINUX)
reqelem << "v4l2src";
#elif defined(Q_OS_UNIX)
reqelem << "osssrc"
<< "osssink";
#elif defined(Q_OS_WIN)
reqelem << "directsoundsrc"
<< "directsoundsink"
<< "ksvideosrc";
#endif
foreach (const QString &name, reqelem) {
GstElement *e = gst_element_factory_make(name.toLatin1().data(), nullptr);
if (!e) {
qDebug("Unable to load element '%s'.", qPrintable(name));
success = false;
return;
}
g_object_unref(G_OBJECT(e));
}
success = true;
}
~GstSession()
{
// docs say to not bother with gst_deinit, but we'll do it
// anyway in case there's an issue with plugin unloading
// update: there could be other gstreamer users, so we
// probably shouldn't call this. also, it appears to crash
// on mac for at least one user.. maybe the function is
// not very well tested.
// gst_deinit();
}
};
//----------------------------------------------------------------------------
// GstMainLoop
//----------------------------------------------------------------------------
class GstMainLoop::Private {
public:
typedef struct {
GSource parent;
GstMainLoop::Private *d = nullptr;
} BridgeQueueSource;
GstMainLoop * q = nullptr;
QString pluginPath;
GstSession * gstSession = nullptr;
std::atomic_bool success;
bool stopping;
GMainContext * mainContext = nullptr;
GMainLoop * mainLoop = nullptr;
QMutex queueMutex;
QMutex stateMutex;
QWaitCondition waitCond;
BridgeQueueSource * bridgeSource = nullptr;
guint bridgeId = 0;
QQueue<QPair<GstMainLoop::ContextCallback, void *>> bridgeQueue;
Private(GstMainLoop *q) : q(q), success(false), stopping(false) { }
static gboolean cb_loop_started(gpointer data) { return static_cast<Private *>(data)->loop_started(); }
gboolean loop_started()
{
success = true;
emit q->started();
return FALSE;
}
static gboolean bridge_callback(gpointer data)
{
auto d = static_cast<GstMainLoop::Private *>(data);
while (!d->bridgeQueue.empty()) {
d->queueMutex.lock();
QPair<GstMainLoop::ContextCallback, void *> p;
bool exist = !d->bridgeQueue.empty();
if (exist)
p = d->bridgeQueue.dequeue();
d->queueMutex.unlock();
if (exist)
p.first(p.second);
}
return d->mainLoop == nullptr ? FALSE : TRUE;
}
static gboolean bridge_prepare(GSource *source, gint *timeout_)
{
*timeout_ = -1;
auto d = reinterpret_cast<Private::BridgeQueueSource *>(source)->d;
QMutexLocker locker(&d->queueMutex);
return !d->bridgeQueue.empty() ? TRUE : FALSE;
}
static gboolean bridge_check(GSource *source)
{
auto d = reinterpret_cast<Private::BridgeQueueSource *>(source)->d;
QMutexLocker locker(&d->queueMutex);
return !d->bridgeQueue.empty() ? TRUE : FALSE;
}
static gboolean bridge_dispatch(GSource *source, GSourceFunc callback, gpointer user_data)
{
Q_UNUSED(source)
if (callback(user_data))
return TRUE;
else
return FALSE;
}
};
GstMainLoop::GstMainLoop(const QString &resPath) : QObject()
{
d = new Private(this);
d->pluginPath = resPath;
// create a variable of type GSourceFuncs
static GSourceFuncs bridgeFuncs
= { Private::bridge_prepare, Private::bridge_check, Private::bridge_dispatch, nullptr, nullptr, nullptr };
// create a new source
d->bridgeSource = reinterpret_cast<Private::BridgeQueueSource *>(
g_source_new(&bridgeFuncs, sizeof(Private::BridgeQueueSource)));
d->bridgeSource->d = d;
// HACK: if gstreamer initializes before certain Qt internal
// initialization occurs, then the app becomes unstable.
// I don't know what exactly needs to happen, or where the
// bug is, but if I fiddle with the default QStyle before
// initializing gstreamer, then this seems to solve it.
// it could be a bug in QCleanlooksStyle or QGtkStyle, which
// may conflict with separate Gtk initialization that may
// occur through gstreamer plugin loading.
//{
// QIcon icon = QApplication::style()->standardIcon(QStyle::SP_MessageBoxCritical, 0, 0);
//}
}
GstMainLoop::~GstMainLoop()
{
stop();
g_source_unref(&d->bridgeSource->parent);
delete d;
}
void GstMainLoop::stop()
{
if (d->stopping || !d->success)
return;
d->stopping = true;
bool stopped = execInContext(
[this](void *) {
g_main_loop_quit(d->mainLoop);
qDebug("g_main_loop_quit");
d->waitCond.wakeOne();
},
this);
if (stopped) {
d->stateMutex.lock();
d->waitCond.wait(&d->stateMutex);
d->stateMutex.unlock();
d->success = false;
}
d->stopping = false;
qDebug("GstMainLoop::stop() finished");
}
QString GstMainLoop::gstVersion() const { return d->gstSession->version; }
GMainContext *GstMainLoop::mainContext() { return d->mainContext; }
bool GstMainLoop::isInitialized() const { return d->success; }
bool GstMainLoop::execInContext(const ContextCallback &cb, void *userData)
{
if (d->mainLoop) {
QMutexLocker(&d->queueMutex);
d->bridgeQueue.enqueue({ cb, userData });
g_main_context_wakeup(d->mainContext);
return true;
}
return false;
}
bool GstMainLoop::start()
{
qDebug("GStreamer thread started");
// this will be unlocked as soon as the mainloop runs
// d->stateMutex.lock();
d->gstSession = new GstSession(d->pluginPath);
// report error
if (!d->gstSession->success) {
d->success = false;
delete d->gstSession;
d->gstSession = nullptr;
qWarning("GStreamer thread completed (error)");
// d->stateMutex.unlock();
return false;
}
// qDebug("Using GStreamer version %s", qPrintable(d->gstSession->version));
d->mainContext = g_main_context_ref_thread_default();
d->mainLoop = g_main_loop_new(d->mainContext, FALSE);
// attach bridge source to context
d->bridgeId = g_source_attach(&d->bridgeSource->parent, d->mainContext);
g_source_set_callback(&d->bridgeSource->parent, GstMainLoop::Private::bridge_callback, d, nullptr);
// deferred call to loop_started()
GSource *timer = g_timeout_source_new(0);
g_source_attach(timer, d->mainContext);
g_source_set_callback(timer, GstMainLoop::Private::cb_loop_started, d, nullptr);
// d->stateMutex.unlock();
qDebug("kick off glib event loop");
// kick off the event loop
g_main_loop_run(d->mainLoop);
g_source_destroy(timer);
g_source_unref(timer);
g_main_loop_unref(d->mainLoop);
d->mainLoop = nullptr;
g_main_context_unref(d->mainContext);
d->mainContext = nullptr;
delete d->gstSession;
d->gstSession = nullptr;
return true;
}
}
<|endoftext|> |
<commit_before>/* This file is part of the KDE project.
Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 2.1 or 3 of the License.
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, see <http://www.gnu.org/licenses/>.
*/
#include "videowidget.h"
#include "x11renderer.h"
#ifndef Q_WS_QWS
#include <QtGui/QPalette>
#include <QtGui/QApplication>
#include <QtGui/QPainter>
#include <X11/Xlib.h>
#include <gst/gst.h>
#include <gst/interfaces/xoverlay.h>
#include <gst/interfaces/propertyprobe.h>
#include "common.h"
#include "mediaobject.h"
#include "message.h"
QT_BEGIN_NAMESPACE
namespace Phonon
{
namespace Gstreamer
{
class OverlayWidget : public QWidget
{
public:
OverlayWidget(VideoWidget *videoWidget, X11Renderer *renderer) :
QWidget(videoWidget),
m_videoWidget(videoWidget),
m_renderer(renderer) { }
void paintEvent(QPaintEvent *) {
Phonon::State state = m_videoWidget->root() ? m_videoWidget->root()->state() : Phonon::LoadingState;
if (state == Phonon::PlayingState || state == Phonon::PausedState) {
m_renderer->windowExposed();
} else {
QPainter painter(this);
painter.fillRect(m_videoWidget->rect(), m_videoWidget->palette().background());
}
}
private:
VideoWidget *m_videoWidget;
X11Renderer *m_renderer;
};
X11Renderer::X11Renderer(VideoWidget *videoWidget)
: AbstractRenderer(videoWidget)
{
m_renderWidget = new OverlayWidget(videoWidget, this);
videoWidget->backend()->logMessage("Creating X11 overlay renderer");
QPalette palette;
palette.setColor(QPalette::Background, Qt::black);
m_videoWidget->setPalette(palette);
m_videoWidget->setAutoFillBackground(true);
m_renderWidget->setMouseTracking(true);
m_videoSink = createVideoSink();
aspectRatioChanged(videoWidget->aspectRatio());
setOverlay();
}
X11Renderer::~X11Renderer()
{
m_renderWidget->setAttribute(Qt::WA_PaintOnScreen, false);
m_renderWidget->setAttribute(Qt::WA_NoSystemBackground, false);
delete m_renderWidget;
}
GstElement* X11Renderer::createVideoSink()
{
GstElement *videoSink = gst_element_factory_make ("xvimagesink", NULL);
if (videoSink) {
// Check if the xv sink is usable
if (gst_element_set_state(videoSink, GST_STATE_READY) != GST_STATE_CHANGE_SUCCESS) {
gst_object_unref(GST_OBJECT(videoSink));
videoSink = 0;
} else {
// Note that this should not really be neccessary as these are
// default values, though under certain conditions values are retained
// even between application instances. (reproducible on 0.10.16/Gutsy)
g_object_set(G_OBJECT(videoSink), "brightness", 0, (const char*)NULL);
g_object_set(G_OBJECT(videoSink), "contrast", 0, (const char*)NULL);
g_object_set(G_OBJECT(videoSink), "hue", 0, (const char*)NULL);
g_object_set(G_OBJECT(videoSink), "saturation", 0, (const char*)NULL);
}
}
if (!videoSink)
videoSink = gst_element_factory_make ("ximagesink", NULL);
gst_object_ref (GST_OBJECT (videoSink)); //Take ownership
gst_object_sink (GST_OBJECT (videoSink));
return videoSink;
}
void X11Renderer::handleMediaNodeEvent(const MediaNodeEvent *event)
{
switch (event->type()) {
case MediaNodeEvent::SourceChanged:
setOverlay(); // We need to do this whenever the pipeline is reset
break; // otherwise the videosink will open in its own window
default:
break;
}
}
void X11Renderer::aspectRatioChanged(Phonon::VideoWidget::AspectRatio)
{
if (m_renderWidget) {
m_renderWidget->setGeometry(m_videoWidget->calculateDrawFrameRect());
}
}
void X11Renderer::scaleModeChanged(Phonon::VideoWidget::ScaleMode)
{
if (m_renderWidget) {
m_renderWidget->setGeometry(m_videoWidget->calculateDrawFrameRect());
}
}
void X11Renderer::movieSizeChanged(const QSize &movieSize)
{
if (m_renderWidget) {
m_renderWidget->setGeometry(m_videoWidget->calculateDrawFrameRect());
}
}
bool X11Renderer::eventFilter(QEvent *e)
{
if (e->type() == QEvent::Show) {
// Setting these values ensures smooth resizing since it
// will prevent the system from clearing the background
m_renderWidget->setAttribute(Qt::WA_NoSystemBackground, true);
m_renderWidget->setAttribute(Qt::WA_PaintOnScreen, true);
setOverlay();
} else if (e->type() == QEvent::Resize) {
// This is a workaround for missing background repaints
// when reducing window size
m_renderWidget->setGeometry(m_videoWidget->calculateDrawFrameRect());
windowExposed();
}
return false;
}
void X11Renderer::handlePaint(QPaintEvent *)
{
QPainter painter(m_videoWidget);
painter.fillRect(m_videoWidget->rect(), m_videoWidget->palette().background());
}
void X11Renderer::setOverlay()
{
if (m_videoSink && GST_IS_X_OVERLAY(m_videoSink)) {
WId windowId = m_renderWidget->winId();
// Even if we have created a winId at this point, other X applications
// need to be aware of it.
QApplication::syncX();
gst_x_overlay_set_xwindow_id ( GST_X_OVERLAY(m_videoSink) , windowId );
}
windowExposed();
m_overlaySet = true;
}
void X11Renderer::windowExposed()
{
QApplication::syncX();
if (m_videoSink && GST_IS_X_OVERLAY(m_videoSink))
gst_x_overlay_expose(GST_X_OVERLAY(m_videoSink));
}
}
} //namespace Phonon::Gstreamer
QT_END_NAMESPACE
#endif // Q_WS_QWS
<commit_msg>Removing some "unused variables" warnings by employing Q_UNUSED<commit_after>/* This file is part of the KDE project.
Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 2.1 or 3 of the License.
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, see <http://www.gnu.org/licenses/>.
*/
#include "videowidget.h"
#include "x11renderer.h"
#ifndef Q_WS_QWS
#include <QtGui/QPalette>
#include <QtGui/QApplication>
#include <QtGui/QPainter>
#include <X11/Xlib.h>
#include <gst/gst.h>
#include <gst/interfaces/xoverlay.h>
#include <gst/interfaces/propertyprobe.h>
#include "common.h"
#include "mediaobject.h"
#include "message.h"
QT_BEGIN_NAMESPACE
namespace Phonon
{
namespace Gstreamer
{
class OverlayWidget : public QWidget
{
public:
OverlayWidget(VideoWidget *videoWidget, X11Renderer *renderer) :
QWidget(videoWidget),
m_videoWidget(videoWidget),
m_renderer(renderer) { }
void paintEvent(QPaintEvent *) {
Phonon::State state = m_videoWidget->root() ? m_videoWidget->root()->state() : Phonon::LoadingState;
if (state == Phonon::PlayingState || state == Phonon::PausedState) {
m_renderer->windowExposed();
} else {
QPainter painter(this);
painter.fillRect(m_videoWidget->rect(), m_videoWidget->palette().background());
}
}
private:
VideoWidget *m_videoWidget;
X11Renderer *m_renderer;
};
X11Renderer::X11Renderer(VideoWidget *videoWidget)
: AbstractRenderer(videoWidget)
{
m_renderWidget = new OverlayWidget(videoWidget, this);
videoWidget->backend()->logMessage("Creating X11 overlay renderer");
QPalette palette;
palette.setColor(QPalette::Background, Qt::black);
m_videoWidget->setPalette(palette);
m_videoWidget->setAutoFillBackground(true);
m_renderWidget->setMouseTracking(true);
m_videoSink = createVideoSink();
aspectRatioChanged(videoWidget->aspectRatio());
setOverlay();
}
X11Renderer::~X11Renderer()
{
m_renderWidget->setAttribute(Qt::WA_PaintOnScreen, false);
m_renderWidget->setAttribute(Qt::WA_NoSystemBackground, false);
delete m_renderWidget;
}
GstElement* X11Renderer::createVideoSink()
{
GstElement *videoSink = gst_element_factory_make ("xvimagesink", NULL);
if (videoSink) {
// Check if the xv sink is usable
if (gst_element_set_state(videoSink, GST_STATE_READY) != GST_STATE_CHANGE_SUCCESS) {
gst_object_unref(GST_OBJECT(videoSink));
videoSink = 0;
} else {
// Note that this should not really be neccessary as these are
// default values, though under certain conditions values are retained
// even between application instances. (reproducible on 0.10.16/Gutsy)
g_object_set(G_OBJECT(videoSink), "brightness", 0, (const char*)NULL);
g_object_set(G_OBJECT(videoSink), "contrast", 0, (const char*)NULL);
g_object_set(G_OBJECT(videoSink), "hue", 0, (const char*)NULL);
g_object_set(G_OBJECT(videoSink), "saturation", 0, (const char*)NULL);
}
}
if (!videoSink)
videoSink = gst_element_factory_make ("ximagesink", NULL);
gst_object_ref (GST_OBJECT (videoSink)); //Take ownership
gst_object_sink (GST_OBJECT (videoSink));
return videoSink;
}
void X11Renderer::handleMediaNodeEvent(const MediaNodeEvent *event)
{
switch (event->type()) {
case MediaNodeEvent::SourceChanged:
setOverlay(); // We need to do this whenever the pipeline is reset
break; // otherwise the videosink will open in its own window
default:
break;
}
}
void X11Renderer::aspectRatioChanged(Phonon::VideoWidget::AspectRatio)
{
if (m_renderWidget) {
m_renderWidget->setGeometry(m_videoWidget->calculateDrawFrameRect());
}
}
void X11Renderer::scaleModeChanged(Phonon::VideoWidget::ScaleMode)
{
if (m_renderWidget) {
m_renderWidget->setGeometry(m_videoWidget->calculateDrawFrameRect());
}
}
void X11Renderer::movieSizeChanged(const QSize &movieSize)
{
Q_UNUSED(movieSize);
if (m_renderWidget) {
m_renderWidget->setGeometry(m_videoWidget->calculateDrawFrameRect());
}
}
bool X11Renderer::eventFilter(QEvent *e)
{
if (e->type() == QEvent::Show) {
// Setting these values ensures smooth resizing since it
// will prevent the system from clearing the background
m_renderWidget->setAttribute(Qt::WA_NoSystemBackground, true);
m_renderWidget->setAttribute(Qt::WA_PaintOnScreen, true);
setOverlay();
} else if (e->type() == QEvent::Resize) {
// This is a workaround for missing background repaints
// when reducing window size
m_renderWidget->setGeometry(m_videoWidget->calculateDrawFrameRect());
windowExposed();
}
return false;
}
void X11Renderer::handlePaint(QPaintEvent *)
{
QPainter painter(m_videoWidget);
painter.fillRect(m_videoWidget->rect(), m_videoWidget->palette().background());
}
void X11Renderer::setOverlay()
{
if (m_videoSink && GST_IS_X_OVERLAY(m_videoSink)) {
WId windowId = m_renderWidget->winId();
// Even if we have created a winId at this point, other X applications
// need to be aware of it.
QApplication::syncX();
gst_x_overlay_set_xwindow_id ( GST_X_OVERLAY(m_videoSink) , windowId );
}
windowExposed();
m_overlaySet = true;
}
void X11Renderer::windowExposed()
{
QApplication::syncX();
if (m_videoSink && GST_IS_X_OVERLAY(m_videoSink))
gst_x_overlay_expose(GST_X_OVERLAY(m_videoSink));
}
}
} //namespace Phonon::Gstreamer
QT_END_NAMESPACE
#endif // Q_WS_QWS
<|endoftext|> |
<commit_before>#include "chunked_response_stream.h"
const rs::httpserver::Stream::byte rs::httpserver::ChunkedResponseStream::endOfLine_[2] = { '\r', '\n' };
const rs::httpserver::Stream::byte rs::httpserver::ChunkedResponseStream::endOfBlocks[5] = { '0', '\r', '\n', '\r', '\n' };
int rs::httpserver::ChunkedResponseStream::Write(const byte* buffer, int offset, int count) {
auto blocks = count / Config::MaxResponseChunkSize;
auto overflow = count % Config::MaxResponseChunkSize;
for (int i = 0; i < blocks; i++) {
stream_.Write(&maxBlockSizeHeader_[0], 0, maxBlockSizeHeader_.size());
stream_.Write(buffer, offset, Config::MaxResponseChunkSize);
stream_.Write(endOfLine_, 0, sizeof(endOfLine_));
offset += Config::MaxResponseChunkSize;
}
if (overflow > 0) {
auto header = GetHeader(overflow);
stream_.Write(&header[0], 0, header.size());
stream_.Write(buffer, offset, overflow);
stream_.Write(endOfLine_, 0, sizeof(endOfLine_));
}
return count;
}
void rs::httpserver::ChunkedResponseStream::Flush() {
stream_.Write(endOfBlocks, 0, sizeof(endOfBlocks));
stream_.Flush();
}
std::vector<rs::httpserver::Stream::byte> rs::httpserver::ChunkedResponseStream::GetHeader(int blockSize) {
if (blockSize <= 0) {
return std::vector<Stream::byte>({'0', '\r', '\n'});
} else {
auto chars = 0;
while ((blockSize >> (4 * chars)) > 0) ++chars;
std::vector<Stream::byte> buffer(chars + 2);
for (auto i = 0; i < chars; ++i) {
auto index = chars - 1 - i;
buffer[index] = (blockSize >> (4 * i)) & 0x0f;
buffer[index] |= buffer[index] > 9 ? ('a' - 10) : '0';
}
buffer[chars] = '\r';
buffer[chars + 1] = '\n';
return buffer;
}
}<commit_msg>Correct the chunked block size calculation<commit_after>#include "chunked_response_stream.h"
const rs::httpserver::Stream::byte rs::httpserver::ChunkedResponseStream::endOfLine_[2] = { '\r', '\n' };
const rs::httpserver::Stream::byte rs::httpserver::ChunkedResponseStream::endOfBlocks[5] = { '0', '\r', '\n', '\r', '\n' };
int rs::httpserver::ChunkedResponseStream::Write(const byte* buffer, int offset, int count) {
auto blocks = count / Config::MaxResponseChunkSize;
auto overflow = count % Config::MaxResponseChunkSize;
for (int i = 0; i < blocks; i++) {
stream_.Write(&maxBlockSizeHeader_[0], 0, maxBlockSizeHeader_.size());
stream_.Write(buffer, offset, Config::MaxResponseChunkSize);
stream_.Write(endOfLine_, 0, sizeof(endOfLine_));
offset += Config::MaxResponseChunkSize;
}
if (overflow > 0) {
auto header = GetHeader(overflow);
stream_.Write(&header[0], 0, header.size());
stream_.Write(buffer, offset, overflow);
stream_.Write(endOfLine_, 0, sizeof(endOfLine_));
}
return count;
}
void rs::httpserver::ChunkedResponseStream::Flush() {
stream_.Write(endOfBlocks, 0, sizeof(endOfBlocks));
stream_.Flush();
}
std::vector<rs::httpserver::Stream::byte> rs::httpserver::ChunkedResponseStream::GetHeader(int blockSize) {
if (blockSize <= 0) {
return std::vector<Stream::byte>({'0', '\r', '\n'});
} else {
auto chars = 0;
while ((blockSize >> (4 * chars)) > 0) ++chars;
std::vector<Stream::byte> buffer(chars + 2);
for (auto i = 0; i < chars; ++i) {
auto index = chars - 1 - i;
buffer[index] = (blockSize >> (4 * i)) & 0x0f;
buffer[index] += buffer[index] > 9 ? ('a' - 10) : '0';
}
buffer[chars] = '\r';
buffer[chars + 1] = '\n';
return buffer;
}
}<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "messageoutputwindow.h"
#include <QtGui/QTextEdit>
using namespace Core::Internal;
MessageOutputWindow::MessageOutputWindow()
{
m_widget = new QTextEdit;
m_widget->setReadOnly(true);
m_widget->setFrameStyle(QFrame::NoFrame);
}
MessageOutputWindow::~MessageOutputWindow()
{
delete m_widget;
}
bool MessageOutputWindow::hasFocus()
{
return m_widget->hasFocus();
}
bool MessageOutputWindow::canFocus()
{
return true;
}
void MessageOutputWindow::setFocus()
{
m_widget->setFocus();
}
void MessageOutputWindow::clearContents()
{
m_widget->clear();
}
QWidget *MessageOutputWindow::outputWidget(QWidget *parent)
{
m_widget->setParent(parent);
return m_widget;
}
QString MessageOutputWindow::name() const
{
return tr("General");
}
void MessageOutputWindow::visibilityChanged(bool /*b*/)
{
}
void MessageOutputWindow::append(const QString &text)
{
m_widget->append(text);
}
int MessageOutputWindow::priorityInStatusBar() const
{
return -1;
}
bool MessageOutputWindow::canNext()
{
return false;
}
bool MessageOutputWindow::canPrevious()
{
return false;
}
void MessageOutputWindow::goToNext()
{
}
void MessageOutputWindow::goToPrev()
{
}
bool MessageOutputWindow::canNavigate()
{
return false;
}
<commit_msg>Make the title of the message output window more clear<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "messageoutputwindow.h"
#include <QtGui/QTextEdit>
using namespace Core::Internal;
MessageOutputWindow::MessageOutputWindow()
{
m_widget = new QTextEdit;
m_widget->setReadOnly(true);
m_widget->setFrameStyle(QFrame::NoFrame);
}
MessageOutputWindow::~MessageOutputWindow()
{
delete m_widget;
}
bool MessageOutputWindow::hasFocus()
{
return m_widget->hasFocus();
}
bool MessageOutputWindow::canFocus()
{
return true;
}
void MessageOutputWindow::setFocus()
{
m_widget->setFocus();
}
void MessageOutputWindow::clearContents()
{
m_widget->clear();
}
QWidget *MessageOutputWindow::outputWidget(QWidget *parent)
{
m_widget->setParent(parent);
return m_widget;
}
QString MessageOutputWindow::name() const
{
return tr("General Messages");
}
void MessageOutputWindow::visibilityChanged(bool /*b*/)
{
}
void MessageOutputWindow::append(const QString &text)
{
m_widget->append(text);
}
int MessageOutputWindow::priorityInStatusBar() const
{
return -1;
}
bool MessageOutputWindow::canNext()
{
return false;
}
bool MessageOutputWindow::canPrevious()
{
return false;
}
void MessageOutputWindow::goToNext()
{
}
void MessageOutputWindow::goToPrev()
{
}
bool MessageOutputWindow::canNavigate()
{
return false;
}
<|endoftext|> |
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "GPUColorControlFilter.h"
#include "Bitmap.h"
#include "ShaderRegistry.h"
#include "../base/ObjectCounter.h"
#include "../base/Exception.h"
#include <iostream>
#define SHADERID "BRIGHTNESS"
using namespace std;
namespace avg {
GPUColorControlFilter::GPUColorControlFilter(const IntPoint& size, bool bStandalone)
: GPUFilter(size, B8G8R8A8, B8G8R8A8, bStandalone),
m_Brightness(1),
m_Contrast(1),
m_RGamma(1),
m_GGamma(1),
m_BGamma(1)
{
ObjectCounter::get()->incRef(&typeid(*this));
initShader();
}
GPUColorControlFilter::~GPUColorControlFilter()
{
ObjectCounter::get()->decRef(&typeid(*this));
}
void GPUColorControlFilter::setParams(float brightness, float contrast, float rGamma,
float gGamma, float bGamma)
{
m_Brightness = brightness;
m_Contrast = contrast;
m_RGamma = rGamma;
m_GGamma = gGamma;
m_BGamma = bGamma;
}
void GPUColorControlFilter::applyOnGPU(GLTexturePtr pSrcTex)
{
OGLShaderPtr pShader = getShader(SHADERID);
pShader->activate();
pShader->setUniformIntParam("Texture", 0);
pShader->setUniformIntParam("texture", 0);
pShader->setUniformFloatParam("brightness", m_Brightness);
pShader->setUniformFloatParam("contrast", m_Contrast);
pShader->setUniformFloatParam("rGamma", 1./m_RGamma);
pShader->setUniformFloatParam("gGamma", 1./m_GGamma);
pShader->setUniformFloatParam("bGamma", 1./m_BGamma);
draw(pSrcTex);
glproc::UseProgramObject(0);
}
void GPUColorControlFilter::initShader()
{
string sProgram =
"uniform sampler2D texture;\n"
"uniform float brightness;\n"
"uniform float contrast;\n"
"uniform float rGamma;\n"
"uniform float gGamma;\n"
"uniform float bGamma;\n"
"\n"
+getStdShaderCode()+
"void main(void)\n"
"{\n"
" vec4 tex = texture2D(texture, gl_TexCoord[0].st);\n"
" unPreMultiplyAlpha(tex);\n"
" vec3 avg = vec3(0.5, 0.5, 0.5);\n"
" tex.rgb = mix(avg, tex.rgb, contrast);\n"
" tex.rgb = tex.rgb*brightness;\n"
" tex.rgb = vec3(pow(tex.r, rGamma), pow(tex.g, gGamma),\n"
" pow(tex.b, bGamma));\n"
" preMultiplyAlpha(tex);\n"
" gl_FragColor = tex;\n"
"}\n"
;
getOrCreateShader(SHADERID, sProgram);
}
} // namespace
<commit_msg>Windows warning fixes.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "GPUColorControlFilter.h"
#include "Bitmap.h"
#include "ShaderRegistry.h"
#include "../base/ObjectCounter.h"
#include "../base/Exception.h"
#include <iostream>
#define SHADERID "BRIGHTNESS"
using namespace std;
namespace avg {
GPUColorControlFilter::GPUColorControlFilter(const IntPoint& size, bool bStandalone)
: GPUFilter(size, B8G8R8A8, B8G8R8A8, bStandalone),
m_Brightness(1),
m_Contrast(1),
m_RGamma(1),
m_GGamma(1),
m_BGamma(1)
{
ObjectCounter::get()->incRef(&typeid(*this));
initShader();
}
GPUColorControlFilter::~GPUColorControlFilter()
{
ObjectCounter::get()->decRef(&typeid(*this));
}
void GPUColorControlFilter::setParams(float brightness, float contrast, float rGamma,
float gGamma, float bGamma)
{
m_Brightness = brightness;
m_Contrast = contrast;
m_RGamma = rGamma;
m_GGamma = gGamma;
m_BGamma = bGamma;
}
void GPUColorControlFilter::applyOnGPU(GLTexturePtr pSrcTex)
{
OGLShaderPtr pShader = getShader(SHADERID);
pShader->activate();
pShader->setUniformIntParam("Texture", 0);
pShader->setUniformIntParam("texture", 0);
pShader->setUniformFloatParam("brightness", m_Brightness);
pShader->setUniformFloatParam("contrast", m_Contrast);
pShader->setUniformFloatParam("rGamma", 1.f/m_RGamma);
pShader->setUniformFloatParam("gGamma", 1.f/m_GGamma);
pShader->setUniformFloatParam("bGamma", 1.f/m_BGamma);
draw(pSrcTex);
glproc::UseProgramObject(0);
}
void GPUColorControlFilter::initShader()
{
string sProgram =
"uniform sampler2D texture;\n"
"uniform float brightness;\n"
"uniform float contrast;\n"
"uniform float rGamma;\n"
"uniform float gGamma;\n"
"uniform float bGamma;\n"
"\n"
+getStdShaderCode()+
"void main(void)\n"
"{\n"
" vec4 tex = texture2D(texture, gl_TexCoord[0].st);\n"
" unPreMultiplyAlpha(tex);\n"
" vec3 avg = vec3(0.5, 0.5, 0.5);\n"
" tex.rgb = mix(avg, tex.rgb, contrast);\n"
" tex.rgb = tex.rgb*brightness;\n"
" tex.rgb = vec3(pow(tex.r, rGamma), pow(tex.g, gGamma),\n"
" pow(tex.b, bGamma));\n"
" preMultiplyAlpha(tex);\n"
" gl_FragColor = tex;\n"
"}\n"
;
getOrCreateShader(SHADERID, sProgram);
}
} // namespace
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "buildstepspage.h"
#include "ui_buildstepspage.h"
#include "project.h"
#include <coreplugin/coreconstants.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <utils/detailsbutton.h>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QMenu>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
BuildStepsPage::BuildStepsPage(Project *project, bool clean) :
BuildConfigWidget(),
m_pro(project),
m_clean(clean)
{
m_vbox = new QVBoxLayout(this);
m_vbox->setContentsMargins(20, 0, 0, 0);
const QList<BuildStep *> &steps = m_clean ? m_pro->cleanSteps() : m_pro->buildSteps();
foreach (BuildStep *bs, steps) {
addBuildStepWidget(-1, bs);
}
m_noStepsLabel = new QLabel(tr("No Build Steps"), this);
m_noStepsLabel->setVisible(steps.isEmpty());
m_vbox->addWidget(m_noStepsLabel);
QHBoxLayout *hboxLayout = new QHBoxLayout();
m_addButton = new QPushButton(this);
m_addButton->setText(clean ? tr("Add clean step") : tr("Add build step"));
m_addButton->setMenu(new QMenu(this));
hboxLayout->addWidget(m_addButton);
m_removeButton = new QPushButton(this);
m_removeButton->setText(clean ? tr("Remove clean step") : tr("Remove build step"));
m_removeButton->setMenu(new QMenu(this));
hboxLayout->addWidget(m_removeButton);
hboxLayout->addStretch(10);
#ifdef Q_OS_MAC
m_addButton->setAttribute(Qt::WA_MacSmallSize);
m_removeButton->setAttribute(Qt::WA_MacSmallSize);
#endif
m_vbox->addLayout(hboxLayout);
updateBuildStepButtonsState();
connect(m_addButton->menu(), SIGNAL(aboutToShow()),
this, SLOT(updateAddBuildStepMenu()));
connect(m_removeButton->menu(), SIGNAL(aboutToShow()),
this, SLOT(updateRemoveBuildStepMenu()));
}
BuildStepsPage::~BuildStepsPage()
{
foreach(BuildStepsWidgetStruct s, m_buildSteps) {
delete s.detailsLabel;
delete s.upButton;
delete s.downButton;
delete s.detailsButton;
delete s.hbox;
delete s.widget;
}
m_buildSteps.clear();
}
void BuildStepsPage::toggleDetails()
{
QAbstractButton *button = qobject_cast<QAbstractButton *>(sender());
if (button) {
foreach(const BuildStepsWidgetStruct &s, m_buildSteps) {
if (s.detailsButton == button) {
s.widget->setVisible(!s.widget->isVisible());
fixupLayout(s.widget);
}
}
}
}
void BuildStepsPage::updateSummary()
{
BuildStepConfigWidget *widget = qobject_cast<BuildStepConfigWidget *>(sender());
if (widget)
foreach(const BuildStepsWidgetStruct &s, m_buildSteps)
if (s.widget == widget)
s.detailsLabel->setText(widget->summaryText());
}
QString BuildStepsPage::displayName() const
{
return m_clean ? tr("Clean Steps") : tr("Build Steps");
}
void BuildStepsPage::init(const QString &buildConfiguration)
{
m_configuration = buildConfiguration;
// make sure widget is updated
foreach(BuildStepsWidgetStruct s, m_buildSteps) {
s.widget->init(m_configuration);
s.detailsLabel->setText(s.widget->summaryText());
}
}
void BuildStepsPage::updateAddBuildStepMenu()
{
QMap<QString, QPair<QString, IBuildStepFactory *> > map;
//Build up a list of possible steps and save map the display names to the (internal) name and factories.
QList<IBuildStepFactory *> factories = ExtensionSystem::PluginManager::instance()->getObjects<IBuildStepFactory>();
foreach (IBuildStepFactory * factory, factories) {
QStringList names = factory->canCreateForProject(m_pro);
foreach (const QString &name, names) {
map.insert(factory->displayNameForName(name), QPair<QString, IBuildStepFactory *>(name, factory));
}
}
// Ask the user which one to add
QMenu *menu = m_addButton->menu();
m_addBuildStepHash.clear();
menu->clear();
if (!map.isEmpty()) {
QStringList names;
QMap<QString, QPair<QString, IBuildStepFactory *> >::const_iterator it, end;
end = map.constEnd();
for (it = map.constBegin(); it != end; ++it) {
QAction *action = menu->addAction(it.key());
connect(action, SIGNAL(triggered()),
this, SLOT(addBuildStep()));
m_addBuildStepHash.insert(action, it.value());
}
}
}
void BuildStepsPage::addBuildStepWidget(int pos, BuildStep *step)
{
// create everything
BuildStepsWidgetStruct s;
s.widget = step->createConfigWidget();
s.detailsLabel = new QLabel(this);
s.detailsLabel->setText(s.widget->summaryText());
s.upButton = new QToolButton(this);
s.upButton->setArrowType(Qt::UpArrow);
s.downButton = new QToolButton(this);
s.downButton->setArrowType(Qt::DownArrow);
#ifdef Q_OS_MAC
s.upButton->setIconSize(QSize(10, 10));
s.downButton->setIconSize(QSize(10, 10));
#endif
s.detailsButton = new Utils::DetailsButton(this);
// layout
s.hbox = new QHBoxLayout();
s.hbox->addWidget(s.detailsLabel);
s.hbox->addWidget(s.upButton);
s.hbox->addWidget(s.downButton);
s.hbox->addWidget(s.detailsButton);
if (pos == -1)
m_buildSteps.append(s);
else
m_buildSteps.insert(pos, s);
if (pos == -1) {
m_vbox->addLayout(s.hbox);
m_vbox->addWidget(s.widget);
} else {
m_vbox->insertLayout(pos *2, s.hbox);
m_vbox->insertWidget(pos *2 + 1, s.widget);
}
s.widget->hide();
// connect
connect(s.detailsButton, SIGNAL(clicked()),
this, SLOT(toggleDetails()));
connect(s.widget, SIGNAL(updateSummary()),
this, SLOT(updateSummary()));
connect(s.upButton, SIGNAL(clicked()),
this, SLOT(upBuildStep()));
connect(s.downButton, SIGNAL(clicked()),
this, SLOT(downBuildStep()));
}
void BuildStepsPage::addBuildStep()
{
if (QAction *action = qobject_cast<QAction *>(sender())) {
QPair<QString, IBuildStepFactory *> pair = m_addBuildStepHash.value(action);
BuildStep *newStep = pair.second->create(m_pro, pair.first);
int pos = m_clean ? m_pro->cleanSteps().count() : m_pro->buildSteps().count();
m_clean ? m_pro->insertCleanStep(pos, newStep) : m_pro->insertBuildStep(pos, newStep);
addBuildStepWidget(pos, newStep);
const BuildStepsWidgetStruct s = m_buildSteps.at(pos);
s.widget->init(m_configuration);
s.detailsLabel->setText(s.widget->summaryText());
}
updateBuildStepButtonsState();
}
void BuildStepsPage::updateRemoveBuildStepMenu()
{
QMenu *menu = m_removeButton->menu();
menu->clear();
const QList<BuildStep *> &steps = m_clean ? m_pro->cleanSteps() : m_pro->buildSteps();
foreach(BuildStep *step, steps) {
QAction *action = menu->addAction(step->displayName());
if (step->immutable())
action->setEnabled(false);
connect(action, SIGNAL(triggered()),
this, SLOT(removeBuildStep()));
}
}
void BuildStepsPage::removeBuildStep()
{
QAction *action = qobject_cast<QAction *>(sender());
if (action) {
int pos = m_removeButton->menu()->actions().indexOf(action);
const QList<BuildStep *> &steps = m_clean ? m_pro->cleanSteps() : m_pro->buildSteps();
if (steps.at(pos)->immutable())
return;
BuildStepsWidgetStruct s = m_buildSteps.at(pos);
delete s.detailsLabel;
delete s.upButton;
delete s.downButton;
delete s.detailsButton;
delete s.hbox;
delete s.widget;
m_buildSteps.removeAt(pos);
m_clean ? m_pro->removeCleanStep(pos) : m_pro->removeBuildStep(pos);
}
updateBuildStepButtonsState();
}
void BuildStepsPage::upBuildStep()
{
int pos = -1;
QToolButton *tb = qobject_cast<QToolButton *>(sender());
if (!tb)
return;
for (int i=0; i<m_buildSteps.count(); ++i) {
if (m_buildSteps.at(i).upButton == tb) {
pos = i;
break;
}
}
if (pos == -1)
return;
stepMoveUp(pos);
updateBuildStepButtonsState();
}
void BuildStepsPage::downBuildStep()
{
int pos = -1;
QToolButton *tb = qobject_cast<QToolButton *>(sender());
if (!tb)
return;
for (int i=0; i<m_buildSteps.count(); ++i) {
if (m_buildSteps.at(i).downButton == tb) {
pos = i;
break;
}
}
if (pos == -1)
return;
stepMoveUp(pos + 1);
updateBuildStepButtonsState();
}
void BuildStepsPage::stepMoveUp(int pos)
{
m_clean ? m_pro->moveCleanStepUp(pos) : m_pro->moveBuildStepUp(pos);
m_buildSteps.at(pos).hbox->setParent(0);
m_vbox->insertLayout((pos - 1) * 2, m_buildSteps.at(pos).hbox);
m_vbox->insertWidget((pos - 1) * 2 + 1, m_buildSteps.at(pos).widget);
BuildStepsWidgetStruct tmp = m_buildSteps.at(pos -1);
m_buildSteps[pos -1] = m_buildSteps.at(pos);
m_buildSteps[pos] = tmp;
}
void BuildStepsPage::updateBuildStepButtonsState()
{
const QList<BuildStep *> &steps = m_clean ? m_pro->cleanSteps() : m_pro->buildSteps();
for(int i=0; i<m_buildSteps.count(); ++i) {
BuildStepsWidgetStruct s = m_buildSteps.at(i);
s.upButton->setEnabled((i>0) && !(steps.at(i)->immutable() && steps.at(i - 1)));
s.downButton->setEnabled((i + 1< steps.count()) && !(steps.at(i)->immutable() && steps.at(i + 1)->immutable()));
}
}
<commit_msg>Fix build.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "buildstepspage.h"
#include "project.h"
#include <coreplugin/coreconstants.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <utils/detailsbutton.h>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QMenu>
#include <QtGui/QVBoxLayout>
#include <QtGui/QHBoxLayout>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
BuildStepsPage::BuildStepsPage(Project *project, bool clean) :
BuildConfigWidget(),
m_pro(project),
m_clean(clean)
{
m_vbox = new QVBoxLayout(this);
m_vbox->setContentsMargins(20, 0, 0, 0);
const QList<BuildStep *> &steps = m_clean ? m_pro->cleanSteps() : m_pro->buildSteps();
foreach (BuildStep *bs, steps) {
addBuildStepWidget(-1, bs);
}
m_noStepsLabel = new QLabel(tr("No Build Steps"), this);
m_noStepsLabel->setVisible(steps.isEmpty());
m_vbox->addWidget(m_noStepsLabel);
QHBoxLayout *hboxLayout = new QHBoxLayout();
m_addButton = new QPushButton(this);
m_addButton->setText(clean ? tr("Add clean step") : tr("Add build step"));
m_addButton->setMenu(new QMenu(this));
hboxLayout->addWidget(m_addButton);
m_removeButton = new QPushButton(this);
m_removeButton->setText(clean ? tr("Remove clean step") : tr("Remove build step"));
m_removeButton->setMenu(new QMenu(this));
hboxLayout->addWidget(m_removeButton);
hboxLayout->addStretch(10);
#ifdef Q_OS_MAC
m_addButton->setAttribute(Qt::WA_MacSmallSize);
m_removeButton->setAttribute(Qt::WA_MacSmallSize);
#endif
m_vbox->addLayout(hboxLayout);
updateBuildStepButtonsState();
connect(m_addButton->menu(), SIGNAL(aboutToShow()),
this, SLOT(updateAddBuildStepMenu()));
connect(m_removeButton->menu(), SIGNAL(aboutToShow()),
this, SLOT(updateRemoveBuildStepMenu()));
}
BuildStepsPage::~BuildStepsPage()
{
foreach(BuildStepsWidgetStruct s, m_buildSteps) {
delete s.detailsLabel;
delete s.upButton;
delete s.downButton;
delete s.detailsButton;
delete s.hbox;
delete s.widget;
}
m_buildSteps.clear();
}
void BuildStepsPage::toggleDetails()
{
QAbstractButton *button = qobject_cast<QAbstractButton *>(sender());
if (button) {
foreach(const BuildStepsWidgetStruct &s, m_buildSteps) {
if (s.detailsButton == button) {
s.widget->setVisible(!s.widget->isVisible());
fixupLayout(s.widget);
}
}
}
}
void BuildStepsPage::updateSummary()
{
BuildStepConfigWidget *widget = qobject_cast<BuildStepConfigWidget *>(sender());
if (widget)
foreach(const BuildStepsWidgetStruct &s, m_buildSteps)
if (s.widget == widget)
s.detailsLabel->setText(widget->summaryText());
}
QString BuildStepsPage::displayName() const
{
return m_clean ? tr("Clean Steps") : tr("Build Steps");
}
void BuildStepsPage::init(const QString &buildConfiguration)
{
m_configuration = buildConfiguration;
// make sure widget is updated
foreach(BuildStepsWidgetStruct s, m_buildSteps) {
s.widget->init(m_configuration);
s.detailsLabel->setText(s.widget->summaryText());
}
}
void BuildStepsPage::updateAddBuildStepMenu()
{
QMap<QString, QPair<QString, IBuildStepFactory *> > map;
//Build up a list of possible steps and save map the display names to the (internal) name and factories.
QList<IBuildStepFactory *> factories = ExtensionSystem::PluginManager::instance()->getObjects<IBuildStepFactory>();
foreach (IBuildStepFactory * factory, factories) {
QStringList names = factory->canCreateForProject(m_pro);
foreach (const QString &name, names) {
map.insert(factory->displayNameForName(name), QPair<QString, IBuildStepFactory *>(name, factory));
}
}
// Ask the user which one to add
QMenu *menu = m_addButton->menu();
m_addBuildStepHash.clear();
menu->clear();
if (!map.isEmpty()) {
QStringList names;
QMap<QString, QPair<QString, IBuildStepFactory *> >::const_iterator it, end;
end = map.constEnd();
for (it = map.constBegin(); it != end; ++it) {
QAction *action = menu->addAction(it.key());
connect(action, SIGNAL(triggered()),
this, SLOT(addBuildStep()));
m_addBuildStepHash.insert(action, it.value());
}
}
}
void BuildStepsPage::addBuildStepWidget(int pos, BuildStep *step)
{
// create everything
BuildStepsWidgetStruct s;
s.widget = step->createConfigWidget();
s.detailsLabel = new QLabel(this);
s.detailsLabel->setText(s.widget->summaryText());
s.upButton = new QToolButton(this);
s.upButton->setArrowType(Qt::UpArrow);
s.downButton = new QToolButton(this);
s.downButton->setArrowType(Qt::DownArrow);
#ifdef Q_OS_MAC
s.upButton->setIconSize(QSize(10, 10));
s.downButton->setIconSize(QSize(10, 10));
#endif
s.detailsButton = new Utils::DetailsButton(this);
// layout
s.hbox = new QHBoxLayout();
s.hbox->addWidget(s.detailsLabel);
s.hbox->addWidget(s.upButton);
s.hbox->addWidget(s.downButton);
s.hbox->addWidget(s.detailsButton);
if (pos == -1)
m_buildSteps.append(s);
else
m_buildSteps.insert(pos, s);
if (pos == -1) {
m_vbox->addLayout(s.hbox);
m_vbox->addWidget(s.widget);
} else {
m_vbox->insertLayout(pos *2, s.hbox);
m_vbox->insertWidget(pos *2 + 1, s.widget);
}
s.widget->hide();
// connect
connect(s.detailsButton, SIGNAL(clicked()),
this, SLOT(toggleDetails()));
connect(s.widget, SIGNAL(updateSummary()),
this, SLOT(updateSummary()));
connect(s.upButton, SIGNAL(clicked()),
this, SLOT(upBuildStep()));
connect(s.downButton, SIGNAL(clicked()),
this, SLOT(downBuildStep()));
}
void BuildStepsPage::addBuildStep()
{
if (QAction *action = qobject_cast<QAction *>(sender())) {
QPair<QString, IBuildStepFactory *> pair = m_addBuildStepHash.value(action);
BuildStep *newStep = pair.second->create(m_pro, pair.first);
int pos = m_clean ? m_pro->cleanSteps().count() : m_pro->buildSteps().count();
m_clean ? m_pro->insertCleanStep(pos, newStep) : m_pro->insertBuildStep(pos, newStep);
addBuildStepWidget(pos, newStep);
const BuildStepsWidgetStruct s = m_buildSteps.at(pos);
s.widget->init(m_configuration);
s.detailsLabel->setText(s.widget->summaryText());
}
updateBuildStepButtonsState();
}
void BuildStepsPage::updateRemoveBuildStepMenu()
{
QMenu *menu = m_removeButton->menu();
menu->clear();
const QList<BuildStep *> &steps = m_clean ? m_pro->cleanSteps() : m_pro->buildSteps();
foreach(BuildStep *step, steps) {
QAction *action = menu->addAction(step->displayName());
if (step->immutable())
action->setEnabled(false);
connect(action, SIGNAL(triggered()),
this, SLOT(removeBuildStep()));
}
}
void BuildStepsPage::removeBuildStep()
{
QAction *action = qobject_cast<QAction *>(sender());
if (action) {
int pos = m_removeButton->menu()->actions().indexOf(action);
const QList<BuildStep *> &steps = m_clean ? m_pro->cleanSteps() : m_pro->buildSteps();
if (steps.at(pos)->immutable())
return;
BuildStepsWidgetStruct s = m_buildSteps.at(pos);
delete s.detailsLabel;
delete s.upButton;
delete s.downButton;
delete s.detailsButton;
delete s.hbox;
delete s.widget;
m_buildSteps.removeAt(pos);
m_clean ? m_pro->removeCleanStep(pos) : m_pro->removeBuildStep(pos);
}
updateBuildStepButtonsState();
}
void BuildStepsPage::upBuildStep()
{
int pos = -1;
QToolButton *tb = qobject_cast<QToolButton *>(sender());
if (!tb)
return;
for (int i=0; i<m_buildSteps.count(); ++i) {
if (m_buildSteps.at(i).upButton == tb) {
pos = i;
break;
}
}
if (pos == -1)
return;
stepMoveUp(pos);
updateBuildStepButtonsState();
}
void BuildStepsPage::downBuildStep()
{
int pos = -1;
QToolButton *tb = qobject_cast<QToolButton *>(sender());
if (!tb)
return;
for (int i=0; i<m_buildSteps.count(); ++i) {
if (m_buildSteps.at(i).downButton == tb) {
pos = i;
break;
}
}
if (pos == -1)
return;
stepMoveUp(pos + 1);
updateBuildStepButtonsState();
}
void BuildStepsPage::stepMoveUp(int pos)
{
m_clean ? m_pro->moveCleanStepUp(pos) : m_pro->moveBuildStepUp(pos);
m_buildSteps.at(pos).hbox->setParent(0);
m_vbox->insertLayout((pos - 1) * 2, m_buildSteps.at(pos).hbox);
m_vbox->insertWidget((pos - 1) * 2 + 1, m_buildSteps.at(pos).widget);
BuildStepsWidgetStruct tmp = m_buildSteps.at(pos -1);
m_buildSteps[pos -1] = m_buildSteps.at(pos);
m_buildSteps[pos] = tmp;
}
void BuildStepsPage::updateBuildStepButtonsState()
{
const QList<BuildStep *> &steps = m_clean ? m_pro->cleanSteps() : m_pro->buildSteps();
for(int i=0; i<m_buildSteps.count(); ++i) {
BuildStepsWidgetStruct s = m_buildSteps.at(i);
s.upButton->setEnabled((i>0) && !(steps.at(i)->immutable() && steps.at(i - 1)));
s.downButton->setEnabled((i + 1< steps.count()) && !(steps.at(i)->immutable() && steps.at(i + 1)->immutable()));
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
**
** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
**
** 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.
**
****************************************************************************/
#include "blackberrysetupwizardpages.h"
#include "blackberryndksettingswidget.h"
#include "blackberryconfiguration.h"
#include "blackberrysigningutils.h"
#include "ui_blackberrysetupwizardkeyspage.h"
#include "ui_blackberrysetupwizardcertificatepage.h"
#include "ui_blackberrysetupwizarddevicepage.h"
#include "ui_blackberrysetupwizardfinishpage.h"
#include <QVBoxLayout>
#include <QFileInfo>
#include <QLabel>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QAbstractButton>
#include <QDesktopServices>
#include <QUrl>
#include <QDebug>
using namespace Qnx;
using namespace Qnx::Internal;
BlackBerrySetupWizardWelcomePage::BlackBerrySetupWizardWelcomePage(QWidget *parent) :
QWizardPage(parent)
{
const QString welcomeMessage =
tr("Welcome to the BlackBerry Development "
"Environment Setup Wizard.\nThis wizard will guide you through "
"the essential steps to deploy a ready-to-go development environment "
"for BlackBerry 10 devices.");
setTitle(tr("BlackBerry Development Environment Setup"));
QLabel *label = new QLabel(this);
label->setWordWrap(true);
label->setText(welcomeMessage);
QVBoxLayout *layout = new QVBoxLayout;
layout->addStretch();
layout->addWidget(label);
layout->addStretch();
setLayout(layout);
}
//-----------------------------------------------------------------------------
BlackBerrySetupWizardNdkPage::BlackBerrySetupWizardNdkPage(QWidget *parent) :
QWizardPage(parent),
m_widget(0)
{
setTitle(tr("Configure the NDK Path"));
m_widget = new BlackBerryNDKSettingsWidget(this);
m_widget->setWizardMessageVisible(false);
connect(m_widget, SIGNAL(targetsUpdated()), this, SIGNAL(completeChanged()));
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(m_widget);
setLayout(layout);
}
BlackBerrySetupWizardNdkPage::~BlackBerrySetupWizardNdkPage()
{
}
bool BlackBerrySetupWizardNdkPage::isComplete() const
{
return m_widget->hasActiveNdk();
}
//-----------------------------------------------------------------------------
BlackBerrySetupWizardKeysPage::BlackBerrySetupWizardKeysPage(QWidget *parent) :
QWizardPage(parent),
m_ui(0),
m_complete(false)
{
setTitle(tr("Setup Signing Keys"));
initUi();
}
BlackBerrySetupWizardKeysPage::~BlackBerrySetupWizardKeysPage()
{
delete m_ui;
m_ui = 0;
}
void BlackBerrySetupWizardKeysPage::showKeysMessage(const QString &url)
{
const QMessageBox::StandardButton button = QMessageBox::question(this,
tr("Qt Creator"),
tr("This wizard will be closed and you will be taken to the BlackBerry "
"key request web page. Do you want to continue?"),
QMessageBox::Yes | QMessageBox::No);
if (button == QMessageBox::Yes) {
QDesktopServices::openUrl(QUrl(url));
wizard()->reject();
}
}
bool BlackBerrySetupWizardKeysPage::isComplete() const
{
return m_complete;
}
void BlackBerrySetupWizardKeysPage::initUi()
{
BlackBerrySigningUtils &utils = BlackBerrySigningUtils::instance();
m_ui = new Ui::BlackBerrySetupWizardKeysPage;
m_ui->setupUi(this);
if (utils.hasLegacyKeys()) {
m_ui->linkLabel->setVisible(false);
m_ui->legacyLabel->setVisible(true);
m_ui->statusLabel->setVisible(false);
setComplete(false);
} else if (utils.hasRegisteredKeys()) {
m_ui->linkLabel->setVisible(false);
m_ui->legacyLabel->setVisible(false);
m_ui->statusLabel->setVisible(true);
setComplete(true);
} else {
m_ui->linkLabel->setVisible(true);
m_ui->legacyLabel->setVisible(false);
m_ui->statusLabel->setVisible(false);
setComplete(false);
}
connect(m_ui->linkLabel, SIGNAL(linkActivated(QString)),
this, SLOT(showKeysMessage(QString)));
connect(m_ui->legacyLabel, SIGNAL(linkActivated(QString)),
this, SLOT(showKeysMessage(QString)));
}
void BlackBerrySetupWizardKeysPage::setComplete(bool complete)
{
if (m_complete != complete) {
m_complete = complete;
m_ui->linkLabel->setVisible(!complete);
m_ui->statusLabel->setVisible(complete);
emit completeChanged();
}
}
//-----------------------------------------------------------------------------
const char BlackBerrySetupWizardCertificatePage::AuthorField[] = "CertificatePage::Author";
const char BlackBerrySetupWizardCertificatePage::PasswordField[] = "CertificatePage::Password";
const char BlackBerrySetupWizardCertificatePage::PasswordField2[] = "CertificatePage::Password2";
BlackBerrySetupWizardCertificatePage::BlackBerrySetupWizardCertificatePage(QWidget *parent)
: QWizardPage(parent),
m_ui(0),
m_complete(false)
{
setTitle(tr("Create Developer Certificate"));
initUi();
}
bool BlackBerrySetupWizardCertificatePage::isComplete() const
{
return m_complete;
}
void BlackBerrySetupWizardCertificatePage::validate()
{
if (m_ui->author->text().isEmpty()
|| m_ui->password->text().isEmpty()
|| m_ui->password2->text().isEmpty()) {
m_ui->status->clear();
setComplete(false);
return;
}
if (m_ui->password->text() != m_ui->password2->text()) {
m_ui->status->setText(tr("The entered passwords do not match."));
setComplete(false);
return;
}
m_ui->status->clear();
setComplete(true);
}
void BlackBerrySetupWizardCertificatePage::checkBoxChanged(int state)
{
if (state == Qt::Checked) {
m_ui->password->setEchoMode(QLineEdit::Normal);
m_ui->password2->setEchoMode(QLineEdit::Normal);
} else {
m_ui->password->setEchoMode(QLineEdit::Password);
m_ui->password2->setEchoMode(QLineEdit::Password);
}
}
void BlackBerrySetupWizardCertificatePage::setComplete(bool complete)
{
if (m_complete != complete) {
m_complete = complete;
emit completeChanged();
}
}
void BlackBerrySetupWizardCertificatePage::initUi()
{
m_ui = new Ui::BlackBerrySetupWizardCertificatePage;
m_ui->setupUi(this);
m_ui->status->clear();
connect(m_ui->author, SIGNAL(textChanged(QString)),
this, SLOT(validate()));
connect(m_ui->password, SIGNAL(textChanged(QString)),
this, SLOT(validate()));
connect(m_ui->password2, SIGNAL(textChanged(QString)),
this, SLOT(validate()));
connect(m_ui->showPassword, SIGNAL(stateChanged(int)),
this, SLOT(checkBoxChanged(int)));
registerField(QLatin1String(AuthorField) + QLatin1Char('*'), m_ui->author);
registerField(QLatin1String(PasswordField) + QLatin1Char('*'), m_ui->password);
registerField(QLatin1String(PasswordField2) + QLatin1Char('*'), m_ui->password2);
}
//-----------------------------------------------------------------------------
const char BlackBerrySetupWizardDevicePage::NameField[] = "DevicePage::Name";
const char BlackBerrySetupWizardDevicePage::IpAddressField[] = "DevicePage::IpAddress";
const char BlackBerrySetupWizardDevicePage::PasswordField[] = "DevicePage::PasswordField";
const char BlackBerrySetupWizardDevicePage::PhysicalDeviceField[] = "DevicePage::PhysicalDeviceField";
BlackBerrySetupWizardDevicePage::BlackBerrySetupWizardDevicePage(QWidget *parent)
: QWizardPage(parent),
m_ui(0)
{
setTitle(tr("Configure BlackBerry Device Connection"));
m_ui = new Ui::BlackBerrySetupWizardDevicePage;
m_ui->setupUi(this);
m_ui->deviceName->setText(tr("BlackBerry Device"));
m_ui->ipAddress->setText(QLatin1String("169.254.0.1"));
connect(m_ui->deviceName, SIGNAL(textChanged(QString)), this, SIGNAL(completeChanged()));
connect(m_ui->ipAddress, SIGNAL(textChanged(QString)), this, SIGNAL(completeChanged()));
connect(m_ui->password, SIGNAL(textChanged(QString)), this, SIGNAL(completeChanged()));
connect(m_ui->physicalDevice, SIGNAL(toggled(bool)), this, SIGNAL(completeChanged()));
registerField(QLatin1String(NameField) + QLatin1Char('*'), m_ui->deviceName);
registerField(QLatin1String(IpAddressField) + QLatin1Char('*'), m_ui->ipAddress);
registerField(QLatin1String(PasswordField), m_ui->password);
registerField(QLatin1String(PhysicalDeviceField), m_ui->physicalDevice);
}
bool BlackBerrySetupWizardDevicePage::isComplete() const
{
if (m_ui->deviceName->text().isEmpty() || m_ui->ipAddress->text().isEmpty())
return false;
const bool passwordMandatory = m_ui->physicalDevice->isChecked();
if (passwordMandatory && m_ui->password->text().isEmpty())
return false;
return true;
}
//-----------------------------------------------------------------------------
BlackBerrySetupWizardFinishPage::BlackBerrySetupWizardFinishPage(QWidget *parent)
: QWizardPage(parent),
m_ui(0)
{
setSubTitle(tr("Your environment is ready to be configured."));
m_ui = new Ui::BlackBerrySetupWizardFinishPage;
m_ui->setupUi(this);
setProgress(QString(), -1);
}
void BlackBerrySetupWizardFinishPage::setProgress(const QString &status, int progress)
{
if (progress < 0) {
m_ui->progressBar->hide();
m_ui->statusLabel->clear();
return;
} else if (!m_ui->progressBar->isVisible()) {
m_ui->progressBar->show();
}
m_ui->statusLabel->setText(status);
m_ui->progressBar->setValue(progress);
}
<commit_msg>QNX: Fix password length warning in environment setup wizard<commit_after>/**************************************************************************
**
** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
**
** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
**
** 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.
**
****************************************************************************/
#include "blackberrysetupwizardpages.h"
#include "blackberryndksettingswidget.h"
#include "blackberryconfiguration.h"
#include "blackberrysigningutils.h"
#include "ui_blackberrysetupwizardkeyspage.h"
#include "ui_blackberrysetupwizardcertificatepage.h"
#include "ui_blackberrysetupwizarddevicepage.h"
#include "ui_blackberrysetupwizardfinishpage.h"
#include <QVBoxLayout>
#include <QFileInfo>
#include <QLabel>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QAbstractButton>
#include <QDesktopServices>
#include <QUrl>
#include <QDebug>
using namespace Qnx;
using namespace Qnx::Internal;
BlackBerrySetupWizardWelcomePage::BlackBerrySetupWizardWelcomePage(QWidget *parent) :
QWizardPage(parent)
{
const QString welcomeMessage =
tr("Welcome to the BlackBerry Development "
"Environment Setup Wizard.\nThis wizard will guide you through "
"the essential steps to deploy a ready-to-go development environment "
"for BlackBerry 10 devices.");
setTitle(tr("BlackBerry Development Environment Setup"));
QLabel *label = new QLabel(this);
label->setWordWrap(true);
label->setText(welcomeMessage);
QVBoxLayout *layout = new QVBoxLayout;
layout->addStretch();
layout->addWidget(label);
layout->addStretch();
setLayout(layout);
}
//-----------------------------------------------------------------------------
BlackBerrySetupWizardNdkPage::BlackBerrySetupWizardNdkPage(QWidget *parent) :
QWizardPage(parent),
m_widget(0)
{
setTitle(tr("Configure the NDK Path"));
m_widget = new BlackBerryNDKSettingsWidget(this);
m_widget->setWizardMessageVisible(false);
connect(m_widget, SIGNAL(targetsUpdated()), this, SIGNAL(completeChanged()));
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(m_widget);
setLayout(layout);
}
BlackBerrySetupWizardNdkPage::~BlackBerrySetupWizardNdkPage()
{
}
bool BlackBerrySetupWizardNdkPage::isComplete() const
{
return m_widget->hasActiveNdk();
}
//-----------------------------------------------------------------------------
BlackBerrySetupWizardKeysPage::BlackBerrySetupWizardKeysPage(QWidget *parent) :
QWizardPage(parent),
m_ui(0),
m_complete(false)
{
setTitle(tr("Setup Signing Keys"));
initUi();
}
BlackBerrySetupWizardKeysPage::~BlackBerrySetupWizardKeysPage()
{
delete m_ui;
m_ui = 0;
}
void BlackBerrySetupWizardKeysPage::showKeysMessage(const QString &url)
{
const QMessageBox::StandardButton button = QMessageBox::question(this,
tr("Qt Creator"),
tr("This wizard will be closed and you will be taken to the BlackBerry "
"key request web page. Do you want to continue?"),
QMessageBox::Yes | QMessageBox::No);
if (button == QMessageBox::Yes) {
QDesktopServices::openUrl(QUrl(url));
wizard()->reject();
}
}
bool BlackBerrySetupWizardKeysPage::isComplete() const
{
return m_complete;
}
void BlackBerrySetupWizardKeysPage::initUi()
{
BlackBerrySigningUtils &utils = BlackBerrySigningUtils::instance();
m_ui = new Ui::BlackBerrySetupWizardKeysPage;
m_ui->setupUi(this);
if (utils.hasLegacyKeys()) {
m_ui->linkLabel->setVisible(false);
m_ui->legacyLabel->setVisible(true);
m_ui->statusLabel->setVisible(false);
setComplete(false);
} else if (utils.hasRegisteredKeys()) {
m_ui->linkLabel->setVisible(false);
m_ui->legacyLabel->setVisible(false);
m_ui->statusLabel->setVisible(true);
setComplete(true);
} else {
m_ui->linkLabel->setVisible(true);
m_ui->legacyLabel->setVisible(false);
m_ui->statusLabel->setVisible(false);
setComplete(false);
}
connect(m_ui->linkLabel, SIGNAL(linkActivated(QString)),
this, SLOT(showKeysMessage(QString)));
connect(m_ui->legacyLabel, SIGNAL(linkActivated(QString)),
this, SLOT(showKeysMessage(QString)));
}
void BlackBerrySetupWizardKeysPage::setComplete(bool complete)
{
if (m_complete != complete) {
m_complete = complete;
m_ui->linkLabel->setVisible(!complete);
m_ui->statusLabel->setVisible(complete);
emit completeChanged();
}
}
//-----------------------------------------------------------------------------
const char BlackBerrySetupWizardCertificatePage::AuthorField[] = "CertificatePage::Author";
const char BlackBerrySetupWizardCertificatePage::PasswordField[] = "CertificatePage::Password";
const char BlackBerrySetupWizardCertificatePage::PasswordField2[] = "CertificatePage::Password2";
BlackBerrySetupWizardCertificatePage::BlackBerrySetupWizardCertificatePage(QWidget *parent)
: QWizardPage(parent),
m_ui(0),
m_complete(false)
{
setTitle(tr("Create Developer Certificate"));
initUi();
}
bool BlackBerrySetupWizardCertificatePage::isComplete() const
{
return m_complete;
}
void BlackBerrySetupWizardCertificatePage::validate()
{
if (m_ui->author->text().isEmpty()
|| m_ui->password->text().isEmpty()
|| m_ui->password2->text().isEmpty()) {
m_ui->status->clear();
setComplete(false);
return;
}
if (m_ui->password->text() != m_ui->password2->text()) {
m_ui->status->setText(tr("The entered passwords do not match."));
setComplete(false);
return;
}
if (m_ui->password->text().size() < 6) {
// TODO: Use tr() once string freeze is over
m_ui->status->setText(QCoreApplication::translate("Qnx::Internal::BlackBerryCreateCertificateDialog", "Password must be at least 6 characters long."));
setComplete(false);
return;
}
m_ui->status->clear();
setComplete(true);
}
void BlackBerrySetupWizardCertificatePage::checkBoxChanged(int state)
{
if (state == Qt::Checked) {
m_ui->password->setEchoMode(QLineEdit::Normal);
m_ui->password2->setEchoMode(QLineEdit::Normal);
} else {
m_ui->password->setEchoMode(QLineEdit::Password);
m_ui->password2->setEchoMode(QLineEdit::Password);
}
}
void BlackBerrySetupWizardCertificatePage::setComplete(bool complete)
{
if (m_complete != complete) {
m_complete = complete;
emit completeChanged();
}
}
void BlackBerrySetupWizardCertificatePage::initUi()
{
m_ui = new Ui::BlackBerrySetupWizardCertificatePage;
m_ui->setupUi(this);
m_ui->status->clear();
connect(m_ui->author, SIGNAL(textChanged(QString)),
this, SLOT(validate()));
connect(m_ui->password, SIGNAL(textChanged(QString)),
this, SLOT(validate()));
connect(m_ui->password2, SIGNAL(textChanged(QString)),
this, SLOT(validate()));
connect(m_ui->showPassword, SIGNAL(stateChanged(int)),
this, SLOT(checkBoxChanged(int)));
registerField(QLatin1String(AuthorField) + QLatin1Char('*'), m_ui->author);
registerField(QLatin1String(PasswordField) + QLatin1Char('*'), m_ui->password);
registerField(QLatin1String(PasswordField2) + QLatin1Char('*'), m_ui->password2);
}
//-----------------------------------------------------------------------------
const char BlackBerrySetupWizardDevicePage::NameField[] = "DevicePage::Name";
const char BlackBerrySetupWizardDevicePage::IpAddressField[] = "DevicePage::IpAddress";
const char BlackBerrySetupWizardDevicePage::PasswordField[] = "DevicePage::PasswordField";
const char BlackBerrySetupWizardDevicePage::PhysicalDeviceField[] = "DevicePage::PhysicalDeviceField";
BlackBerrySetupWizardDevicePage::BlackBerrySetupWizardDevicePage(QWidget *parent)
: QWizardPage(parent),
m_ui(0)
{
setTitle(tr("Configure BlackBerry Device Connection"));
m_ui = new Ui::BlackBerrySetupWizardDevicePage;
m_ui->setupUi(this);
m_ui->deviceName->setText(tr("BlackBerry Device"));
m_ui->ipAddress->setText(QLatin1String("169.254.0.1"));
connect(m_ui->deviceName, SIGNAL(textChanged(QString)), this, SIGNAL(completeChanged()));
connect(m_ui->ipAddress, SIGNAL(textChanged(QString)), this, SIGNAL(completeChanged()));
connect(m_ui->password, SIGNAL(textChanged(QString)), this, SIGNAL(completeChanged()));
connect(m_ui->physicalDevice, SIGNAL(toggled(bool)), this, SIGNAL(completeChanged()));
registerField(QLatin1String(NameField) + QLatin1Char('*'), m_ui->deviceName);
registerField(QLatin1String(IpAddressField) + QLatin1Char('*'), m_ui->ipAddress);
registerField(QLatin1String(PasswordField), m_ui->password);
registerField(QLatin1String(PhysicalDeviceField), m_ui->physicalDevice);
}
bool BlackBerrySetupWizardDevicePage::isComplete() const
{
if (m_ui->deviceName->text().isEmpty() || m_ui->ipAddress->text().isEmpty())
return false;
const bool passwordMandatory = m_ui->physicalDevice->isChecked();
if (passwordMandatory && m_ui->password->text().isEmpty())
return false;
return true;
}
//-----------------------------------------------------------------------------
BlackBerrySetupWizardFinishPage::BlackBerrySetupWizardFinishPage(QWidget *parent)
: QWizardPage(parent),
m_ui(0)
{
setSubTitle(tr("Your environment is ready to be configured."));
m_ui = new Ui::BlackBerrySetupWizardFinishPage;
m_ui->setupUi(this);
setProgress(QString(), -1);
}
void BlackBerrySetupWizardFinishPage::setProgress(const QString &status, int progress)
{
if (progress < 0) {
m_ui->progressBar->hide();
m_ui->statusLabel->clear();
return;
} else if (!m_ui->progressBar->isVisible()) {
m_ui->progressBar->show();
}
m_ui->statusLabel->setText(status);
m_ui->progressBar->setValue(progress);
}
<|endoftext|> |
<commit_before>/* gdnet_peer.cpp */
#include "gdnet_peer.h"
GDNetPeer::GDNetPeer(GDNetHost* host, ENetPeer* peer) : _host(host), _peer(peer) {
_host->reference();
}
GDNetPeer::~GDNetPeer() {
_host->unreference();
}
int GDNetPeer::get_peer_id() {
ERR_FAIL_COND_V(_host->_host == NULL, -1);
return (int)(_peer - _host->_host->peers);
}
Ref<GDNetAddress> GDNetPeer::get_address() {
Ref<GDNetAddress> address = memnew(GDNetAddress);
address->set_port(_peer->address.port);
char ip[64];
enet_address_get_host_ip(&_peer->address, ip, 64);
address->set_host(ip);
return address;
}
void GDNetPeer::ping() {
ERR_FAIL_COND(_host->_host == NULL);
_host->_mutex->lock();
enet_peer_ping(_peer);
_host->_mutex->unlock();
}
void GDNetPeer::reset() {
ERR_FAIL_COND(_host->_host == NULL);
_host->_mutex->lock();
enet_peer_reset(_peer);
_host->_mutex->unlock();
}
void GDNetPeer::disconnect(int data) {
ERR_FAIL_COND(_host->_host == NULL);
_host->_mutex->lock();
enet_peer_disconnect(_peer, data);
_host->_mutex->unlock();
}
void GDNetPeer::disconnect_later(int data) {
ERR_FAIL_COND(_host->_host == NULL);
_host->_mutex->lock();
enet_peer_disconnect_later(_peer, data);
_host->_mutex->unlock();
}
void GDNetPeer::disconnect_now(int data) {
ERR_FAIL_COND(_host->_host == NULL);
_host->_mutex->lock();
enet_peer_disconnect_now(_peer, data);
_host->_mutex->unlock();
}
void GDNetPeer::send_packet(const ByteArray& packet, int channel_id, int type) {
ERR_FAIL_COND(_host->_host == NULL);
GDNetMessage* message = memnew(GDNetMessage((GDNetMessage::Type)type));
message->set_peer_id(get_peer_id());
message->set_channel_id(channel_id);
message->set_packet(packet);
_host->_message_queue.push(message);
}
void GDNetPeer::send_var(const Variant& var, int channel_id, int type) {
ERR_FAIL_COND(_host->_host == NULL);
int len;
Error err = encode_variant(var, NULL, len);
ERR_FAIL_COND(err != OK || len == 0);
GDNetMessage* message = memnew(GDNetMessage((GDNetMessage::Type)type));
message->set_peer_id(get_peer_id());
message->set_channel_id(channel_id);
ByteArray packet;
packet.resize(len);
ByteArray::Write w = packet.write();
err = encode_variant(var, w.ptr(), len);
ERR_FAIL_COND(err != OK);
message->set_packet(packet);
_host->_message_queue.push(message);
}
void GDNetPeer::_bind_methods() {
ObjectTypeDB::bind_method("get_peer_id",&GDNetPeer::get_peer_id);
ObjectTypeDB::bind_method("get_address",&GDNetPeer::get_address);
ObjectTypeDB::bind_method("ping",&GDNetPeer::ping);
ObjectTypeDB::bind_method("reset",&GDNetPeer::reset);
ObjectTypeDB::bind_method("disconnect",&GDNetPeer::disconnect,DEFVAL(0));
ObjectTypeDB::bind_method("disconnect_later",&GDNetPeer::disconnect_later,DEFVAL(0));
ObjectTypeDB::bind_method("disconnect_now",&GDNetPeer::disconnect_now,DEFVAL(0));
ObjectTypeDB::bind_method("send_packet",&GDNetPeer::send_packet,DEFVAL(0),DEFVAL(GDNetMessage::UNSEQUENCED));
ObjectTypeDB::bind_method("send_var",&GDNetPeer::send_var,DEFVAL(0),DEFVAL(GDNetMessage::UNSEQUENCED));
}
<commit_msg>Fixed peer commands.<commit_after>/* gdnet_peer.cpp */
#include "gdnet_peer.h"
GDNetPeer::GDNetPeer(GDNetHost* host, ENetPeer* peer) : _host(host), _peer(peer) {
_host->reference();
}
GDNetPeer::~GDNetPeer() {
_host->unreference();
}
int GDNetPeer::get_peer_id() {
ERR_FAIL_COND_V(_host->_host == NULL, -1);
return (int)(_peer - _host->_host->peers);
}
Ref<GDNetAddress> GDNetPeer::get_address() {
Ref<GDNetAddress> address = memnew(GDNetAddress);
address->set_port(_peer->address.port);
char ip[64];
enet_address_get_host_ip(&_peer->address, ip, 64);
address->set_host(ip);
return address;
}
void GDNetPeer::ping() {
ERR_FAIL_COND(_host->_host == NULL);
while (true) {
if (_host->_mutex->try_lock() == 0) {
enet_peer_ping(_peer);
_host->_mutex->unlock();
break;
}
}
}
void GDNetPeer::reset() {
ERR_FAIL_COND(_host->_host == NULL);
while (true) {
if (_host->_mutex->try_lock() == 0) {
enet_peer_reset(_peer);
_host->_mutex->unlock();
break;
}
}
}
void GDNetPeer::disconnect(int data) {
ERR_FAIL_COND(_host->_host == NULL);
while (true) {
if (_host->_mutex->try_lock() == 0) {
enet_peer_disconnect(_peer, data);
_host->_mutex->unlock();
break;
}
}
}
void GDNetPeer::disconnect_later(int data) {
ERR_FAIL_COND(_host->_host == NULL);
while (true) {
if (_host->_mutex->try_lock() == 0) {
enet_peer_disconnect_later(_peer, data);
_host->_mutex->unlock();
break;
}
}
}
void GDNetPeer::disconnect_now(int data) {
ERR_FAIL_COND(_host->_host == NULL);
while (true) {
if (_host->_mutex->try_lock() == 0) {
enet_peer_disconnect_now(_peer, data);
_host->_mutex->unlock();
break;
}
}
}
void GDNetPeer::send_packet(const ByteArray& packet, int channel_id, int type) {
ERR_FAIL_COND(_host->_host == NULL);
GDNetMessage* message = memnew(GDNetMessage((GDNetMessage::Type)type));
message->set_peer_id(get_peer_id());
message->set_channel_id(channel_id);
message->set_packet(packet);
_host->_message_queue.push(message);
}
void GDNetPeer::send_var(const Variant& var, int channel_id, int type) {
ERR_FAIL_COND(_host->_host == NULL);
int len;
Error err = encode_variant(var, NULL, len);
ERR_FAIL_COND(err != OK || len == 0);
GDNetMessage* message = memnew(GDNetMessage((GDNetMessage::Type)type));
message->set_peer_id(get_peer_id());
message->set_channel_id(channel_id);
ByteArray packet;
packet.resize(len);
ByteArray::Write w = packet.write();
err = encode_variant(var, w.ptr(), len);
ERR_FAIL_COND(err != OK);
message->set_packet(packet);
_host->_message_queue.push(message);
}
void GDNetPeer::_bind_methods() {
ObjectTypeDB::bind_method("get_peer_id",&GDNetPeer::get_peer_id);
ObjectTypeDB::bind_method("get_address",&GDNetPeer::get_address);
ObjectTypeDB::bind_method("ping",&GDNetPeer::ping);
ObjectTypeDB::bind_method("reset",&GDNetPeer::reset);
ObjectTypeDB::bind_method("disconnect",&GDNetPeer::disconnect,DEFVAL(0));
ObjectTypeDB::bind_method("disconnect_later",&GDNetPeer::disconnect_later,DEFVAL(0));
ObjectTypeDB::bind_method("disconnect_now",&GDNetPeer::disconnect_now,DEFVAL(0));
ObjectTypeDB::bind_method("send_packet",&GDNetPeer::send_packet,DEFVAL(0),DEFVAL(GDNetMessage::UNSEQUENCED));
ObjectTypeDB::bind_method("send_var",&GDNetPeer::send_var,DEFVAL(0),DEFVAL(GDNetMessage::UNSEQUENCED));
}
<|endoftext|> |
<commit_before>// Copyright (c) 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 <cassert>
#include <cstddef>
#include <iomanip>
#include <map>
#include <sstream>
#include <string>
#include "jit.h"
#include "jump-x86.h"
#include "plugin.h"
#include "version.h"
#ifdef WIN32
#include <Windows.h>
#else
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1 // for dladdr()
#endif
#include <dlfcn.h>
#endif
extern void *pAMXFunctions;
typedef void (*logprintf_t)(const char *format, ...);
static logprintf_t logprintf;
typedef std::map<AMX*, jit::Jitter*> AmxToJitterMap;
static AmxToJitterMap amx2jitter;
static JumpX86 amx_Exec_hook;
static cell *opcodeTable = 0;
static int AMXAPI amx_Exec_JIT(AMX *amx, cell *retval, int index) {
#if defined __GNUC__ && !defined WIN32
if ((amx->flags & AMX_FLAG_BROWSE) == AMX_FLAG_BROWSE) {
assert(::opcodeTable != 0);
*retval = reinterpret_cast<cell>(::opcodeTable);
return AMX_ERR_NONE;
}
#endif
AmxToJitterMap::iterator iterator = ::amx2jitter.find(amx);
if (iterator == ::amx2jitter.end()) {
// Compilation previously failed, call normal amx_Exec().
JumpX86::ScopedRemove r(&amx_Exec_hook);
return amx_Exec(amx, retval, index);
} else {
jit::Jitter *jitter = iterator->second;
return jitter->exec(index, retval);
}
}
static std::string GetModuleNameBySymbol(void *symbol) {
char module[FILENAME_MAX] = "";
if (symbol != 0) {
#ifdef WIN32
MEMORY_BASIC_INFORMATION mbi;
VirtualQuery(symbol, &mbi, sizeof(mbi));
GetModuleFileName((HMODULE)mbi.AllocationBase, module, FILENAME_MAX);
#else
Dl_info info;
dladdr(symbol, &info);
strcpy(module, info.dli_fname);
#endif
}
return std::string(module);
}
static std::string GetFileName(const std::string &path) {
std::string::size_type lastSep = path.find_last_of("/\\");
if (lastSep != std::string::npos) {
return path.substr(lastSep + 1);
}
return path;
}
static std::string InstrToString(const jit::AmxInstruction &instr) {
std::stringstream ss;
const char *name = instr.getName();
if (name != 0) {
ss << instr.getName();
} else {
ss << std::setw(8) << std::setfill('0') << std::hex << instr.getOpcode();
}
std::vector<cell> opers = instr.getOperands();
for (std::vector<cell>::const_iterator it = opers.begin(); it != opers.end(); ++it) {
ss << ' ' << std::setw(8) << std::setfill('0') << std::hex << *it;
}
return ss.str();
}
static void CompileError(const jit::AmxVm &vm, const jit::AmxInstruction &instr) {
logprintf("JIT failed to compile instruction at %08x:", instr.getAddress());
logprintf(" %s", InstrToString(instr).c_str());
}
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
pAMXFunctions = reinterpret_cast<void*>(ppData[PLUGIN_DATA_AMX_EXPORTS]);
void *funAddr = JumpX86::GetTargetAddress(((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec]);
if (funAddr != 0) {
std::string module = GetFileName(GetModuleNameBySymbol(funAddr));
if (!module.empty() && module != "samp-server.exe" && module != "samp03svr") {
logprintf(" JIT must be loaded before %s", module.c_str());
return false;
}
}
logprintf(" JIT plugin v%s is OK.", PLUGIN_VERSION_STRING);
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL Unload() {
for (AmxToJitterMap::iterator it = amx2jitter.begin(); it != amx2jitter.end(); ++it) {
delete it->second;
}
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
typedef int (AMXAPI *amx_Exec_t)(AMX *amx, cell *retval, int index);
amx_Exec_t amx_Exec = (amx_Exec_t)((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec];
typedef int (AMXAPI *amx_GetAddr_t)(AMX *amx, cell amx_addr, cell **phys_addr);
amx_GetAddr_t amx_GetAddr = (amx_GetAddr_t)((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_GetAddr];
#if defined __GNUC__ && !defined WIN32
// Get opcode list before we hook amx_Exec().
if (::opcodeTable == 0) {
amx->flags |= AMX_FLAG_BROWSE;
amx_Exec(amx, reinterpret_cast<cell*>(&::opcodeTable), 0);
amx->flags &= ~AMX_FLAG_BROWSE;
}
#endif
jit::Jitter *jitter = new jit::Jitter(amx, ::opcodeTable);
if (!jitter->compile(CompileError)) {
delete jitter;
} else {
::amx2jitter.insert(std::make_pair(amx, jitter));
}
if (!amx_Exec_hook.IsInstalled()) {
amx_Exec_hook.Install(
(void*)amx_Exec,
(void*)amx_Exec_JIT);
}
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
AmxToJitterMap::iterator it = amx2jitter.find(amx);
if (it != amx2jitter.end()) {
delete it->second;
amx2jitter.erase(it);
}
return AMX_ERR_NONE;
}
<commit_msg>Make JIT report runtime errors<commit_after>// Copyright (c) 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 <cassert>
#include <cstddef>
#include <iomanip>
#include <map>
#include <sstream>
#include <string>
#include <amx/amx.h>
#include "jit.h"
#include "jump-x86.h"
#include "plugin.h"
#include "version.h"
#ifdef WIN32
#include <Windows.h>
#else
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1 // for dladdr()
#endif
#include <dlfcn.h>
#endif
extern void *pAMXFunctions;
typedef void (*logprintf_t)(const char *format, ...);
static logprintf_t logprintf;
typedef std::map<AMX*, jit::Jitter*> AmxToJitterMap;
static AmxToJitterMap amx2jitter;
static JumpX86 amx_Exec_hook;
static cell *opcodeTable = 0;
static std::string InstrToString(const jit::AmxInstruction &instr) {
std::stringstream stream;
if (instr.getName() != 0) {
stream << instr.getName();
} else {
stream << std::setw(8) << std::setfill('0') << std::hex << instr.getOpcode();
}
std::vector<cell> opers = instr.getOperands();
for (std::vector<cell>::const_iterator it = opers.begin(); it != opers.end(); ++it) {
stream << ' ' << std::setw(8) << std::setfill('0') << std::hex << *it;
}
return stream.str();
}
static void CompileError(const jit::AmxVm &vm, const jit::AmxInstruction &instr) {
logprintf("JIT compilation error at %08x:", instr.getAddress());
logprintf(" %s", InstrToString(instr).c_str());
}
static void RuntimeError(int errorCode) {
static const char *errorStrings[] = {
/* AMX_ERR_NONE */ "(none)",
/* AMX_ERR_EXIT */ "Forced exit",
/* AMX_ERR_ASSERT */ "Assertion failed",
/* AMX_ERR_STACKERR */ "Stack/heap collision (insufficient stack size)",
/* AMX_ERR_BOUNDS */ "Array index out of bounds",
/* AMX_ERR_MEMACCESS */ "Invalid memory access",
/* AMX_ERR_INVINSTR */ "Invalid instruction",
/* AMX_ERR_STACKLOW */ "Stack underflow",
/* AMX_ERR_HEAPLOW */ "Heap underflow",
/* AMX_ERR_CALLBACK */ "No (valid) native function callback",
/* AMX_ERR_NATIVE */ "Native function failed",
/* AMX_ERR_DIVIDE */ "Divide by zero",
/* AMX_ERR_SLEEP */ "(sleep mode)",
/* 13 */ "(reserved)",
/* 14 */ "(reserved)",
/* 15 */ "(reserved)",
/* AMX_ERR_MEMORY */ "Out of memory",
/* AMX_ERR_FORMAT */ "Invalid/unsupported P-code file format",
/* AMX_ERR_VERSION */ "File is for a newer version of the AMX",
/* AMX_ERR_NOTFOUND */ "File or function is not found",
/* AMX_ERR_INDEX */ "Invalid index parameter (bad entry point)",
/* AMX_ERR_DEBUG */ "Debugger cannot run",
/* AMX_ERR_INIT */ "AMX not initialized (or doubly initialized)",
/* AMX_ERR_USERDATA */ "Unable to set user data field (table full)",
/* AMX_ERR_INIT_JIT */ "Cannot initialize the JIT",
/* AMX_ERR_PARAMS */ "Parameter error",
/* AMX_ERR_DOMAIN */ "Domain error, expression result does not fit in range",
/* AMX_ERR_GENERAL */ "General error (unknown or unspecific error)"
};
logprintf("JIT runtime error %d: \"%s\"", errorCode, errorStrings[errorCode]);
}
static int AMXAPI amx_Exec_JIT(AMX *amx, cell *retval, int index) {
#if defined __GNUC__ && !defined WIN32
if ((amx->flags & AMX_FLAG_BROWSE) == AMX_FLAG_BROWSE) {
assert(::opcodeTable != 0);
*retval = reinterpret_cast<cell>(::opcodeTable);
return AMX_ERR_NONE;
}
#endif
AmxToJitterMap::iterator iterator = ::amx2jitter.find(amx);
if (iterator == ::amx2jitter.end()) {
// Compilation previously failed, call normal amx_Exec().
JumpX86::ScopedRemove r(&amx_Exec_hook);
return amx_Exec(amx, retval, index);
} else {
jit::Jitter *jitter = iterator->second;
int error = jitter->exec(index, retval);
if (error != AMX_ERR_NONE) {
RuntimeError(error);
}
return error;
}
}
static std::string GetModuleNameBySymbol(void *symbol) {
char module[FILENAME_MAX] = "";
if (symbol != 0) {
#ifdef WIN32
MEMORY_BASIC_INFORMATION mbi;
VirtualQuery(symbol, &mbi, sizeof(mbi));
GetModuleFileName((HMODULE)mbi.AllocationBase, module, FILENAME_MAX);
#else
Dl_info info;
dladdr(symbol, &info);
strcpy(module, info.dli_fname);
#endif
}
return std::string(module);
}
static std::string GetFileName(const std::string &path) {
std::string::size_type lastSep = path.find_last_of("/\\");
if (lastSep != std::string::npos) {
return path.substr(lastSep + 1);
}
return path;
}
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
pAMXFunctions = reinterpret_cast<void*>(ppData[PLUGIN_DATA_AMX_EXPORTS]);
void *funAddr = JumpX86::GetTargetAddress(((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec]);
if (funAddr != 0) {
std::string module = GetFileName(GetModuleNameBySymbol(funAddr));
if (!module.empty() && module != "samp-server.exe" && module != "samp03svr") {
logprintf(" JIT must be loaded before %s", module.c_str());
return false;
}
}
logprintf(" JIT plugin v%s is OK.", PLUGIN_VERSION_STRING);
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL Unload() {
for (AmxToJitterMap::iterator it = amx2jitter.begin(); it != amx2jitter.end(); ++it) {
delete it->second;
}
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
typedef int (AMXAPI *amx_Exec_t)(AMX *amx, cell *retval, int index);
amx_Exec_t amx_Exec = (amx_Exec_t)((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec];
typedef int (AMXAPI *amx_GetAddr_t)(AMX *amx, cell amx_addr, cell **phys_addr);
amx_GetAddr_t amx_GetAddr = (amx_GetAddr_t)((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_GetAddr];
#if defined __GNUC__ && !defined WIN32
// Get opcode list before we hook amx_Exec().
if (::opcodeTable == 0) {
amx->flags |= AMX_FLAG_BROWSE;
amx_Exec(amx, reinterpret_cast<cell*>(&::opcodeTable), 0);
amx->flags &= ~AMX_FLAG_BROWSE;
}
#endif
jit::Jitter *jitter = new jit::Jitter(amx, ::opcodeTable);
if (!jitter->compile(CompileError)) {
delete jitter;
} else {
::amx2jitter.insert(std::make_pair(amx, jitter));
}
if (!amx_Exec_hook.IsInstalled()) {
amx_Exec_hook.Install(
(void*)amx_Exec,
(void*)amx_Exec_JIT);
}
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
AmxToJitterMap::iterator it = amx2jitter.find(amx);
if (it != amx2jitter.end()) {
delete it->second;
amx2jitter.erase(it);
}
return AMX_ERR_NONE;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <unistd.h>
#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "gk_utils.h"
#include "gk_types.h"
#include "gk_functions.h"
#include "gk_operators.h"
#include "gk_Worker.h"
using std::cout; using std::endl; using std::string;
using namespace cv;
//using cv::CommandLineParser; using cv::Mat;
using namespace gekon;
static void help()
{
cout << "Usage: gekon [PARAMETER] [ORIGNAL IMAGE] [MODIFIED IMAGE]" << endl << endl;
cout << "All parameters are mandatory." << endl;
cout << "PARAMETER is size of convolution matrix" << endl;
cout << "ORIGINAL IMAGE is image before modification" << endl;
cout << "MODIFIED IMAGE is image after modification" << endl << endl;
cout << "Example of usage: ./gekon 3 lena.jpg lena-mod.jpg" << endl << endl;
cout << "Authors: Vojtech Vladyka <vojtech.vladyka@gmail.com> and Martin Sehnoutka <>" << endl;
cout << "Department of Automation and Measurement, FEEC BUT, 2016" << endl;
}
const char* keys =
{
"{help h||}{@convSize|3|convolution size}{@original|lena.jpg|original image name}{@modified|lena.mod.jpg|modiifed image name}"
};
int main(int argc, char **argv) {
srand ((unsigned int)time(NULL));
cout << "GeKon" << endl;
CommandLineParser parser(argc, argv, keys);
if (parser.has("help"))
{
help();
return 0;
}
string original = parser.get<string>(1);
string modified = parser.get<string>(2);
int convSize = parser.get<int>(0);
cout << "Convolution matrix size: " << convSize << endl;
cout << "Original image: " << original << endl;
cout << "Modified image: " << modified << endl;
Mat_<ker_num_t > mod_img;
Mat i1 = imread(modified, CV_LOAD_IMAGE_GRAYSCALE);
i1.convertTo(mod_img, KERNEL_TYPE, 1/255.0);
Mat_<ker_num_t > orig_img;
Mat i2 = imread(original, CV_LOAD_IMAGE_GRAYSCALE);
i2.convertTo(orig_img, KERNEL_TYPE, 1/255.0);
imshow("Image", i1);
cv::waitKey(0);
imshow("Image", i2);
cv::waitKey(0);
imshow("Image", mod_img);
cv::waitKey(0);
imshow("Image", orig_img);
cv::waitKey(0);
if (!mod_img.data || !orig_img.data)
{
cout << "Error while reading training samples." << endl;
return -1;
}
// init gekon here
cv::theRNG().state = time(NULL); //random seed for opencv. Need to be initialized for each thread.
tr_sample_t sample = {
.original = orig_img,
.modified = mod_img
};
Worker the_gekon(10,convSize);
the_gekon.setTrSample(sample);
std::vector<double> fitPlot;
// test inputs
// run!
for (int j = 0; j < 40; ++j) {
auto ret = the_gekon.run();
cout << endl << ">>>>MAIN:" << ret << endl << endl;
fitPlot.push_back(ret);
}
plot_graph(fitPlot, "Fitness");
auto sol = the_gekon.retBestSolution();
cout << sol << endl;
Mat conv_result;
filter2D(sample.original, conv_result, -1, sol, cv::Point(-1, -1), 0, cv::BORDER_CONSTANT);
auto w_sol = the_gekon.retWorstSolution();
cout << w_sol << endl;
Mat conv_result2;
filter2D(sample.original, conv_result2, -1, w_sol, cv::Point(-1, -1), 0, cv::BORDER_CONSTANT);
imshow("Image", sample.modified);
cv::waitKey(0);
imshow("Image", conv_result);
cv::waitKey(0);
imshow("Image", conv_result2);
cv::waitKey(0);
cout << "Bye!" << endl;
return 0;
}
<commit_msg>Fixed struct initialization according c++<commit_after>#include <iostream>
#include <unistd.h>
#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "gk_utils.h"
#include "gk_types.h"
#include "gk_functions.h"
#include "gk_operators.h"
#include "gk_Worker.h"
using std::cout; using std::endl; using std::string;
using namespace cv;
//using cv::CommandLineParser; using cv::Mat;
using namespace gekon;
static void help()
{
cout << "Usage: gekon [PARAMETER] [ORIGNAL IMAGE] [MODIFIED IMAGE]" << endl << endl;
cout << "All parameters are mandatory." << endl;
cout << "PARAMETER is size of convolution matrix" << endl;
cout << "ORIGINAL IMAGE is image before modification" << endl;
cout << "MODIFIED IMAGE is image after modification" << endl << endl;
cout << "Example of usage: ./gekon 3 lena.jpg lena-mod.jpg" << endl << endl;
cout << "Authors: Vojtech Vladyka <vojtech.vladyka@gmail.com> and Martin Sehnoutka <>" << endl;
cout << "Department of Automation and Measurement, FEEC BUT, 2016" << endl;
}
const char* keys =
{
"{help h||}{@convSize|3|convolution size}{@original|lena.jpg|original image name}{@modified|lena.mod.jpg|modiifed image name}"
};
int main(int argc, char **argv) {
srand ((unsigned int)time(NULL));
cout << "GeKon" << endl;
CommandLineParser parser(argc, argv, keys);
if (parser.has("help"))
{
help();
return 0;
}
string original = parser.get<string>(1);
string modified = parser.get<string>(2);
int convSize = parser.get<int>(0);
cout << "Convolution matrix size: " << convSize << endl;
cout << "Original image: " << original << endl;
cout << "Modified image: " << modified << endl;
Mat_<ker_num_t > mod_img;
Mat i1 = imread(modified, CV_LOAD_IMAGE_GRAYSCALE);
i1.convertTo(mod_img, KERNEL_TYPE, 1/255.0);
Mat_<ker_num_t > orig_img;
Mat i2 = imread(original, CV_LOAD_IMAGE_GRAYSCALE);
i2.convertTo(orig_img, KERNEL_TYPE, 1/255.0);
imshow("Image", i1);
cv::waitKey(0);
imshow("Image", i2);
cv::waitKey(0);
imshow("Image", mod_img);
cv::waitKey(0);
imshow("Image", orig_img);
cv::waitKey(0);
if (!mod_img.data || !orig_img.data)
{
cout << "Error while reading training samples." << endl;
return -1;
}
// init gekon here
cv::theRNG().state = time(NULL); //random seed for opencv. Need to be initialized for each thread.
tr_sample_t sample = {
orig_img,
mod_img
};
Worker the_gekon(10,convSize);
the_gekon.setTrSample(sample);
std::vector<double> fitPlot;
// test inputs
// run!
for (int j = 0; j < 40; ++j) {
auto ret = the_gekon.run();
cout << endl << ">>>>MAIN:" << ret << endl << endl;
fitPlot.push_back(ret);
}
plot_graph(fitPlot, "Fitness");
auto sol = the_gekon.retBestSolution();
cout << sol << endl;
Mat conv_result;
filter2D(sample.original, conv_result, -1, sol, cv::Point(-1, -1), 0, cv::BORDER_CONSTANT);
auto w_sol = the_gekon.retWorstSolution();
cout << w_sol << endl;
Mat conv_result2;
filter2D(sample.original, conv_result2, -1, w_sol, cv::Point(-1, -1), 0, cv::BORDER_CONSTANT);
imshow("Image", sample.modified);
cv::waitKey(0);
imshow("Image", conv_result);
cv::waitKey(0);
imshow("Image", conv_result2);
cv::waitKey(0);
cout << "Bye!" << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (C) 2016 ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* 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 <deque>
#include <unordered_set>
#include <seastar/util/lazy.hh>
#include "mutation.hh"
#include "utils/UUID_gen.hh"
#include "tracing/tracing.hh"
#include "gms/inet_address.hh"
namespace tracing {
class trace_state final {
using clock_type = std::chrono::steady_clock;
private:
utils::UUID _session_id;
trace_type _type;
bool _write_on_close;
// Used for calculation of time passed since the beginning of a tracing
// session till each tracing event.
clock_type::time_point _start;
gc_clock::duration _ttl;
// TRUE for a primary trace_state object
bool _primary;
bool _tracing_began = false;
std::chrono::system_clock::rep _started_at;
gms::inet_address _client;
sstring _request;
int _pending_trace_events = 0;
shared_ptr<tracing> _local_tracing_ptr;
i_tracing_backend_helper& _local_backend;
struct params_values {
std::experimental::optional<std::unordered_set<gms::inet_address>> batchlog_endpoints;
std::experimental::optional<api::timestamp_type> user_timestamp;
std::experimental::optional<sstring> query;
std::experimental::optional<db::consistency_level> cl;
std::experimental::optional<db::consistency_level> serial_cl;
std::experimental::optional<int32_t> page_size;
};
class params_ptr {
private:
std::unique_ptr<params_values> _vals;
params_values* get_ptr_safe() {
if (!_vals) {
_vals = std::make_unique<params_values>();
}
return _vals.get();
}
public:
explicit operator bool() const {
return (bool)_vals;
}
params_values* operator->() {
return get_ptr_safe();
}
params_values& operator*() {
return *get_ptr_safe();
}
} _params_ptr;
public:
trace_state(trace_type type, bool write_on_close, const std::experimental::optional<utils::UUID>& session_id = std::experimental::nullopt)
: _session_id(session_id ? *session_id : utils::UUID_gen::get_time_UUID())
, _type(type)
, _write_on_close(write_on_close)
, _ttl(ttl_by_type(_type))
, _primary(!session_id)
, _local_tracing_ptr(tracing::get_local_tracing_instance().shared_from_this())
, _local_backend(_local_tracing_ptr->backend_helper())
{ }
~trace_state();
const utils::UUID& get_session_id() const {
return _session_id;
}
trace_type get_type() const {
return _type;
}
bool get_write_on_close() const {
return _write_on_close;
}
private:
/**
* Returns the number of microseconds passed since the beginning of this
* tracing session.
*
* @return number of microseconds passed since the beginning of this session
*/
inline int elapsed();
/**
* Initiates a tracing session.
*
* Starts the tracing session time measurments.
* This overload is meant for secondary sessions.
*/
void begin() {
std::atomic_signal_fence(std::memory_order::memory_order_seq_cst);
_start = clock_type::now();
std::atomic_signal_fence(std::memory_order::memory_order_seq_cst);
_tracing_began = true;
}
/**
* Initiates a tracing session.
*
* Starts the tracing session time measurments.
* This overload is meant for primary sessions.
*
* @param request description of a request being traces
* @param client address of a client the traced request came from
*/
void begin(sstring request, gms::inet_address client) {
begin();
_started_at = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
_request = std::move(request);
_client = std::move(client);
}
template <typename Func>
void begin(const seastar::lazy_eval<Func>& lf, gms::inet_address client) {
begin(lf(), client);
}
/**
* Stores a batchlog endpoints.
*
* This value will eventually be stored in a params<string, string> map of a tracing session
* with a 'batchlog_endpoints' key.
*
* @param val the set of batchlog endpoints
*/
void set_batchlog_endpoints(const std::unordered_set<gms::inet_address>& val) {
_params_ptr->batchlog_endpoints.emplace(val);
}
/**
* Stores a consistency level of a query being traced.
*
* This value will eventually be stored in a params<string, string> map of a tracing session
* with a 'consistency_level' key.
*
* @param val the consistency level
*/
void set_consistency_level(db::consistency_level val) {
_params_ptr->cl.emplace(val);
}
/**
* Stores an optional serial consistency level of a query being traced.
*
* This value will eventually be stored in a params<string, string> map of a tracing session
* with a 'serial_consistency_level' key.
*
* @param val the optional value with a serial consistency level
*/
void set_optional_serial_consistency_level(const std::experimental::optional<db::consistency_level>& val) {
if (val) {
_params_ptr->serial_cl.emplace(*val);
}
}
/**
* Stores a page size of a query being traced.
*
* This value will eventually be stored in a params<string, string> map of a tracing session
* with a 'page_size' key.
*
* @param val the PAGE size
*/
void set_page_size(int32_t val) {
if (val > 0) {
_params_ptr->page_size.emplace(val);
}
}
/**
* Store a query string.
*
* This value will eventually be stored in a params<string, string> map of a tracing session
* with a 'query' key.
*
* @param val the query string
*/
void set_query(const sstring& val) {
_params_ptr->query.emplace(val);
}
/**
* Store a user provided timestamp.
*
* This value will eventually be stored in a params<string, string> map of a tracing session
* with a 'user_timestamp' key.
*
* @param val the timestamp
*/
void set_user_timestamp(api::timestamp_type val) {
_params_ptr->user_timestamp.emplace(val);
}
std::unordered_map<sstring, sstring> get_params();
/**
* Add a single trace entry - a special case for a simple string.
*
* @param msg trace message
*/
inline void trace(sstring msg);
inline void trace(const char* msg) {
trace(sstring(msg));
}
/**
* Add a single trace entry - printf-like version
*
* Add a single trace entry with a message given in a printf-like way:
* format string with positional parameters.
*
* @note Both format string and positional parameters are going to be copied
* and the final string is going to built later. A caller has to take this
* into an account and make sure that positional parameters are both
* copiable and that their copying is not expensive.
*
* @tparam A
* @param fmt format string
* @param a positional parameters
*/
template <typename... A>
inline void trace(const char* fmt, A&&... a);
template <typename... A>
friend void begin(const trace_state_ptr& p, A&&... a);
template <typename... A>
friend void trace(const trace_state_ptr& p, A&&... a);
friend void set_page_size(const trace_state_ptr& p, int32_t val);
friend void set_batchlog_endpoints(const trace_state_ptr& p, const std::unordered_set<gms::inet_address>& val);
friend void set_consistency_level(const trace_state_ptr& p, db::consistency_level val);
friend void set_optional_serial_consistency_level(const trace_state_ptr& p, const std::experimental::optional<db::consistency_level>&val);
friend void set_query(const trace_state_ptr& p, const sstring& val);
friend void set_user_timestamp(const trace_state_ptr& p, api::timestamp_type val);
};
void trace_state::trace(sstring message) {
if (!_tracing_began) {
throw std::logic_error("trying to use a trace() before begin() for \"" + message + "\" tracepoint");
}
if (_pending_trace_events >= tracing::max_trace_events_per_session) {
return;
}
_local_backend.write_event_record(_session_id, std::move(message), elapsed(), _ttl, i_tracing_backend_helper::wall_clock::now());
++_pending_trace_events;
}
template <typename... A>
void trace_state::trace(const char* fmt, A&&... a) {
try {
fmt::MemoryWriter out;
out.write(fmt, std::forward<A>(a)...);
trace(out.c_str());
} catch (...) {
// Bump up an error counter and ignore
++_local_tracing_ptr->stats.trace_errors;
}
}
int trace_state::elapsed() {
using namespace std::chrono;
std::atomic_signal_fence(std::memory_order::memory_order_seq_cst);
auto elapsed = duration_cast<microseconds>(clock_type::now() - _start).count();
std::atomic_signal_fence(std::memory_order::memory_order_seq_cst);
if (elapsed > std::numeric_limits<int>::max()) {
return std::numeric_limits<int>::max();
}
return elapsed;
}
inline void set_page_size(const trace_state_ptr& p, int32_t val) {
if (p) {
p->set_page_size(val);
}
}
inline void set_batchlog_endpoints(const trace_state_ptr& p, const std::unordered_set<gms::inet_address>& val) {
if (p) {
p->set_batchlog_endpoints(val);
}
}
inline void set_consistency_level(const trace_state_ptr& p, db::consistency_level val) {
if (p) {
p->set_consistency_level(val);
}
}
inline void set_optional_serial_consistency_level(const trace_state_ptr& p, const std::experimental::optional<db::consistency_level>& val) {
if (p) {
p->set_optional_serial_consistency_level(val);
}
}
inline void set_query(const trace_state_ptr& p, const sstring& val) {
if (p) {
p->set_query(val);
}
}
inline void set_user_timestamp(const trace_state_ptr& p, api::timestamp_type val) {
if (p) {
p->set_user_timestamp(val);
}
}
/**
* A helper for conditional invoking trace_state::begin() functions.
*
* If trace state is initialized the operation takes place immediatelly,
* otherwise nothing happens.
*
* @tparam A
* @param p trace state handle
* @param a optional parameters for trace_state::begin()
*/
template <typename... A>
inline void begin(const trace_state_ptr& p, A&&... a) {
if (p) {
p->begin(std::forward<A>(a)...);
}
}
/**
* A helper for conditional invoking trace_state::trace() function.
*
* Create a trace entry if a given trace state @param p is initialized.
* Otherwise, it @param p is not initialized - do nothing.
* Trace message may be passed as a printf-like format string with the
* corresponding positional parameters.
*
* If @param p is initialized both trace message string and positional
* parameters are going to be copied and the final string is going to be build
* later. Therefore a caller has to take this into an account and make sure
* that positional parameters are both copiable and that the copy is not
* expensive.
*
* @param A
* @param p trace state handle
* @param a trace message format string with optional parameters
*/
template <typename... A>
inline void trace(const trace_state_ptr& p, A&&... a) {
if (p) {
p->trace(std::forward<A>(a)...);
}
}
inline std::experimental::optional<trace_info> make_trace_info(const trace_state_ptr& state) {
if (state) {
return trace_info{state->get_session_id(), state->get_type(), state->get_write_on_close()};
}
return std::experimental::nullopt;
}
}
<commit_msg>tracing: use seastar::format() for formatted trace()<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (C) 2016 ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* 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 <deque>
#include <unordered_set>
#include <seastar/util/lazy.hh>
#include "mutation.hh"
#include "utils/UUID_gen.hh"
#include "tracing/tracing.hh"
#include "gms/inet_address.hh"
namespace tracing {
class trace_state final {
using clock_type = std::chrono::steady_clock;
private:
utils::UUID _session_id;
trace_type _type;
bool _write_on_close;
// Used for calculation of time passed since the beginning of a tracing
// session till each tracing event.
clock_type::time_point _start;
gc_clock::duration _ttl;
// TRUE for a primary trace_state object
bool _primary;
bool _tracing_began = false;
std::chrono::system_clock::rep _started_at;
gms::inet_address _client;
sstring _request;
int _pending_trace_events = 0;
shared_ptr<tracing> _local_tracing_ptr;
i_tracing_backend_helper& _local_backend;
struct params_values {
std::experimental::optional<std::unordered_set<gms::inet_address>> batchlog_endpoints;
std::experimental::optional<api::timestamp_type> user_timestamp;
std::experimental::optional<sstring> query;
std::experimental::optional<db::consistency_level> cl;
std::experimental::optional<db::consistency_level> serial_cl;
std::experimental::optional<int32_t> page_size;
};
class params_ptr {
private:
std::unique_ptr<params_values> _vals;
params_values* get_ptr_safe() {
if (!_vals) {
_vals = std::make_unique<params_values>();
}
return _vals.get();
}
public:
explicit operator bool() const {
return (bool)_vals;
}
params_values* operator->() {
return get_ptr_safe();
}
params_values& operator*() {
return *get_ptr_safe();
}
} _params_ptr;
public:
trace_state(trace_type type, bool write_on_close, const std::experimental::optional<utils::UUID>& session_id = std::experimental::nullopt)
: _session_id(session_id ? *session_id : utils::UUID_gen::get_time_UUID())
, _type(type)
, _write_on_close(write_on_close)
, _ttl(ttl_by_type(_type))
, _primary(!session_id)
, _local_tracing_ptr(tracing::get_local_tracing_instance().shared_from_this())
, _local_backend(_local_tracing_ptr->backend_helper())
{ }
~trace_state();
const utils::UUID& get_session_id() const {
return _session_id;
}
trace_type get_type() const {
return _type;
}
bool get_write_on_close() const {
return _write_on_close;
}
private:
/**
* Returns the number of microseconds passed since the beginning of this
* tracing session.
*
* @return number of microseconds passed since the beginning of this session
*/
inline int elapsed();
/**
* Initiates a tracing session.
*
* Starts the tracing session time measurments.
* This overload is meant for secondary sessions.
*/
void begin() {
std::atomic_signal_fence(std::memory_order::memory_order_seq_cst);
_start = clock_type::now();
std::atomic_signal_fence(std::memory_order::memory_order_seq_cst);
_tracing_began = true;
}
/**
* Initiates a tracing session.
*
* Starts the tracing session time measurments.
* This overload is meant for primary sessions.
*
* @param request description of a request being traces
* @param client address of a client the traced request came from
*/
void begin(sstring request, gms::inet_address client) {
begin();
_started_at = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
_request = std::move(request);
_client = std::move(client);
}
template <typename Func>
void begin(const seastar::lazy_eval<Func>& lf, gms::inet_address client) {
begin(lf(), client);
}
/**
* Stores a batchlog endpoints.
*
* This value will eventually be stored in a params<string, string> map of a tracing session
* with a 'batchlog_endpoints' key.
*
* @param val the set of batchlog endpoints
*/
void set_batchlog_endpoints(const std::unordered_set<gms::inet_address>& val) {
_params_ptr->batchlog_endpoints.emplace(val);
}
/**
* Stores a consistency level of a query being traced.
*
* This value will eventually be stored in a params<string, string> map of a tracing session
* with a 'consistency_level' key.
*
* @param val the consistency level
*/
void set_consistency_level(db::consistency_level val) {
_params_ptr->cl.emplace(val);
}
/**
* Stores an optional serial consistency level of a query being traced.
*
* This value will eventually be stored in a params<string, string> map of a tracing session
* with a 'serial_consistency_level' key.
*
* @param val the optional value with a serial consistency level
*/
void set_optional_serial_consistency_level(const std::experimental::optional<db::consistency_level>& val) {
if (val) {
_params_ptr->serial_cl.emplace(*val);
}
}
/**
* Stores a page size of a query being traced.
*
* This value will eventually be stored in a params<string, string> map of a tracing session
* with a 'page_size' key.
*
* @param val the PAGE size
*/
void set_page_size(int32_t val) {
if (val > 0) {
_params_ptr->page_size.emplace(val);
}
}
/**
* Store a query string.
*
* This value will eventually be stored in a params<string, string> map of a tracing session
* with a 'query' key.
*
* @param val the query string
*/
void set_query(const sstring& val) {
_params_ptr->query.emplace(val);
}
/**
* Store a user provided timestamp.
*
* This value will eventually be stored in a params<string, string> map of a tracing session
* with a 'user_timestamp' key.
*
* @param val the timestamp
*/
void set_user_timestamp(api::timestamp_type val) {
_params_ptr->user_timestamp.emplace(val);
}
std::unordered_map<sstring, sstring> get_params();
/**
* Add a single trace entry - a special case for a simple string.
*
* @param msg trace message
*/
inline void trace(sstring msg);
inline void trace(const char* msg) {
trace(sstring(msg));
}
/**
* Add a single trace entry - printf-like version
*
* Add a single trace entry with a message given in a printf-like way:
* format string with positional parameters.
*
* @note Both format string and positional parameters are going to be copied
* and the final string is going to built later. A caller has to take this
* into an account and make sure that positional parameters are both
* copiable and that their copying is not expensive.
*
* @tparam A
* @param fmt format string
* @param a positional parameters
*/
template <typename... A>
inline void trace(const char* fmt, A&&... a);
template <typename... A>
friend void begin(const trace_state_ptr& p, A&&... a);
template <typename... A>
friend void trace(const trace_state_ptr& p, A&&... a);
friend void set_page_size(const trace_state_ptr& p, int32_t val);
friend void set_batchlog_endpoints(const trace_state_ptr& p, const std::unordered_set<gms::inet_address>& val);
friend void set_consistency_level(const trace_state_ptr& p, db::consistency_level val);
friend void set_optional_serial_consistency_level(const trace_state_ptr& p, const std::experimental::optional<db::consistency_level>&val);
friend void set_query(const trace_state_ptr& p, const sstring& val);
friend void set_user_timestamp(const trace_state_ptr& p, api::timestamp_type val);
};
void trace_state::trace(sstring message) {
if (!_tracing_began) {
throw std::logic_error("trying to use a trace() before begin() for \"" + message + "\" tracepoint");
}
if (_pending_trace_events >= tracing::max_trace_events_per_session) {
return;
}
_local_backend.write_event_record(_session_id, std::move(message), elapsed(), _ttl, i_tracing_backend_helper::wall_clock::now());
++_pending_trace_events;
}
template <typename... A>
void trace_state::trace(const char* fmt, A&&... a) {
try {
trace(seastar::format(fmt, std::forward<A>(a)...));
} catch (...) {
// Bump up an error counter and ignore
++_local_tracing_ptr->stats.trace_errors;
}
}
int trace_state::elapsed() {
using namespace std::chrono;
std::atomic_signal_fence(std::memory_order::memory_order_seq_cst);
auto elapsed = duration_cast<microseconds>(clock_type::now() - _start).count();
std::atomic_signal_fence(std::memory_order::memory_order_seq_cst);
if (elapsed > std::numeric_limits<int>::max()) {
return std::numeric_limits<int>::max();
}
return elapsed;
}
inline void set_page_size(const trace_state_ptr& p, int32_t val) {
if (p) {
p->set_page_size(val);
}
}
inline void set_batchlog_endpoints(const trace_state_ptr& p, const std::unordered_set<gms::inet_address>& val) {
if (p) {
p->set_batchlog_endpoints(val);
}
}
inline void set_consistency_level(const trace_state_ptr& p, db::consistency_level val) {
if (p) {
p->set_consistency_level(val);
}
}
inline void set_optional_serial_consistency_level(const trace_state_ptr& p, const std::experimental::optional<db::consistency_level>& val) {
if (p) {
p->set_optional_serial_consistency_level(val);
}
}
inline void set_query(const trace_state_ptr& p, const sstring& val) {
if (p) {
p->set_query(val);
}
}
inline void set_user_timestamp(const trace_state_ptr& p, api::timestamp_type val) {
if (p) {
p->set_user_timestamp(val);
}
}
/**
* A helper for conditional invoking trace_state::begin() functions.
*
* If trace state is initialized the operation takes place immediatelly,
* otherwise nothing happens.
*
* @tparam A
* @param p trace state handle
* @param a optional parameters for trace_state::begin()
*/
template <typename... A>
inline void begin(const trace_state_ptr& p, A&&... a) {
if (p) {
p->begin(std::forward<A>(a)...);
}
}
/**
* A helper for conditional invoking trace_state::trace() function.
*
* Create a trace entry if a given trace state @param p is initialized.
* Otherwise, it @param p is not initialized - do nothing.
* Trace message may be passed as a printf-like format string with the
* corresponding positional parameters.
*
* If @param p is initialized both trace message string and positional
* parameters are going to be copied and the final string is going to be build
* later. Therefore a caller has to take this into an account and make sure
* that positional parameters are both copiable and that the copy is not
* expensive.
*
* @param A
* @param p trace state handle
* @param a trace message format string with optional parameters
*/
template <typename... A>
inline void trace(const trace_state_ptr& p, A&&... a) {
if (p) {
p->trace(std::forward<A>(a)...);
}
}
inline std::experimental::optional<trace_info> make_trace_info(const trace_state_ptr& state) {
if (state) {
return trace_info{state->get_session_id(), state->get_type(), state->get_write_on_close()};
}
return std::experimental::nullopt;
}
}
<|endoftext|> |
<commit_before>/* vim: set sw=4 sts=4 et foldmethod=syntax : */
#include <max_biclique/max_biclique_params.hh>
#include <max_biclique/max_biclique_result.hh>
#include <max_biclique/algorithms.hh>
#include <graph/degree_sort.hh>
#include <boost/program_options.hpp>
#include <iostream>
#include <iomanip>
#include <exception>
#include <algorithm>
#include <random>
#include <thread>
#include <cstdlib>
#include <cmath>
using namespace parasols;
namespace po = boost::program_options;
using std::chrono::steady_clock;
using std::chrono::duration_cast;
using std::chrono::milliseconds;
std::mt19937 rnd;
void table(
int size,
int samples,
const std::vector<std::function<MaxBicliqueResult (const Graph &, const MaxBicliqueParams &)> > & algorithms)
{
using namespace std::placeholders;
for (int p = 1 ; p < 100 ; ++p) {
for (int symmetry = 0 ; symmetry <= 1 ; ++symmetry) {
std::vector<double> omega_average((algorithms.size()));
std::vector<double> time_average((algorithms.size()));
std::vector<double> find_time_average((algorithms.size()));
std::vector<double> prove_time_average((algorithms.size()));
std::vector<double> nodes_average((algorithms.size()));
std::vector<double> find_nodes_average((algorithms.size()));
std::vector<double> prove_nodes_average((algorithms.size()));
std::vector<double> speedup_average((algorithms.size()));
std::vector<std::vector<double> > times((samples));
std::vector<std::vector<double> > speedups((samples));
for (int n = 0 ; n < samples ; ++n) {
Graph graph(size, false);
std::uniform_real_distribution<double> dist(0.0, 1.0);
for (int e = 0 ; e < size ; ++e)
for (int f = e + 1 ; f < size ; ++f)
if (dist(rnd) <= (double(p) / 100.0))
graph.add_edge(e, f);
double baseline = 0.0;
for (unsigned a = 0 ; a < algorithms.size() ; ++a) {
unsigned omega;
{
MaxBicliqueParams params;
params.n_threads = 2;
params.break_ab_symmetry = symmetry;
params.order_function = std::bind(degree_sort, _1, _2, false);
params.start_time = steady_clock::now();
auto result = algorithms.at(a)(graph, params);
auto overall_time = duration_cast<milliseconds>(steady_clock::now() - params.start_time);
omega_average.at(a) += double(result.size) / double(samples);
time_average.at(a) += double(overall_time.count()) / double(samples);
nodes_average.at(a) += double(result.nodes) / double(samples);
times.at(a).push_back(double(overall_time.count()));
omega = result.size;
if (0 == a)
baseline = double(overall_time.count());
speedups.at(a).push_back(baseline / double(overall_time.count()));
speedup_average.at(a) += (baseline / double(overall_time.count())) / samples;
}
{
MaxBicliqueParams params;
params.n_threads = 2;
std::atomic<bool> abort;
abort.store(false);
params.abort = &abort;
params.stop_after_finding = omega;
params.break_ab_symmetry = symmetry;
params.order_function = std::bind(degree_sort, _1, _2, false);
params.start_time = steady_clock::now();
auto result = algorithms.at(a)(graph, params);
auto overall_time = duration_cast<milliseconds>(steady_clock::now() - params.start_time);
find_time_average.at(a) += double(overall_time.count()) / double(samples);
find_nodes_average.at(a) += double(result.nodes) / double(samples);
}
{
MaxBicliqueParams params;
params.n_threads = 2;
std::atomic<bool> abort;
abort.store(false);
params.abort = &abort;
params.initial_bound = omega;
params.break_ab_symmetry = symmetry;
params.order_function = std::bind(degree_sort, _1, _2, false);
params.start_time = steady_clock::now();
auto result = algorithms.at(a)(graph, params);
auto overall_time = duration_cast<milliseconds>(steady_clock::now() - params.start_time);
prove_time_average.at(a) += double(overall_time.count()) / double(samples);
prove_nodes_average.at(a) += double(result.nodes) / double(samples);
}
}
}
if (0 == symmetry)
std::cout << (double(p) / 100.0);
for (unsigned a = 0 ; a < algorithms.size() ; ++a) {
if (0 == a && 0 == symmetry)
std::cout << " " << omega_average.at(a);
double ts = 0.0;
for (int n = 0 ; n < samples ; ++n)
ts += (times.at(a).at(n) - time_average.at(a)) * (times.at(a).at(n) - time_average.at(a));
ts = std::sqrt(ts / samples);
double ss = 0.0;
for (int n = 0 ; n < samples ; ++n)
ss += (speedups.at(a).at(n) - speedup_average.at(a)) * (speedups.at(a).at(n) - speedup_average.at(a));
ss = std::sqrt(ss / samples);
std::cout
<< " " << time_average.at(a)
<< " " << ts
<< " " << speedup_average.at(a)
<< " " << ss
<< " " << find_time_average.at(a)
<< " " << prove_time_average.at(a)
<< " " << nodes_average.at(a)
<< " " << find_nodes_average.at(a)
<< " " << prove_nodes_average.at(a);
}
}
std::cout << std::endl;
}
}
auto main(int argc, char * argv[]) -> int
{
try {
po::options_description display_options{ "Program options" };
display_options.add_options()
("help", "Display help information")
;
po::options_description all_options{ "All options" };
all_options.add(display_options);
all_options.add_options()
("size", po::value<int>(), "Size of graph")
("samples", po::value<int>(), "Sample size")
("algorithm", po::value<std::vector<std::string> >(), "Algorithms")
;
po::positional_options_description positional_options;
positional_options
.add("size", 1)
.add("samples", 1)
.add("algorithm", -1)
;
po::variables_map options_vars;
po::store(po::command_line_parser(argc, argv)
.options(all_options)
.positional(positional_options)
.run(), options_vars);
po::notify(options_vars);
/* --help? Show a message, and exit. */
if (options_vars.count("help")) {
std::cout << "Usage: " << argv[0] << " [options] size samples algorithms..." << std::endl;
std::cout << std::endl;
std::cout << display_options << std::endl;
return EXIT_SUCCESS;
}
/* No values specified? Show a message and exit. */
if (! options_vars.count("size") || ! options_vars.count("samples")) {
std::cout << "Usage: " << argv[0] << " [options] size samples algorithms..." << std::endl;
return EXIT_FAILURE;
}
int size = options_vars["size"].as<int>();
int samples = options_vars["samples"].as<int>();
std::vector<std::function<MaxBicliqueResult (const Graph &, const MaxBicliqueParams &)> > selected_algorithms;
for (auto & s : options_vars["algorithm"].as<std::vector<std::string> >()) {
/* Turn an algorithm string name into a runnable function. */
auto algorithm = max_biclique_algorithms.begin(), algorithm_end = max_biclique_algorithms.end();
for ( ; algorithm != algorithm_end ; ++algorithm)
if (std::get<0>(*algorithm) == s)
break;
if (algorithm == algorithm_end) {
std::cerr << "Unknown algorithm " << s << ", choose from:";
for (auto a : max_biclique_algorithms)
std::cerr << " " << std::get<0>(a);
std::cerr << std::endl;
return EXIT_FAILURE;
}
selected_algorithms.push_back(std::get<1>(*algorithm));
}
table(size, samples, selected_algorithms);
return EXIT_SUCCESS;
}
catch (const po::error & e) {
std::cerr << "Error: " << e.what() << std::endl;
std::cerr << "Try " << argv[0] << " --help" << std::endl;
return EXIT_FAILURE;
}
catch (const std::exception & e) {
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
}
<commit_msg>Fixes<commit_after>/* vim: set sw=4 sts=4 et foldmethod=syntax : */
#include <max_biclique/max_biclique_params.hh>
#include <max_biclique/max_biclique_result.hh>
#include <max_biclique/algorithms.hh>
#include <graph/degree_sort.hh>
#include <boost/program_options.hpp>
#include <iostream>
#include <iomanip>
#include <exception>
#include <algorithm>
#include <random>
#include <thread>
#include <cstdlib>
#include <cmath>
using namespace parasols;
namespace po = boost::program_options;
using std::chrono::steady_clock;
using std::chrono::duration_cast;
using std::chrono::milliseconds;
std::mt19937 rnd;
void table(
int size,
int samples,
const std::vector<std::function<MaxBicliqueResult (const Graph &, const MaxBicliqueParams &)> > & algorithms)
{
using namespace std::placeholders;
for (int p = 1 ; p < 100 ; ++p) {
for (int symmetry = 0 ; symmetry <= 1 ; ++symmetry) {
std::vector<double> omega_average((algorithms.size()));
std::vector<double> time_average((algorithms.size()));
std::vector<double> find_time_average((algorithms.size()));
std::vector<double> prove_time_average((algorithms.size()));
std::vector<double> nodes_average((algorithms.size()));
std::vector<double> find_nodes_average((algorithms.size()));
std::vector<double> prove_nodes_average((algorithms.size()));
std::vector<double> speedup_average((algorithms.size()));
std::vector<std::vector<double> > times((algorithms.size()));
std::vector<std::vector<double> > speedups((algorithms.size()));
for (int n = 0 ; n < samples ; ++n) {
Graph graph(size, false);
std::uniform_real_distribution<double> dist(0.0, 1.0);
for (int e = 0 ; e < size ; ++e)
for (int f = e + 1 ; f < size ; ++f)
if (dist(rnd) <= (double(p) / 100.0))
graph.add_edge(e, f);
double baseline = 0.0;
for (unsigned a = 0 ; a < algorithms.size() ; ++a) {
unsigned omega;
{
MaxBicliqueParams params;
std::atomic<bool> abort;
abort.store(false);
params.abort = &abort;
params.n_threads = 2;
params.break_ab_symmetry = symmetry;
params.order_function = std::bind(degree_sort, _1, _2, false);
params.start_time = steady_clock::now();
auto result = algorithms.at(a)(graph, params);
auto overall_time = duration_cast<milliseconds>(steady_clock::now() - params.start_time);
omega_average.at(a) += double(result.size) / double(samples);
time_average.at(a) += double(overall_time.count()) / double(samples);
nodes_average.at(a) += double(result.nodes) / double(samples);
times.at(a).push_back(double(overall_time.count()));
omega = result.size;
if (0 == a)
baseline = double(overall_time.count());
speedups.at(a).push_back(baseline / double(overall_time.count()));
speedup_average.at(a) += (baseline / double(overall_time.count())) / samples;
}
{
MaxBicliqueParams params;
params.n_threads = 2;
std::atomic<bool> abort;
abort.store(false);
params.abort = &abort;
params.stop_after_finding = omega;
params.break_ab_symmetry = symmetry;
params.order_function = std::bind(degree_sort, _1, _2, false);
params.start_time = steady_clock::now();
auto result = algorithms.at(a)(graph, params);
auto overall_time = duration_cast<milliseconds>(steady_clock::now() - params.start_time);
find_time_average.at(a) += double(overall_time.count()) / double(samples);
find_nodes_average.at(a) += double(result.nodes) / double(samples);
}
{
MaxBicliqueParams params;
params.n_threads = 2;
std::atomic<bool> abort;
abort.store(false);
params.abort = &abort;
params.initial_bound = omega;
params.break_ab_symmetry = symmetry;
params.order_function = std::bind(degree_sort, _1, _2, false);
params.start_time = steady_clock::now();
auto result = algorithms.at(a)(graph, params);
auto overall_time = duration_cast<milliseconds>(steady_clock::now() - params.start_time);
prove_time_average.at(a) += double(overall_time.count()) / double(samples);
prove_nodes_average.at(a) += double(result.nodes) / double(samples);
}
}
}
if (0 == symmetry)
std::cout << (double(p) / 100.0);
for (unsigned a = 0 ; a < algorithms.size() ; ++a) {
if (0 == a && 0 == symmetry)
std::cout << " " << omega_average.at(a);
double ts = 0.0;
for (int n = 0 ; n < samples ; ++n)
ts += (times.at(a).at(n) - time_average.at(a)) * (times.at(a).at(n) - time_average.at(a));
ts = std::sqrt(ts / samples);
double ss = 0.0;
for (int n = 0 ; n < samples ; ++n)
ss += (speedups.at(a).at(n) - speedup_average.at(a)) * (speedups.at(a).at(n) - speedup_average.at(a));
ss = std::sqrt(ss / samples);
std::cout
<< " " << time_average.at(a)
<< " " << ts
<< " " << speedup_average.at(a)
<< " " << ss
<< " " << find_time_average.at(a)
<< " " << prove_time_average.at(a)
<< " " << nodes_average.at(a)
<< " " << find_nodes_average.at(a)
<< " " << prove_nodes_average.at(a);
}
}
std::cout << std::endl;
}
}
auto main(int argc, char * argv[]) -> int
{
try {
po::options_description display_options{ "Program options" };
display_options.add_options()
("help", "Display help information")
;
po::options_description all_options{ "All options" };
all_options.add(display_options);
all_options.add_options()
("size", po::value<int>(), "Size of graph")
("samples", po::value<int>(), "Sample size")
("algorithm", po::value<std::vector<std::string> >(), "Algorithms")
;
po::positional_options_description positional_options;
positional_options
.add("size", 1)
.add("samples", 1)
.add("algorithm", -1)
;
po::variables_map options_vars;
po::store(po::command_line_parser(argc, argv)
.options(all_options)
.positional(positional_options)
.run(), options_vars);
po::notify(options_vars);
/* --help? Show a message, and exit. */
if (options_vars.count("help")) {
std::cout << "Usage: " << argv[0] << " [options] size samples algorithms..." << std::endl;
std::cout << std::endl;
std::cout << display_options << std::endl;
return EXIT_SUCCESS;
}
/* No values specified? Show a message and exit. */
if (! options_vars.count("size") || ! options_vars.count("samples")) {
std::cout << "Usage: " << argv[0] << " [options] size samples algorithms..." << std::endl;
return EXIT_FAILURE;
}
int size = options_vars["size"].as<int>();
int samples = options_vars["samples"].as<int>();
std::vector<std::function<MaxBicliqueResult (const Graph &, const MaxBicliqueParams &)> > selected_algorithms;
for (auto & s : options_vars["algorithm"].as<std::vector<std::string> >()) {
/* Turn an algorithm string name into a runnable function. */
auto algorithm = max_biclique_algorithms.begin(), algorithm_end = max_biclique_algorithms.end();
for ( ; algorithm != algorithm_end ; ++algorithm)
if (std::get<0>(*algorithm) == s)
break;
if (algorithm == algorithm_end) {
std::cerr << "Unknown algorithm " << s << ", choose from:";
for (auto a : max_biclique_algorithms)
std::cerr << " " << std::get<0>(a);
std::cerr << std::endl;
return EXIT_FAILURE;
}
selected_algorithms.push_back(std::get<1>(*algorithm));
}
table(size, samples, selected_algorithms);
return EXIT_SUCCESS;
}
catch (const po::error & e) {
std::cerr << "Error: " << e.what() << std::endl;
std::cerr << "Try " << argv[0] << " --help" << std::endl;
return EXIT_FAILURE;
}
catch (const std::exception & e) {
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Matthew Harvey
*
* 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 "day_command.hpp"
#include "command.hpp"
#include "config.hpp"
#include "help_line.hpp"
#include "reporting_command.hpp"
#include "time_point.hpp"
#include <ostream>
#include <sstream>
#include <string>
#include <vector>
using std::ostream;
using std::ostringstream;
using std::string;
using std::stringstream;
using std::vector;
namespace swx
{
namespace
{
int const k_max_days_ago = 9;
string days_ago_pluralized(int days)
{
if (days == 1)
{
return "yesterday";
}
ostringstream oss;
oss << days << " days ago";
return oss.str();
}
}
DayCommand::DayCommand
( string const& p_command_word,
vector<string> const& p_aliases,
TimeLog& p_time_log
):
ReportingCommand
( p_command_word,
p_aliases,
"Print summary of a single day's activities",
vector<HelpLine>
{ HelpLine("Print summary of time spent on all activities today"),
HelpLine
( "Print summary of time spent on ACTIVITY today",
"<ACTIVITY>"
)
},
p_time_log
)
{
add_option
( 'a',
"Instead of today's activities, print the activities from N days ago.",
nullptr,
&m_days_ago_str,
"<N>"
);
}
DayCommand::~DayCommand() = default;
Command::ErrorMessages
DayCommand::do_process
( Config const& p_config,
std::vector<std::string> const& p_ordinary_args,
ostream& p_ordinary_ostream
)
{
ErrorMessages ret;
TimePoint const n = now();
int days_ago = 0;
stringstream ss(m_days_ago_str);
ss >> days_ago;
if (!ss)
{
ret.push_back("Could not parse \"" + m_days_ago_str + "\" as numeric argument.");
}
if (ret.empty())
{
auto const b = day_begin(n, -days_ago);
auto const e = day_end(n, -days_ago);
print_report
( p_ordinary_ostream,
p_config,
p_ordinary_args,
&b,
&e
);
}
return ret;
}
} // namespace swx
<commit_msg>Minor wording change in help output for "day" command<commit_after>/*
* Copyright 2014 Matthew Harvey
*
* 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 "day_command.hpp"
#include "command.hpp"
#include "config.hpp"
#include "help_line.hpp"
#include "reporting_command.hpp"
#include "time_point.hpp"
#include <ostream>
#include <sstream>
#include <string>
#include <vector>
using std::ostream;
using std::ostringstream;
using std::string;
using std::stringstream;
using std::vector;
namespace swx
{
namespace
{
int const k_max_days_ago = 9;
string days_ago_pluralized(int days)
{
if (days == 1)
{
return "yesterday";
}
ostringstream oss;
oss << days << " days ago";
return oss.str();
}
}
DayCommand::DayCommand
( string const& p_command_word,
vector<string> const& p_aliases,
TimeLog& p_time_log
):
ReportingCommand
( p_command_word,
p_aliases,
"Print summary of a single day's activities",
vector<HelpLine>
{ HelpLine("Print summary of time spent on all activities today"),
HelpLine
( "Print summary of time spent on ACTIVITY today",
"<ACTIVITY>"
)
},
p_time_log
)
{
add_option
( 'a',
"Instead of today's activities, print the activities of N days ago",
nullptr,
&m_days_ago_str,
"<N>"
);
}
DayCommand::~DayCommand() = default;
Command::ErrorMessages
DayCommand::do_process
( Config const& p_config,
std::vector<std::string> const& p_ordinary_args,
ostream& p_ordinary_ostream
)
{
ErrorMessages ret;
TimePoint const n = now();
int days_ago = 0;
stringstream ss(m_days_ago_str);
ss >> days_ago;
if (!ss)
{
ret.push_back("Could not parse \"" + m_days_ago_str + "\" as numeric argument.");
}
if (ret.empty())
{
auto const b = day_begin(n, -days_ago);
auto const e = day_end(n, -days_ago);
print_report
( p_ordinary_ostream,
p_config,
p_ordinary_args,
&b,
&e
);
}
return ret;
}
} // namespace swx
<|endoftext|> |
<commit_before>// Copyright 2019 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP_COMPONENTS__COMPONENT_MANAGER_HPP__
#define RCLCPP_COMPONENTS__COMPONENT_MANAGER_HPP__
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "composition_interfaces/srv/load_node.hpp"
#include "composition_interfaces/srv/unload_node.hpp"
#include "composition_interfaces/srv/list_nodes.hpp"
#include "rclcpp/executor.hpp"
#include "rclcpp/node_options.hpp"
#include "rclcpp/rclcpp.hpp"
#include "rclcpp_components/node_factory.hpp"
#include "rclcpp_components/visibility_control.hpp"
namespace class_loader
{
class ClassLoader;
} // namespace class_loader
namespace rclcpp_components
{
class ComponentManagerException : public std::runtime_error
{
public:
explicit ComponentManagerException(const std::string & error_desc)
: std::runtime_error(error_desc) {}
};
class ComponentManager : public rclcpp::Node
{
public:
using LoadNode = composition_interfaces::srv::LoadNode;
using UnloadNode = composition_interfaces::srv::UnloadNode;
using ListNodes = composition_interfaces::srv::ListNodes;
/// Represents a component resource.
/**
* Is a pair of class name (for class loader) and library path (absolute)
*/
using ComponentResource = std::pair<std::string, std::string>;
RCLCPP_COMPONENTS_PUBLIC
ComponentManager(
std::weak_ptr<rclcpp::Executor> executor,
std::string node_name = "ComponentManager",
const rclcpp::NodeOptions & node_options = rclcpp::NodeOptions());
RCLCPP_COMPONENTS_PUBLIC
virtual ~ComponentManager();
/// Return a list of valid loadable components in a given package.
RCLCPP_COMPONENTS_PUBLIC
virtual std::vector<ComponentResource>
get_component_resources(
const std::string & package_name,
const std::string & resource_index = "rclcpp_components") const;
RCLCPP_COMPONENTS_PUBLIC
virtual std::shared_ptr<rclcpp_components::NodeFactory>
create_component_factory(const ComponentResource & resource);
protected:
RCLCPP_COMPONENTS_PUBLIC
virtual void
OnLoadNode(
const std::shared_ptr<rmw_request_id_t> request_header,
const std::shared_ptr<LoadNode::Request> request,
std::shared_ptr<LoadNode::Response> response);
RCLCPP_COMPONENTS_PUBLIC
virtual void
OnUnloadNode(
const std::shared_ptr<rmw_request_id_t> request_header,
const std::shared_ptr<UnloadNode::Request> request,
std::shared_ptr<UnloadNode::Response> response);
RCLCPP_COMPONENTS_PUBLIC
virtual void
OnListNodes(
const std::shared_ptr<rmw_request_id_t> request_header,
const std::shared_ptr<ListNodes::Request> request,
std::shared_ptr<ListNodes::Response> response);
private:
std::weak_ptr<rclcpp::Executor> executor_;
uint64_t unique_id_ {1};
std::map<std::string, std::unique_ptr<class_loader::ClassLoader>> loaders_;
std::map<uint64_t, rclcpp_components::NodeInstanceWrapper> node_wrappers_;
rclcpp::Service<LoadNode>::SharedPtr loadNode_srv_;
rclcpp::Service<UnloadNode>::SharedPtr unloadNode_srv_;
rclcpp::Service<ListNodes>::SharedPtr listNodes_srv_;
};
} // namespace rclcpp_components
#endif // RCLCPP_COMPONENTS__COMPONENT_MANAGER_HPP__
<commit_msg>Added dockblock to ComponentManager class (#1102)<commit_after>// Copyright 2019 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP_COMPONENTS__COMPONENT_MANAGER_HPP__
#define RCLCPP_COMPONENTS__COMPONENT_MANAGER_HPP__
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "composition_interfaces/srv/load_node.hpp"
#include "composition_interfaces/srv/unload_node.hpp"
#include "composition_interfaces/srv/list_nodes.hpp"
#include "rclcpp/executor.hpp"
#include "rclcpp/node_options.hpp"
#include "rclcpp/rclcpp.hpp"
#include "rclcpp_components/node_factory.hpp"
#include "rclcpp_components/visibility_control.hpp"
namespace class_loader
{
class ClassLoader;
} // namespace class_loader
namespace rclcpp_components
{
/// Thrown when an error happens in the component Manager class.
class ComponentManagerException : public std::runtime_error
{
public:
explicit ComponentManagerException(const std::string & error_desc)
: std::runtime_error(error_desc) {}
};
/// ComponentManager handles the services to load, unload, and get the list of loaded components.
class ComponentManager : public rclcpp::Node
{
public:
using LoadNode = composition_interfaces::srv::LoadNode;
using UnloadNode = composition_interfaces::srv::UnloadNode;
using ListNodes = composition_interfaces::srv::ListNodes;
/// Represents a component resource.
/**
* Is a pair of class name (for class loader) and library path (absolute)
*/
using ComponentResource = std::pair<std::string, std::string>;
/// Default constructor
/**
* Initializes the component manager. It creates the services: load node, unload node
* and list nodes.
*
* \param executor the executor which will spin the node.
* \param node_name the name of the node that the data originates from.
* \param node_options additional options to control creation of the node.
*/
RCLCPP_COMPONENTS_PUBLIC
ComponentManager(
std::weak_ptr<rclcpp::Executor> executor,
std::string node_name = "ComponentManager",
const rclcpp::NodeOptions & node_options = rclcpp::NodeOptions());
RCLCPP_COMPONENTS_PUBLIC
virtual ~ComponentManager();
/// Return a list of valid loadable components in a given package.
/*
* \param package_name name of the package
* \param resource_index name of the executable
* \throws ComponentManagerException if the resource was not found or a invalid resource entry
* \return a list of component resources
*/
RCLCPP_COMPONENTS_PUBLIC
virtual std::vector<ComponentResource>
get_component_resources(
const std::string & package_name,
const std::string & resource_index = "rclcpp_components") const;
/// Instantiate a component from a dynamic library.
/*
* \param resource a component resource (class name + library path)
* \return a NodeFactory interface
*/
RCLCPP_COMPONENTS_PUBLIC
virtual std::shared_ptr<rclcpp_components::NodeFactory>
create_component_factory(const ComponentResource & resource);
protected:
/// Service callback to load a new node in the component
/*
* This function allows to add parameters, remap rules, a specific node, name a namespace
* and/or additional arguments.
*
* \param request_header unused
* \param request information with the node to load
* \param response
* \throws std::overflow_error if node_id suffers an overflow. Very unlikely to happen at 1 kHz
* (very optimistic rate). it would take 585 years.
* \throws ComponentManagerException In the case that the component constructor throws an
* exception, rethrow into the following catch block.
*/
RCLCPP_COMPONENTS_PUBLIC
virtual void
OnLoadNode(
const std::shared_ptr<rmw_request_id_t> request_header,
const std::shared_ptr<LoadNode::Request> request,
std::shared_ptr<LoadNode::Response> response);
/// Service callback to unload a node in the component
/*
* \param request_header unused
* \param request unique identifier to remove from the component
* \param response true on the success field if the node unload was succefully, otherwise false
* and the error_message field contains the error.
*/
RCLCPP_COMPONENTS_PUBLIC
virtual void
OnUnloadNode(
const std::shared_ptr<rmw_request_id_t> request_header,
const std::shared_ptr<UnloadNode::Request> request,
std::shared_ptr<UnloadNode::Response> response);
/// Service callback to get the list of nodes in the component
/*
* Return a two list: one with the unique identifiers and other with full name of the nodes.
*
* \param request_header unused
* \param request unused
* \param response list with the unique ids and full node names
*/
RCLCPP_COMPONENTS_PUBLIC
virtual void
OnListNodes(
const std::shared_ptr<rmw_request_id_t> request_header,
const std::shared_ptr<ListNodes::Request> request,
std::shared_ptr<ListNodes::Response> response);
private:
std::weak_ptr<rclcpp::Executor> executor_;
uint64_t unique_id_ {1};
std::map<std::string, std::unique_ptr<class_loader::ClassLoader>> loaders_;
std::map<uint64_t, rclcpp_components::NodeInstanceWrapper> node_wrappers_;
rclcpp::Service<LoadNode>::SharedPtr loadNode_srv_;
rclcpp::Service<UnloadNode>::SharedPtr unloadNode_srv_;
rclcpp::Service<ListNodes>::SharedPtr listNodes_srv_;
};
} // namespace rclcpp_components
#endif // RCLCPP_COMPONENTS__COMPONENT_MANAGER_HPP__
<|endoftext|> |
<commit_before><commit_msg>small fix on ICP<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/profiling/memory/bounded_queue.h"
#include "gtest/gtest.h"
#include <thread>
namespace perfetto {
namespace profiling {
namespace {
TEST(BoundedQueueTest, IsFIFO) {
BoundedQueue<int> q(2);
q.Add(1);
q.Add(2);
int out;
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 1);
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 2);
}
TEST(BoundedQueueTest, BlockingAdd) {
BoundedQueue<int> q(2);
q.Add(1);
q.Add(2);
std::thread th([&q] { q.Add(3); });
int out;
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 1);
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 2);
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 3);
th.join();
}
TEST(BoundedQueueTest, BlockingGet) {
BoundedQueue<int> q(2);
std::thread th([&q] {
int out;
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 1);
});
q.Add(1);
th.join();
}
TEST(BoundedQueueTest, Resize) {
BoundedQueue<int> q(2);
q.Add(1);
q.Add(2);
q.SetCapacity(3);
q.Add(3);
int out;
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 1);
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 2);
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 3);
}
TEST(BoundedQueueTest, Shutdown) {
BoundedQueue<int> q(3);
q.Add(1);
q.Add(2);
q.Add(3);
int out;
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 1);
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 2);
q.Shutdown();
EXPECT_FALSE(q.Get(&out));
}
TEST(BoundedQueueTest, ShutdownBlockingAdd) {
BoundedQueue<int> q(2);
q.Add(1);
q.Add(2);
std::thread th([&q] { EXPECT_FALSE(q.Add(3)); });
int out;
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 1);
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 2);
q.Shutdown();
th.join();
}
TEST(BoundedQueueTest, ShutdownBlockingGet) {
BoundedQueue<int> q(1);
std::thread th([&q] {
int out;
EXPECT_FALSE(q.Get(&out));
});
q.Shutdown();
th.join();
}
} // namespace
} // namespace profiling
} // namespace perfetto
<commit_msg>profiling: Fix BoundedQueueTest.<commit_after>/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/profiling/memory/bounded_queue.h"
#include "gtest/gtest.h"
#include <thread>
namespace perfetto {
namespace profiling {
namespace {
TEST(BoundedQueueTest, IsFIFO) {
BoundedQueue<int> q(2);
q.Add(1);
q.Add(2);
int out;
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 1);
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 2);
q.Shutdown();
}
TEST(BoundedQueueTest, BlockingAdd) {
BoundedQueue<int> q(2);
q.Add(1);
q.Add(2);
std::thread th([&q] { q.Add(3); });
int out;
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 1);
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 2);
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 3);
th.join();
q.Shutdown();
}
TEST(BoundedQueueTest, BlockingGet) {
BoundedQueue<int> q(2);
std::thread th([&q] {
int out;
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 1);
});
q.Add(1);
th.join();
q.Shutdown();
}
TEST(BoundedQueueTest, Resize) {
BoundedQueue<int> q(2);
q.Add(1);
q.Add(2);
q.SetCapacity(3);
q.Add(3);
int out;
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 1);
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 2);
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 3);
q.Shutdown();
}
TEST(BoundedQueueTest, Shutdown) {
BoundedQueue<int> q(3);
q.Add(1);
q.Add(2);
q.Add(3);
int out;
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 1);
EXPECT_TRUE(q.Get(&out));
EXPECT_EQ(out, 2);
q.Shutdown();
EXPECT_FALSE(q.Get(&out));
}
TEST(BoundedQueueTest, ShutdownBlockingAdd) {
BoundedQueue<int> q(2);
q.Add(1);
q.Add(2);
std::thread th([&q] { EXPECT_FALSE(q.Add(3)); });
q.Shutdown();
th.join();
}
TEST(BoundedQueueTest, ShutdownBlockingGet) {
BoundedQueue<int> q(1);
std::thread th([&q] {
int out;
EXPECT_FALSE(q.Get(&out));
});
q.Shutdown();
th.join();
}
} // namespace
} // namespace profiling
} // namespace perfetto
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2004-2005 The Regents of The University of Michigan
* 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 holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
* Andrew Schultz
* Miguel Serrano
*/
#include <sys/time.h>
#include <ctime>
#include <string>
#include "base/bitfield.hh"
#include "base/time.hh"
#include "base/trace.hh"
#include "debug/MC146818.hh"
#include "dev/mc146818.hh"
#include "dev/rtcreg.h"
using namespace std;
static uint8_t
bcdize(uint8_t val)
{
uint8_t result;
result = val % 10;
result += (val / 10) << 4;
return result;
}
static uint8_t
unbcdize(uint8_t val)
{
uint8_t result;
result = val & 0xf;
result += (val >> 4) * 10;
return result;
}
void
MC146818::setTime(const struct tm time)
{
curTime = time;
year = time.tm_year;
// Unix is 0-11 for month, data seet says start at 1
mon = time.tm_mon + 1;
mday = time.tm_mday;
hour = time.tm_hour;
min = time.tm_min;
sec = time.tm_sec;
// Datasheet says 1 is sunday
wday = time.tm_wday + 1;
if (!stat_regB.dm) {
// The datasheet says that the year field can be either BCD or
// years since 1900. Linux seems to be happy with years since
// 1900.
year = bcdize(year % 100);
mon = bcdize(mon);
mday = bcdize(mday);
hour = bcdize(hour);
min = bcdize(min);
sec = bcdize(sec);
}
}
MC146818::MC146818(EventManager *em, const string &n, const struct tm time,
bool bcd, Tick frequency)
: EventManager(em), _name(n), event(this, frequency), tickEvent(this)
{
memset(clock_data, 0, sizeof(clock_data));
stat_regA = 0;
stat_regA.dv = RTCA_DV_32768HZ;
stat_regA.rs = RTCA_RS_1024HZ;
stat_regB = 0;
stat_regB.pie = 1;
stat_regB.format24h = 1;
stat_regB.dm = bcd ? 0 : 1;
setTime(time);
DPRINTFN("Real-time clock set to %s", asctime(&time));
}
MC146818::~MC146818()
{
deschedule(tickEvent);
deschedule(event);
}
bool
MC146818::rega_dv_disabled(const RtcRegA ®)
{
return reg.dv == RTCA_DV_DISABLED0 ||
reg.dv == RTCA_DV_DISABLED1;
}
void
MC146818::writeData(const uint8_t addr, const uint8_t data)
{
bool panic_unsupported(false);
if (addr < RTC_STAT_REGA) {
clock_data[addr] = data;
curTime.tm_sec = unbcdize(sec);
curTime.tm_min = unbcdize(min);
curTime.tm_hour = unbcdize(hour);
curTime.tm_mday = unbcdize(mday);
curTime.tm_mon = unbcdize(mon) - 1;
curTime.tm_year = ((unbcdize(year) + 50) % 100) + 1950;
curTime.tm_wday = unbcdize(wday) - 1;
} else {
switch (addr) {
case RTC_STAT_REGA: {
RtcRegA old_rega(stat_regA);
stat_regA = data;
// The "update in progress" bit is read only.
stat_regA.uip = old_rega;
if (stat_regA.dv != RTCA_DV_32768HZ) {
inform("RTC: Unimplemented divider configuration: %i\n",
stat_regA.dv);
panic_unsupported = true;
}
if (stat_regA.rs != RTCA_RS_1024HZ) {
inform("RTC: Unimplemented interrupt rate: %i\n",
stat_regA.rs);
panic_unsupported = true;
}
} break;
case RTC_STAT_REGB:
stat_regB = data;
if (stat_regB.set) {
inform("RTC: Updating stopping not implemented.\n");
panic_unsupported = true;
}
if (stat_regB.aie || stat_regB.uie) {
inform("RTC: Unimplemented interrupt configuration: %s %s\n",
stat_regB.aie ? "alarm" : "",
stat_regB.uie ? "update" : "");
panic_unsupported = true;
}
if (stat_regB.dm) {
inform("RTC: The binary interface is not fully implemented.\n");
panic_unsupported = true;
}
if (!stat_regB.format24h) {
inform("RTC: The 12h time format not supported.\n");
panic_unsupported = true;
}
if (stat_regB.dse) {
inform("RTC: Automatic daylight saving time not supported.\n");
panic_unsupported = true;
}
if (stat_regB.pie) {
if (!event.scheduled())
event.scheduleIntr();
} else {
if (event.scheduled())
deschedule(event);
}
break;
case RTC_STAT_REGC:
case RTC_STAT_REGD:
panic("RTC status registers C and D are not implemented.\n");
break;
}
}
if (panic_unsupported)
panic("Unimplemented RTC configuration!\n");
}
uint8_t
MC146818::readData(uint8_t addr)
{
if (addr < RTC_STAT_REGA)
return clock_data[addr];
else {
switch (addr) {
case RTC_STAT_REGA:
// toggle UIP bit for linux
stat_regA.uip = !stat_regA.uip;
return stat_regA;
break;
case RTC_STAT_REGB:
return stat_regB;
break;
case RTC_STAT_REGC:
case RTC_STAT_REGD:
return 0x00;
break;
default:
panic("Shouldn't be here");
}
}
}
void
MC146818::tickClock()
{
if (stat_regB.set)
return;
time_t calTime = mkutctime(&curTime);
calTime++;
setTime(*gmtime(&calTime));
}
void
MC146818::serialize(const string &base, ostream &os)
{
uint8_t regA_serial(stat_regA);
uint8_t regB_serial(stat_regB);
arrayParamOut(os, base + ".clock_data", clock_data, sizeof(clock_data));
paramOut(os, base + ".stat_regA", (uint8_t)regA_serial);
paramOut(os, base + ".stat_regB", (uint8_t)regB_serial);
//
// save the timer tick and rtc clock tick values to correctly reschedule
// them during unserialize
//
Tick rtcTimerInterruptTickOffset = event.when() - curTick();
SERIALIZE_SCALAR(rtcTimerInterruptTickOffset);
Tick rtcClockTickOffset = tickEvent.when() - curTick();
SERIALIZE_SCALAR(rtcClockTickOffset);
}
void
MC146818::unserialize(const string &base, Checkpoint *cp,
const string §ion)
{
uint8_t tmp8;
arrayParamIn(cp, section, base + ".clock_data", clock_data,
sizeof(clock_data));
paramIn(cp, section, base + ".stat_regA", tmp8);
stat_regA = tmp8;
paramIn(cp, section, base + ".stat_regB", tmp8);
stat_regB = tmp8;
//
// properly schedule the timer and rtc clock events
//
Tick rtcTimerInterruptTickOffset;
UNSERIALIZE_SCALAR(rtcTimerInterruptTickOffset);
reschedule(event, curTick() + rtcTimerInterruptTickOffset);
Tick rtcClockTickOffset;
UNSERIALIZE_SCALAR(rtcClockTickOffset);
reschedule(tickEvent, curTick() + rtcClockTickOffset);
}
MC146818::RTCEvent::RTCEvent(MC146818 * _parent, Tick i)
: parent(_parent), interval(i)
{
DPRINTF(MC146818, "RTC Event Initilizing\n");
parent->schedule(this, curTick() + interval);
}
void
MC146818::RTCEvent::scheduleIntr()
{
parent->schedule(this, curTick() + interval);
}
void
MC146818::RTCEvent::process()
{
DPRINTF(MC146818, "RTC Timer Interrupt\n");
parent->schedule(this, curTick() + interval);
parent->handleEvent();
}
const char *
MC146818::RTCEvent::description() const
{
return "RTC interrupt";
}
void
MC146818::RTCTickEvent::process()
{
DPRINTF(MC146818, "RTC clock tick\n");
parent->schedule(this, curTick() + SimClock::Int::s);
parent->tickClock();
}
const char *
MC146818::RTCTickEvent::description() const
{
return "RTC clock tick";
}
<commit_msg>dev: Add support for disabling ticking and the divider in MC146818<commit_after>/*
* Copyright (c) 2004-2005 The Regents of The University of Michigan
* 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 holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
* Andrew Schultz
* Miguel Serrano
*/
#include <sys/time.h>
#include <ctime>
#include <string>
#include "base/bitfield.hh"
#include "base/time.hh"
#include "base/trace.hh"
#include "debug/MC146818.hh"
#include "dev/mc146818.hh"
#include "dev/rtcreg.h"
using namespace std;
static uint8_t
bcdize(uint8_t val)
{
uint8_t result;
result = val % 10;
result += (val / 10) << 4;
return result;
}
static uint8_t
unbcdize(uint8_t val)
{
uint8_t result;
result = val & 0xf;
result += (val >> 4) * 10;
return result;
}
void
MC146818::setTime(const struct tm time)
{
curTime = time;
year = time.tm_year;
// Unix is 0-11 for month, data seet says start at 1
mon = time.tm_mon + 1;
mday = time.tm_mday;
hour = time.tm_hour;
min = time.tm_min;
sec = time.tm_sec;
// Datasheet says 1 is sunday
wday = time.tm_wday + 1;
if (!stat_regB.dm) {
// The datasheet says that the year field can be either BCD or
// years since 1900. Linux seems to be happy with years since
// 1900.
year = bcdize(year % 100);
mon = bcdize(mon);
mday = bcdize(mday);
hour = bcdize(hour);
min = bcdize(min);
sec = bcdize(sec);
}
}
MC146818::MC146818(EventManager *em, const string &n, const struct tm time,
bool bcd, Tick frequency)
: EventManager(em), _name(n), event(this, frequency), tickEvent(this)
{
memset(clock_data, 0, sizeof(clock_data));
stat_regA = 0;
stat_regA.dv = RTCA_DV_32768HZ;
stat_regA.rs = RTCA_RS_1024HZ;
stat_regB = 0;
stat_regB.pie = 1;
stat_regB.format24h = 1;
stat_regB.dm = bcd ? 0 : 1;
setTime(time);
DPRINTFN("Real-time clock set to %s", asctime(&time));
}
MC146818::~MC146818()
{
deschedule(tickEvent);
deschedule(event);
}
bool
MC146818::rega_dv_disabled(const RtcRegA ®)
{
return reg.dv == RTCA_DV_DISABLED0 ||
reg.dv == RTCA_DV_DISABLED1;
}
void
MC146818::writeData(const uint8_t addr, const uint8_t data)
{
bool panic_unsupported(false);
if (addr < RTC_STAT_REGA) {
clock_data[addr] = data;
curTime.tm_sec = unbcdize(sec);
curTime.tm_min = unbcdize(min);
curTime.tm_hour = unbcdize(hour);
curTime.tm_mday = unbcdize(mday);
curTime.tm_mon = unbcdize(mon) - 1;
curTime.tm_year = ((unbcdize(year) + 50) % 100) + 1950;
curTime.tm_wday = unbcdize(wday) - 1;
} else {
switch (addr) {
case RTC_STAT_REGA: {
RtcRegA old_rega(stat_regA);
stat_regA = data;
// The "update in progress" bit is read only.
stat_regA.uip = old_rega;
if (!rega_dv_disabled(stat_regA) &&
stat_regA.dv != RTCA_DV_32768HZ) {
inform("RTC: Unimplemented divider configuration: %i\n",
stat_regA.dv);
panic_unsupported = true;
}
if (stat_regA.rs != RTCA_RS_1024HZ) {
inform("RTC: Unimplemented interrupt rate: %i\n",
stat_regA.rs);
panic_unsupported = true;
}
if (rega_dv_disabled(stat_regA)) {
// The divider is disabled, make sure that we don't
// schedule any ticks.
if (tickEvent.scheduled())
deschedule(tickEvent);
} else if (rega_dv_disabled(old_rega)) {
// If the divider chain goes from reset to active, we
// need to schedule a tick after precisely 0.5s.
assert(!tickEvent.scheduled());
schedule(tickEvent, curTick() + SimClock::Int::s / 2);
}
} break;
case RTC_STAT_REGB:
stat_regB = data;
if (stat_regB.aie || stat_regB.uie) {
inform("RTC: Unimplemented interrupt configuration: %s %s\n",
stat_regB.aie ? "alarm" : "",
stat_regB.uie ? "update" : "");
panic_unsupported = true;
}
if (stat_regB.dm) {
inform("RTC: The binary interface is not fully implemented.\n");
panic_unsupported = true;
}
if (!stat_regB.format24h) {
inform("RTC: The 12h time format not supported.\n");
panic_unsupported = true;
}
if (stat_regB.dse) {
inform("RTC: Automatic daylight saving time not supported.\n");
panic_unsupported = true;
}
if (stat_regB.pie) {
if (!event.scheduled())
event.scheduleIntr();
} else {
if (event.scheduled())
deschedule(event);
}
break;
case RTC_STAT_REGC:
case RTC_STAT_REGD:
panic("RTC status registers C and D are not implemented.\n");
break;
}
}
if (panic_unsupported)
panic("Unimplemented RTC configuration!\n");
}
uint8_t
MC146818::readData(uint8_t addr)
{
if (addr < RTC_STAT_REGA)
return clock_data[addr];
else {
switch (addr) {
case RTC_STAT_REGA:
// toggle UIP bit for linux
stat_regA.uip = !stat_regA.uip;
return stat_regA;
break;
case RTC_STAT_REGB:
return stat_regB;
break;
case RTC_STAT_REGC:
case RTC_STAT_REGD:
return 0x00;
break;
default:
panic("Shouldn't be here");
}
}
}
void
MC146818::tickClock()
{
assert(!rega_dv_disabled(stat_regA));
if (stat_regB.set)
return;
time_t calTime = mkutctime(&curTime);
calTime++;
setTime(*gmtime(&calTime));
}
void
MC146818::serialize(const string &base, ostream &os)
{
uint8_t regA_serial(stat_regA);
uint8_t regB_serial(stat_regB);
arrayParamOut(os, base + ".clock_data", clock_data, sizeof(clock_data));
paramOut(os, base + ".stat_regA", (uint8_t)regA_serial);
paramOut(os, base + ".stat_regB", (uint8_t)regB_serial);
//
// save the timer tick and rtc clock tick values to correctly reschedule
// them during unserialize
//
Tick rtcTimerInterruptTickOffset = event.when() - curTick();
SERIALIZE_SCALAR(rtcTimerInterruptTickOffset);
Tick rtcClockTickOffset = tickEvent.when() - curTick();
SERIALIZE_SCALAR(rtcClockTickOffset);
}
void
MC146818::unserialize(const string &base, Checkpoint *cp,
const string §ion)
{
uint8_t tmp8;
arrayParamIn(cp, section, base + ".clock_data", clock_data,
sizeof(clock_data));
paramIn(cp, section, base + ".stat_regA", tmp8);
stat_regA = tmp8;
paramIn(cp, section, base + ".stat_regB", tmp8);
stat_regB = tmp8;
//
// properly schedule the timer and rtc clock events
//
Tick rtcTimerInterruptTickOffset;
UNSERIALIZE_SCALAR(rtcTimerInterruptTickOffset);
reschedule(event, curTick() + rtcTimerInterruptTickOffset);
Tick rtcClockTickOffset;
UNSERIALIZE_SCALAR(rtcClockTickOffset);
reschedule(tickEvent, curTick() + rtcClockTickOffset);
}
MC146818::RTCEvent::RTCEvent(MC146818 * _parent, Tick i)
: parent(_parent), interval(i)
{
DPRINTF(MC146818, "RTC Event Initilizing\n");
parent->schedule(this, curTick() + interval);
}
void
MC146818::RTCEvent::scheduleIntr()
{
parent->schedule(this, curTick() + interval);
}
void
MC146818::RTCEvent::process()
{
DPRINTF(MC146818, "RTC Timer Interrupt\n");
parent->schedule(this, curTick() + interval);
parent->handleEvent();
}
const char *
MC146818::RTCEvent::description() const
{
return "RTC interrupt";
}
void
MC146818::RTCTickEvent::process()
{
DPRINTF(MC146818, "RTC clock tick\n");
parent->schedule(this, curTick() + SimClock::Int::s);
parent->tickClock();
}
const char *
MC146818::RTCTickEvent::description() const
{
return "RTC clock tick";
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2004-2005 The Regents of The University of Michigan
* 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 holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Andrew Schultz
* Nathan Binkert
*/
/**
* @file
* Generic interface for platforms
*/
#ifndef __DEV_PLATFORM_HH__
#define __DEV_PLATFORM_HH__
#include <bitset>
#include <set>
#include "params/Platform.hh"
#include "sim/sim_object.hh"
class PciConfigAll;
class IntrControl;
class Terminal;
class Uart;
class System;
class Platform : public SimObject
{
public:
/** Pointer to the interrupt controller */
IntrControl *intrctrl;
/** Pointer to the system for info about the memory system. */
System *system;
public:
typedef PlatformParams Params;
Platform(const Params *p);
virtual ~Platform();
virtual void postConsoleInt() = 0;
virtual void clearConsoleInt() = 0;
virtual void postPciInt(int line);
virtual void clearPciInt(int line);
virtual Addr pciToDma(Addr pciAddr) const;
virtual Addr calcPciConfigAddr(int bus, int dev, int func) = 0;
virtual Addr calcPciIOAddr(Addr addr) = 0;
virtual Addr calcPciMemAddr(Addr addr) = 0;
virtual void registerPciDevice(uint8_t bus, uint8_t dev, uint8_t func,
uint8_t intr);
private:
std::bitset<256> intLines;
std::set<uint32_t> pciDevices;
};
#endif // __DEV_PLATFORM_HH__
<commit_msg>dev: Remove unused system pointer in the Platform base class<commit_after>/*
* Copyright (c) 2004-2005 The Regents of The University of Michigan
* 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 holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Andrew Schultz
* Nathan Binkert
*/
/**
* @file
* Generic interface for platforms
*/
#ifndef __DEV_PLATFORM_HH__
#define __DEV_PLATFORM_HH__
#include <bitset>
#include <set>
#include "params/Platform.hh"
#include "sim/sim_object.hh"
class PciConfigAll;
class IntrControl;
class Terminal;
class Uart;
class System;
class Platform : public SimObject
{
public:
/** Pointer to the interrupt controller */
IntrControl *intrctrl;
public:
typedef PlatformParams Params;
Platform(const Params *p);
virtual ~Platform();
virtual void postConsoleInt() = 0;
virtual void clearConsoleInt() = 0;
virtual void postPciInt(int line);
virtual void clearPciInt(int line);
virtual Addr pciToDma(Addr pciAddr) const;
virtual Addr calcPciConfigAddr(int bus, int dev, int func) = 0;
virtual Addr calcPciIOAddr(Addr addr) = 0;
virtual Addr calcPciMemAddr(Addr addr) = 0;
virtual void registerPciDevice(uint8_t bus, uint8_t dev, uint8_t func,
uint8_t intr);
private:
std::bitset<256> intLines;
std::set<uint32_t> pciDevices;
};
#endif // __DEV_PLATFORM_HH__
<|endoftext|> |
<commit_before>
#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include "api/BamReader.h"
#include "transrate-pileup.h"
using namespace BamTools;
using namespace std;
struct ContigRecord {
int bases_mapped;
int p_seq_true;
int bridges;
int length;
string name;
int fragments_mapped;
int both_mapped;
int properpair;
int good;
int bases_uncovered;
double p_unique;
double p_not_segmented;
};
class BetterBam {
int realistic_distance;
int seq_count;
int i,j;
uint32_t nm_tag;
int ldist;
int rdist;
int maxL=0;
std::string file;
BamReader reader;
BamAlignment alignment;
public:
std::vector<ContigRecord> array;
BetterBam (std::string);
bool check_cigar(BamAlignment alignment) {
int numCigarOps = alignment.CigarData.size();
bool check = false;
for (int i = 0; i < numCigarOps; ++i) {
const CigarOp& op = alignment.CigarData.at(i);
if (op.Type != 'S') {
check = true;
}
}
return check;
}
void set_fragment_size(int size, int sd) {
realistic_distance = size + 3 * sd;
}
int load_bam() {
if (!reader.Open(file)) {
cerr << "Could not open BAM file" << endl;
return 1;
}
// get sam header
SamSequenceDictionary dictionary = reader.GetHeader().Sequences;
seq_count = dictionary.Size();
array.resize(seq_count);
// get an iterator for looping over the sequences in the header
std::vector<SamSequence>::iterator it = dictionary.Begin();
// fill the vector with intial values
for (i = 0; i < seq_count; i++) {
array[i].bases_mapped = 0;
array[i].p_seq_true = 0;
array[i].bridges = 0;
if (it[i].HasLength()) {
array[i].length = atoi(it[i].Length.c_str());
if (array[i].length > maxL) {
maxL = array[i].length;
}
} else {
array[i].length = 0;
}
array[i].name = it[i].Name;
array[i].fragments_mapped = 0;
array[i].both_mapped = 0;
array[i].properpair = 0;
array[i].good = 0;
array[i].bases_uncovered = 0;
array[i].p_unique = 0;
array[i].p_not_segmented = 1;
}
// loop through bam file
i = -2;
TransratePileup pileup(maxL);
int ref_length = -1;
while (reader.GetNextAlignment(alignment)) {
if (alignment.IsMapped() && check_cigar(alignment)) {
// new contig
if (alignment.RefID != i) {
if (i>=0) {
array[i].bases_uncovered = pileup.getBasesUncovered();
array[i].p_unique = pileup.getUniqueBases();
array[i].p_not_segmented = pileup.p_not_segmented();
}
i = alignment.RefID;
ref_length = array[i].length;
pileup.clearCoverage(ref_length);
}
if (alignment.IsPrimaryAlignment()) {
pileup.addAlignment(alignment);
}
array[i].bases_mapped += alignment.Length;
if (alignment.HasTag("NM")) {
if (alignment.GetTag("NM", nm_tag)) {
array[i].p_seq_true += nm_tag;
}
}
if (alignment.IsFirstMate() ||
(alignment.IsSecondMate() && !alignment.IsMateMapped())) {
array[i].fragments_mapped++;
}
if (alignment.IsFirstMate() && alignment.IsMateMapped()) {
array[i].both_mapped++;
if (alignment.IsProperPair() && alignment.RefID==alignment.MateRefID) {
array[i].properpair++;
// check orientation
ldist = max(alignment.Position-alignment.MatePosition,
alignment.MatePosition-alignment.Position);
if (ldist < realistic_distance) {
if (!alignment.IsReverseStrand() && alignment.IsMateReverseStrand()) {
if (alignment.GetEndPosition() < alignment.MatePosition) {
array[i].good++;
}
} else if (alignment.IsReverseStrand() && !alignment.IsMateReverseStrand()) {
if (alignment.GetEndPosition() > alignment.MatePosition) {
array[i].good++;
}
}
}
} else {
if (i != alignment.MateRefID) {
ldist = min(alignment.Position,
array[i].length - alignment.Position);
rdist = min(alignment.MatePosition,
array[alignment.MateRefID].length - alignment.MatePosition);
if (ldist + rdist <= realistic_distance) {
array[i].bridges++;
}
}
}
}
}
}
array[i].bases_uncovered = pileup.getBasesUncovered();
array[i].p_unique = pileup.getUniqueBases();
array[i].p_not_segmented = pileup.p_not_segmented();
reader.Close();
return 0;
}
int get_seq_count() {
return seq_count;
}
ContigRecord get_info(int i) {
return array.at(i);
}
int get_bases_mapped(int i) {
return array.at(i).bases_mapped;
}
};
//constructor
BetterBam::BetterBam (std::string s) {
file = s;
realistic_distance = 350;
}
int main (int argc, char* argv[]) {
if (argc == 3) {
string infile = argv[1];
BetterBam bam (infile);
bam.load_bam();
int i;
std::ofstream output;
output.open (argv[2]);
output << "name,p_seq_true,bridges,length,fragments_mapped,"
"both_mapped,properpair,good,bases_uncovered,p_unique,"
"p_not_segmented" << endl;
for (i = 0; i < bam.get_seq_count(); i++) {
output << bam.get_info(i).name << ",";
if (bam.get_info(i).bases_mapped>0) {
output << 1-((double)bam.get_info(i).p_seq_true/bam.get_info(i).bases_mapped) << ",";
} else {
output << "1,";
}
output << bam.get_info(i).bridges << ",";
output << bam.get_info(i).length << ",";
output << bam.get_info(i).fragments_mapped << ",";
output << bam.get_info(i).both_mapped << ",";
output << bam.get_info(i).properpair << ",";
output << bam.get_info(i).good << ",";
output << bam.get_info(i).bases_uncovered << ",";
output << bam.get_info(i).p_unique << ",";
output << bam.get_info(i).p_not_segmented << endl;
}
output.close();
return 0;
} else {
cout << "bam-read version 0.3.3\nUsage:\nbam-read <bam_file> <output_csv>" << endl;
return 1;
}
}
<commit_msg>first-pass tidy, comment and fixx<commit_after>
#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include "api/BamReader.h"
#include "transrate-pileup.h"
using namespace BamTools;
using namespace std;
struct ContigRecord {
int bases_mapped;
int p_seq_true;
int bridges;
int length;
string name;
int fragments_mapped;
int both_mapped;
int properpair;
int good;
int bases_uncovered;
double p_unique;
double p_not_segmented;
};
class BetterBam {
int realistic_distance;
int seq_count;
int i,j;
uint32_t nm_tag;
int ldist;
int rdist;
int maxL=0;
std::string file;
BamReader reader;
BamAlignment alignment;
public:
std::vector<ContigRecord> array;
BetterBam (std::string);
// loop through all cigar operations and check they are not S
bool check_cigar(BamAlignment alignment) {
int numCigarOps = alignment.CigarData.size();
bool check = false;
for (int i = 0; i < numCigarOps; ++i) {
const CigarOp& op = alignment.CigarData.at(i);
if (op.Type != 'S') {
check = true;
}
}
return check;
}
// set realistic distance between pairs to have 0.03% false positive rate
void set_fragment_size(int size, int sd) {
realistic_distance = size + 3 * sd;
}
int load_bam() {
if (!reader.Open(file)) {
cerr << "Could not open BAM file" << endl;
return 1;
}
// get sam header
SamSequenceDictionary dictionary = reader.GetHeader().Sequences;
seq_count = dictionary.Size();
array.resize(seq_count);
// get an iterator for looping over the sequences in the header
std::vector<SamSequence>::iterator it = dictionary.Begin();
// fill the vector with intial values
for (i = 0; i < seq_count; i++) {
array[i].bases_mapped = 0;
array[i].p_seq_true = 0;
array[i].bridges = 0;
if (it[i].HasLength()) {
array[i].length = atoi(it[i].Length.c_str());
if (array[i].length > maxL) {
maxL = array[i].length;
}
} else {
array[i].length = 0;
}
array[i].name = it[i].Name;
array[i].fragments_mapped = 0;
array[i].both_mapped = 0;
array[i].properpair = 0;
array[i].good = 0;
array[i].bases_uncovered = 0;
array[i].p_unique = 0;
array[i].p_not_segmented = 1;
}
// loop through bam file
i = -2;
TransratePileup pileup(maxL);
int ref_length = -1;
while (reader.GetNextAlignment(alignment)) {
// read must be mapped
if (!alignment.IsMapped()) {
continue;
}
// alignment must have a valid cigar sting
if (!check_cigar(alignment)) {
continue;
}
// check this read comes from the currently loaded contig
// if not, load the new contig
if (alignment.RefID != i) {
if (i>=0) {
array[i].bases_uncovered = pileup.getBasesUncovered();
array[i].p_unique = pileup.getUniqueBases();
array[i].p_not_segmented = pileup.p_not_segmented();
}
i = alignment.RefID;
ref_length = array[i].length;
pileup.clearCoverage(ref_length);
}
// we only care about the primary alignment of each fragment
if (!alignment.IsPrimaryAlignment()) {
continue;
}
pileup.addAlignment(alignment);
array[i].bases_mapped += alignment.Length;
// store edit distance for sequence accuracy calculation
if (alignment.HasTag("NM")) {
if (alignment.GetTag("NM", nm_tag)) {
array[i].p_seq_true += nm_tag;
}
}
// count fragments where either or both mates mapped
if (alignment.IsFirstMate() ||
(alignment.IsSecondMate() && !alignment.IsMateMapped())) {
array[i].fragments_mapped++;
}
// from now on ignore fragments unless both mates mapped
if (!(alignment.IsFirstMate() && alignment.IsMateMapped())) {
continue;
}
array[i].both_mapped++;
// mates must align to same contig, otherwise we record a bridge
if (alignment.RefIDv != alignment.MateRefID) {
array[i].bridges++;
continue;
}
// fragment length must be plausible
ldist = max(alignment.Position-alignment.MatePosition,
alignment.MatePosition-alignment.Position);
if (ldist > realistic_distance) {
// mates are too far apart
continue;
}
// read orientation must match the generated library
// in this case we only test for FR/RF orientation,
// that is - we expect mates to be on opposite strands
bool is_reversed = a.IsReverseStrand();
bool is_mate_reversed = a.IsMateReverseStrand();
if (!is_reversed && is_mate_reversed)
// in FR orientation, first read must start
// before second read
if (alignment.Position < alignment.MatePosition) {
array[i].good++;
}
} else if (is_reversed && !is_mate_reversed) {
// in RF orientation, second read must start
// before first read
if (alignment.MatePosition < alignment.Position) {
array[i].good++;
}
}
}
array[i].bases_uncovered = pileup.getBasesUncovered();
array[i].p_unique = pileup.getUniqueBases();
array[i].p_not_segmented = pileup.p_not_segmented();
reader.Close();
return 0;
}
int get_seq_count() {
return seq_count;
}
ContigRecord get_info(int i) {
return array.at(i);
}
int get_bases_mapped(int i) {
return array.at(i).bases_mapped;
}
};
//constructor
BetterBam::BetterBam (std::string s) {
file = s;
realistic_distance = 350;
}
int main (int argc, char* argv[]) {
if (argc == 3) {
string infile = argv[1];
BetterBam bam (infile);
bam.load_bam();
int i;
std::ofstream output;
output.open (argv[2]);
output << "name,p_seq_true,bridges,length,fragments_mapped,"
"both_mapped,properpair,good,bases_uncovered,p_unique,"
"p_not_segmented" << endl;
for (i = 0; i < bam.get_seq_count(); i++) {
output << bam.get_info(i).name << ",";
if (bam.get_info(i).bases_mapped>0) {
output << 1-((double)bam.get_info(i).p_seq_true/bam.get_info(i).bases_mapped) << ",";
} else {
output << "1,";
}
output << bam.get_info(i).bridges << ",";
output << bam.get_info(i).length << ",";
output << bam.get_info(i).fragments_mapped << ",";
output << bam.get_info(i).both_mapped << ",";
output << bam.get_info(i).properpair << ",";
output << bam.get_info(i).good << ",";
output << bam.get_info(i).bases_uncovered << ",";
output << bam.get_info(i).p_unique << ",";
output << bam.get_info(i).p_not_segmented << endl;
}
output.close();
return 0;
} else {
cout << "bam-read version 0.3.3\nUsage:\nbam-read <bam_file> <output_csv>" << endl;
return 1;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "runtime/debug/zorba_debugger_iterators.h"
#include <iostream>
#include <sstream>
#include <cassert>
#include <zorbautils/thread.h>
#include "system/globalenv.h"
#include "debugger/debugger_server.h"
using namespace std;
namespace zorba {
FnDebugIterator::FnDebugIterator(const QueryLoc& loc,
checked_vector<store::Item_t> varnames_,
checked_vector<std::string> var_keys_,
checked_vector<xqtref_t> vartypes_,
checked_vector<global_binding> globals_,
std::vector<PlanIter_t>& aChildren,
bool for_expr_)
: NaryBaseIterator<FnDebugIterator, PlanIteratorState>(loc, aChildren),
theDebugger(0), varnames(varnames_), var_keys(var_keys_), vartypes(vartypes_),
globals(globals_), for_expr(for_expr_){}
FnDebugIterator::~FnDebugIterator(){}
bool FnDebugIterator::nextImpl( store::Item_t& result, PlanState& planState ) const
{
PlanIteratorState * state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if ( theDebugger->hasToSuspend() )
{
updateInfos(loc, planState, varnames, var_keys, vartypes, globals);
assert(theDebugger->theRuntimeThread);
theDebugger->theRuntimeThread->suspend();
} else if ( theDebugger->hasToStepOver() ) {
updateInfos(loc, planState, varnames, var_keys, vartypes, globals);
theDebugger->stepOver();
theDebugger->setStatus(QUERY_SUSPENDED, CAUSE_STEP);
assert(theDebugger->theRuntimeThread);
theDebugger->theRuntimeThread->suspend();
} else if ( theDebugger->hasToStepOut() ) {
updateInfos(loc, planState, varnames, var_keys, vartypes, globals);
theDebugger->stepOut();
theDebugger->setStatus(QUERY_SUSPENDED, CAUSE_STEP);
assert(theDebugger->theRuntimeThread);
theDebugger->theRuntimeThread->suspend();
} else if ( theDebugger->hasToStepInto() ) {
updateInfos(loc, planState, varnames, var_keys, vartypes, globals);
theDebugger->stepInto();
theDebugger->setStatus(QUERY_SUSPENDED, CAUSE_STEP);
assert(theDebugger->theRuntimeThread);
theDebugger->theRuntimeThread->suspend();
}
while ( consumeNext( result, theChildren[0], planState )) {
STACK_PUSH(true, state);
if ( for_expr ) {
if ( theDebugger->hasToSuspend() )
{
updateInfos(loc, planState, varnames, var_keys, vartypes, globals);
assert(theDebugger->theRuntimeThread);
theDebugger->theRuntimeThread->suspend();
} else if ( theDebugger->hasToStepOver() ) {
updateInfos(loc, planState, varnames, var_keys, vartypes, globals);
theDebugger->stepOver();
theDebugger->setStatus(QUERY_SUSPENDED, CAUSE_STEP);
assert(theDebugger->theRuntimeThread);
theDebugger->theRuntimeThread->suspend();
} else if ( theDebugger->hasToStepOut() ) {
updateInfos(loc, planState, varnames, var_keys, vartypes, globals);
theDebugger->stepOut();
theDebugger->setStatus(QUERY_SUSPENDED, CAUSE_STEP);
assert(theDebugger->theRuntimeThread);
theDebugger->theRuntimeThread->suspend();
} else if ( theDebugger->hasToStepInto() ) {
updateInfos(loc, planState, varnames, var_keys, vartypes, globals);
theDebugger->stepInto();
theDebugger->setStatus(QUERY_SUSPENDED, CAUSE_STEP);
assert(theDebugger->theRuntimeThread);
theDebugger->theRuntimeThread->suspend();
}
}
}
STACK_END(state);
}
void FnDebugIterator::openImpl(PlanState& planState, uint32_t& offset )
{
NaryBaseIterator<FnDebugIterator, PlanIteratorState>::openImpl(planState, offset);
theDebugger = planState.theCompilerCB->m_debugger;
}
void FnDebugIterator::accept( PlanIterVisitor& v ) const
{
v.beginVisit(*this);
std::vector<PlanIter_t>::const_iterator iter = theChildren.begin();
std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
for ( ; iter != lEnd; ++iter ) {
( *iter )->accept ( v );
}
v.endVisit(*this);
}
void FnDebugIterator::updateInfos(const QueryLoc& loc, PlanState& planState, checked_vector<store::Item_t> varnames,
checked_vector<std::string> var_keys, checked_vector<xqtref_t> vartypes,
checked_vector<global_binding> globals) const
{
assert(theDebugger);
theDebugger->theLocation = loc;
theDebugger->thePlanState = &planState;
theDebugger->theVarnames = varnames;
theDebugger->theVarkeys = var_keys;
theDebugger->theVartypes = vartypes;
theDebugger->theGlobals = globals;
theDebugger->theChildren = theChildren;
theDebugger->theLocation = loc;
}
} /* namespace zorba */
<commit_msg>Fix minor issue.<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "runtime/debug/zorba_debugger_iterators.h"
#include <iostream>
#include <sstream>
#include <cassert>
#include <zorbautils/thread.h>
#include "system/globalenv.h"
#include "debugger/debugger_server.h"
using namespace std;
namespace zorba {
FnDebugIterator::FnDebugIterator(const QueryLoc& loc,
checked_vector<store::Item_t> varnames_,
checked_vector<std::string> var_keys_,
checked_vector<xqtref_t> vartypes_,
checked_vector<global_binding> globals_,
std::vector<PlanIter_t>& aChildren,
bool for_expr_)
: NaryBaseIterator<FnDebugIterator, PlanIteratorState>(loc, aChildren),
theDebugger(0), varnames(varnames_), var_keys(var_keys_), vartypes(vartypes_),
globals(globals_), for_expr(for_expr_){}
FnDebugIterator::~FnDebugIterator(){}
bool FnDebugIterator::nextImpl( store::Item_t& result, PlanState& planState ) const
{
PlanIteratorState * state;
updateInfos(loc, planState, varnames, var_keys, vartypes, globals);
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if ( theDebugger->hasToSuspend() )
{
//updateInfos(loc, planState, varnames, var_keys, vartypes, globals);
assert(theDebugger->theRuntimeThread);
theDebugger->theRuntimeThread->suspend();
} else if ( theDebugger->hasToStepOver() ) {
//updateInfos(loc, planState, varnames, var_keys, vartypes, globals);
theDebugger->stepOver();
theDebugger->setStatus(QUERY_SUSPENDED, CAUSE_STEP);
assert(theDebugger->theRuntimeThread);
theDebugger->theRuntimeThread->suspend();
} else if ( theDebugger->hasToStepOut() ) {
//updateInfos(loc, planState, varnames, var_keys, vartypes, globals);
theDebugger->stepOut();
theDebugger->setStatus(QUERY_SUSPENDED, CAUSE_STEP);
assert(theDebugger->theRuntimeThread);
theDebugger->theRuntimeThread->suspend();
} else if ( theDebugger->hasToStepInto() ) {
//updateInfos(loc, planState, varnames, var_keys, vartypes, globals);
theDebugger->stepInto();
theDebugger->setStatus(QUERY_SUSPENDED, CAUSE_STEP);
assert(theDebugger->theRuntimeThread);
theDebugger->theRuntimeThread->suspend();
}
while ( consumeNext( result, theChildren[0], planState )) {
STACK_PUSH(true, state);
if ( for_expr ) {
if ( theDebugger->hasToSuspend() )
{
updateInfos(loc, planState, varnames, var_keys, vartypes, globals);
assert(theDebugger->theRuntimeThread);
theDebugger->theRuntimeThread->suspend();
} else if ( theDebugger->hasToStepOver() ) {
updateInfos(loc, planState, varnames, var_keys, vartypes, globals);
theDebugger->stepOver();
theDebugger->setStatus(QUERY_SUSPENDED, CAUSE_STEP);
assert(theDebugger->theRuntimeThread);
theDebugger->theRuntimeThread->suspend();
} else if ( theDebugger->hasToStepOut() ) {
updateInfos(loc, planState, varnames, var_keys, vartypes, globals);
theDebugger->stepOut();
theDebugger->setStatus(QUERY_SUSPENDED, CAUSE_STEP);
assert(theDebugger->theRuntimeThread);
theDebugger->theRuntimeThread->suspend();
} else if ( theDebugger->hasToStepInto() ) {
updateInfos(loc, planState, varnames, var_keys, vartypes, globals);
theDebugger->stepInto();
theDebugger->setStatus(QUERY_SUSPENDED, CAUSE_STEP);
assert(theDebugger->theRuntimeThread);
theDebugger->theRuntimeThread->suspend();
}
}
}
STACK_END(state);
}
void FnDebugIterator::openImpl(PlanState& planState, uint32_t& offset )
{
NaryBaseIterator<FnDebugIterator, PlanIteratorState>::openImpl(planState, offset);
theDebugger = planState.theCompilerCB->m_debugger;
}
void FnDebugIterator::accept( PlanIterVisitor& v ) const
{
v.beginVisit(*this);
std::vector<PlanIter_t>::const_iterator iter = theChildren.begin();
std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
for ( ; iter != lEnd; ++iter ) {
( *iter )->accept ( v );
}
v.endVisit(*this);
}
void FnDebugIterator::updateInfos(const QueryLoc& loc, PlanState& planState, checked_vector<store::Item_t> varnames,
checked_vector<std::string> var_keys, checked_vector<xqtref_t> vartypes,
checked_vector<global_binding> globals) const
{
assert(theDebugger);
theDebugger->theLocation = loc;
theDebugger->thePlanState = &planState;
theDebugger->theVarnames = varnames;
theDebugger->theVarkeys = var_keys;
theDebugger->theVartypes = vartypes;
theDebugger->theGlobals = globals;
theDebugger->theChildren = theChildren;
theDebugger->theLocation = loc;
}
} /* namespace zorba */
<|endoftext|> |
<commit_before>#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0601
#undef WINVER
#define WINVER 0x0601
#include "keyboard-layout-manager.h"
#include <string>
#include <cctype>
#include <windows.h>
using namespace v8;
std::string ToUTF8(const std::wstring& string) {
if (string.length() < 1) {
return std::string();
}
// NB: In the pathological case, each character could expand up
// to 4 bytes in UTF8.
int cbLen = (string.length()+1) * sizeof(char) * 4;
char* buf = new char[cbLen];
int retLen = WideCharToMultiByte(CP_UTF8, 0, string.c_str(), string.length(), buf, cbLen, NULL, NULL);
buf[retLen] = 0;
std::string ret;
ret.assign(buf);
return ret;
}
void KeyboardLayoutManager::Init(Handle<Object> exports, Handle<Object> module) {
Nan::HandleScope scope;
Local<FunctionTemplate> newTemplate = Nan::New<FunctionTemplate>(KeyboardLayoutManager::New);
newTemplate->SetClassName(Nan::New<String>("KeyboardLayoutManager").ToLocalChecked());
newTemplate->InstanceTemplate()->SetInternalFieldCount(1);
Local<ObjectTemplate> proto = newTemplate->PrototypeTemplate();
Nan::SetMethod(proto, "getCurrentKeyboardLayout", KeyboardLayoutManager::GetCurrentKeyboardLayout);
Nan::SetMethod(proto, "getCurrentKeyboardLanguage", KeyboardLayoutManager::GetCurrentKeyboardLanguage);
Nan::SetMethod(proto, "getInstalledKeyboardLanguages", KeyboardLayoutManager::GetInstalledKeyboardLanguages);
Nan::SetMethod(proto, "getCurrentKeymap", KeyboardLayoutManager::GetCurrentKeymap);
module->Set(Nan::New("exports").ToLocalChecked(), newTemplate->GetFunction());
}
NODE_MODULE(keyboard_layout_manager, KeyboardLayoutManager::Init)
NAN_METHOD(KeyboardLayoutManager::New) {
Nan::HandleScope scope;
Local<Function> callbackHandle = info[0].As<Function>();
Nan::Callback *callback = new Nan::Callback(callbackHandle);
KeyboardLayoutManager *manager = new KeyboardLayoutManager(callback);
manager->Wrap(info.This());
return;
}
KeyboardLayoutManager::KeyboardLayoutManager(Nan::Callback *callback) : callback(callback) {
}
KeyboardLayoutManager::~KeyboardLayoutManager() {
delete callback;
};
void KeyboardLayoutManager::HandleKeyboardLayoutChanged() {
}
NAN_METHOD(KeyboardLayoutManager::GetCurrentKeyboardLayout) {
Nan::HandleScope scope;
char layoutName[KL_NAMELENGTH];
if (::GetKeyboardLayoutName(layoutName))
info.GetReturnValue().Set(Nan::New(layoutName).ToLocalChecked());
else
info.GetReturnValue().Set(Nan::Undefined());
}
NAN_METHOD(KeyboardLayoutManager::GetCurrentKeyboardLanguage) {
Nan::HandleScope scope;
HKL layout;
DWORD dwThreadId = 0;
HWND hWnd = GetForegroundWindow();
if (hWnd != NULL) {
dwThreadId = GetWindowThreadProcessId(hWnd, NULL);
}
layout = GetKeyboardLayout(dwThreadId);
wchar_t buf[LOCALE_NAME_MAX_LENGTH];
std::wstring wstr;
LCIDToLocaleName(MAKELCID((UINT)layout & 0xFFFF, SORT_DEFAULT), buf, LOCALE_NAME_MAX_LENGTH, 0);
wstr.assign(buf);
std::string str = ToUTF8(wstr);
info.GetReturnValue().Set(Nan::New<String>(str.data(), str.size()).ToLocalChecked());
}
NAN_METHOD(KeyboardLayoutManager::GetInstalledKeyboardLanguages) {
Nan::HandleScope scope;
int layoutCount = GetKeyboardLayoutList(0, NULL);
HKL* layouts = new HKL[layoutCount];
GetKeyboardLayoutList(layoutCount, layouts);
Local<Array> result = Nan::New<Array>(layoutCount);
wchar_t buf[LOCALE_NAME_MAX_LENGTH];
for (int i=0; i < layoutCount; i++) {
std::wstring wstr;
LCIDToLocaleName(MAKELCID((UINT)layouts[i] & 0xFFFF, SORT_DEFAULT), buf, LOCALE_NAME_MAX_LENGTH, 0);
wstr.assign(buf);
std::string str = ToUTF8(wstr);
result->Set(i, Nan::New<String>(str.data(), str.size()).ToLocalChecked());
}
delete[] layouts;
info.GetReturnValue().Set(result);
}
struct KeycodeMapEntry {
UINT scanCode;
const char *dom3Code;
};
#define USB_KEYMAP_DECLARATION static const KeycodeMapEntry keyCodeMap[] =
#define USB_KEYMAP(usb, evdev, xkb, win, mac, code, id) {win, code}
#include "keycode_converter_data.inc"
Local<Value> CharacterForNativeCode(HKL keyboardLayout, UINT keyCode, UINT scanCode,
BYTE *keyboardState, bool shift, bool altGraph) {
memset(keyboardState, 0, 256);
if (shift) {
keyboardState[VK_SHIFT] = 0x80;
}
if (altGraph) {
keyboardState[VK_MENU] = 0x80;
keyboardState[VK_CONTROL] = 0x80;
}
wchar_t characters[5];
int count = ToUnicodeEx(keyCode, scanCode, keyboardState, characters, 5, 0, keyboardLayout);
if (count > 0 && !std::iscntrl(characters[0])) {
return Nan::New<String>(reinterpret_cast<const uint16_t *>(characters), count).ToLocalChecked();
} else {
return Nan::Null();
}
}
NAN_METHOD(KeyboardLayoutManager::GetCurrentKeymap) {
BYTE keyboardState[256];
HKL keyboardLayout = GetKeyboardLayout(0);
Handle<Object> result = Nan::New<Object>();
Local<String> unmodifiedKey = Nan::New("unmodified").ToLocalChecked();
Local<String> withShiftKey = Nan::New("withShift").ToLocalChecked();
Local<String> withAltGraphKey = Nan::New("withAltGraph").ToLocalChecked();
Local<String> withAltGraphShiftKey = Nan::New("withAltGraphShift").ToLocalChecked();
size_t keyCodeMapSize = sizeof(keyCodeMap) / sizeof(keyCodeMap[0]);
for (size_t i = 0; i < keyCodeMapSize; i++) {
const char *dom3Code = keyCodeMap[i].dom3Code;
UINT scanCode = keyCodeMap[i].scanCode;
if (dom3Code && scanCode > 0x0000) {
UINT keyCode = MapVirtualKeyEx(scanCode, MAPVK_VSC_TO_VK, keyboardLayout);
Local<String> dom3CodeKey = Nan::New(dom3Code).ToLocalChecked();
Local<Value> unmodified = CharacterForNativeCode(keyboardLayout, keyCode, scanCode, keyboardState, false, false);
Local<Value> withShift = CharacterForNativeCode(keyboardLayout, keyCode, scanCode, keyboardState, true, false);
Local<Value> withAltGraph = CharacterForNativeCode(keyboardLayout, keyCode, scanCode, keyboardState, false, true);
Local<Value> withAltGraphShift = CharacterForNativeCode(keyboardLayout, keyCode, scanCode, keyboardState, true, true);
if (unmodified->IsString() || withShift->IsString() || withAltGraph->IsString() || withAltGraphShift->IsString()) {
Local<Object> entry = Nan::New<Object>();
entry->Set(unmodifiedKey, unmodified);
entry->Set(withShiftKey, withShift);
entry->Set(withAltGraphKey, withAltGraph);
entry->Set(withAltGraphShiftKey, withAltGraphShift);
result->Set(dom3CodeKey, entry);
}
}
}
info.GetReturnValue().Set(result);
}
<commit_msg>Handle dead keys on Windows<commit_after>#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0601
#undef WINVER
#define WINVER 0x0601
#define SPACE_SCAN_CODE 0x0039
#include "keyboard-layout-manager.h"
#include <string>
#include <cctype>
#include <windows.h>
using namespace v8;
std::string ToUTF8(const std::wstring& string) {
if (string.length() < 1) {
return std::string();
}
// NB: In the pathological case, each character could expand up
// to 4 bytes in UTF8.
int cbLen = (string.length()+1) * sizeof(char) * 4;
char* buf = new char[cbLen];
int retLen = WideCharToMultiByte(CP_UTF8, 0, string.c_str(), string.length(), buf, cbLen, NULL, NULL);
buf[retLen] = 0;
std::string ret;
ret.assign(buf);
return ret;
}
void KeyboardLayoutManager::Init(Handle<Object> exports, Handle<Object> module) {
Nan::HandleScope scope;
Local<FunctionTemplate> newTemplate = Nan::New<FunctionTemplate>(KeyboardLayoutManager::New);
newTemplate->SetClassName(Nan::New<String>("KeyboardLayoutManager").ToLocalChecked());
newTemplate->InstanceTemplate()->SetInternalFieldCount(1);
Local<ObjectTemplate> proto = newTemplate->PrototypeTemplate();
Nan::SetMethod(proto, "getCurrentKeyboardLayout", KeyboardLayoutManager::GetCurrentKeyboardLayout);
Nan::SetMethod(proto, "getCurrentKeyboardLanguage", KeyboardLayoutManager::GetCurrentKeyboardLanguage);
Nan::SetMethod(proto, "getInstalledKeyboardLanguages", KeyboardLayoutManager::GetInstalledKeyboardLanguages);
Nan::SetMethod(proto, "getCurrentKeymap", KeyboardLayoutManager::GetCurrentKeymap);
module->Set(Nan::New("exports").ToLocalChecked(), newTemplate->GetFunction());
}
NODE_MODULE(keyboard_layout_manager, KeyboardLayoutManager::Init)
NAN_METHOD(KeyboardLayoutManager::New) {
Nan::HandleScope scope;
Local<Function> callbackHandle = info[0].As<Function>();
Nan::Callback *callback = new Nan::Callback(callbackHandle);
KeyboardLayoutManager *manager = new KeyboardLayoutManager(callback);
manager->Wrap(info.This());
return;
}
KeyboardLayoutManager::KeyboardLayoutManager(Nan::Callback *callback) : callback(callback) {
}
KeyboardLayoutManager::~KeyboardLayoutManager() {
delete callback;
};
void KeyboardLayoutManager::HandleKeyboardLayoutChanged() {
}
NAN_METHOD(KeyboardLayoutManager::GetCurrentKeyboardLayout) {
Nan::HandleScope scope;
char layoutName[KL_NAMELENGTH];
if (::GetKeyboardLayoutName(layoutName))
info.GetReturnValue().Set(Nan::New(layoutName).ToLocalChecked());
else
info.GetReturnValue().Set(Nan::Undefined());
}
NAN_METHOD(KeyboardLayoutManager::GetCurrentKeyboardLanguage) {
Nan::HandleScope scope;
HKL layout;
DWORD dwThreadId = 0;
HWND hWnd = GetForegroundWindow();
if (hWnd != NULL) {
dwThreadId = GetWindowThreadProcessId(hWnd, NULL);
}
layout = GetKeyboardLayout(dwThreadId);
wchar_t buf[LOCALE_NAME_MAX_LENGTH];
std::wstring wstr;
LCIDToLocaleName(MAKELCID((UINT)layout & 0xFFFF, SORT_DEFAULT), buf, LOCALE_NAME_MAX_LENGTH, 0);
wstr.assign(buf);
std::string str = ToUTF8(wstr);
info.GetReturnValue().Set(Nan::New<String>(str.data(), str.size()).ToLocalChecked());
}
NAN_METHOD(KeyboardLayoutManager::GetInstalledKeyboardLanguages) {
Nan::HandleScope scope;
int layoutCount = GetKeyboardLayoutList(0, NULL);
HKL* layouts = new HKL[layoutCount];
GetKeyboardLayoutList(layoutCount, layouts);
Local<Array> result = Nan::New<Array>(layoutCount);
wchar_t buf[LOCALE_NAME_MAX_LENGTH];
for (int i=0; i < layoutCount; i++) {
std::wstring wstr;
LCIDToLocaleName(MAKELCID((UINT)layouts[i] & 0xFFFF, SORT_DEFAULT), buf, LOCALE_NAME_MAX_LENGTH, 0);
wstr.assign(buf);
std::string str = ToUTF8(wstr);
result->Set(i, Nan::New<String>(str.data(), str.size()).ToLocalChecked());
}
delete[] layouts;
info.GetReturnValue().Set(result);
}
struct KeycodeMapEntry {
UINT scanCode;
const char *dom3Code;
};
#define USB_KEYMAP_DECLARATION static const KeycodeMapEntry keyCodeMap[] =
#define USB_KEYMAP(usb, evdev, xkb, win, mac, code, id) {win, code}
#include "keycode_converter_data.inc"
Local<Value> CharacterForNativeCode(HKL keyboardLayout, UINT keyCode, UINT scanCode,
BYTE *keyboardState, bool shift, bool altGraph) {
memset(keyboardState, 0, 256);
if (shift) {
keyboardState[VK_SHIFT] = 0x80;
}
if (altGraph) {
keyboardState[VK_MENU] = 0x80;
keyboardState[VK_CONTROL] = 0x80;
}
wchar_t characters[5];
int count = ToUnicodeEx(keyCode, scanCode, keyboardState, characters, 5, 0, keyboardLayout);
if (count == -1) { // Dead key
Local<String> result = Nan::New<String>(reinterpret_cast<const uint16_t *>(characters), count).ToLocalChecked();
// Clear dead key out of kernel-mode keyboard buffer so subsequent translations are not affected
UINT spaceKeyCode = MapVirtualKeyEx(SPACE_SCAN_CODE, MAPVK_VSC_TO_VK, keyboardLayout);
ToUnicodeEx(spaceKeyCode, SPACE_SCAN_CODE, keyboardState, characters, 5, 0, keyboardLayout);
return result;
}
if (count > 0 && !std::iscntrl(characters[0])) {
return Nan::New<String>(reinterpret_cast<const uint16_t *>(characters), count).ToLocalChecked();
} else {
return Nan::Null();
}
}
NAN_METHOD(KeyboardLayoutManager::GetCurrentKeymap) {
BYTE keyboardState[256];
HKL keyboardLayout = GetKeyboardLayout(0);
Handle<Object> result = Nan::New<Object>();
Local<String> unmodifiedKey = Nan::New("unmodified").ToLocalChecked();
Local<String> withShiftKey = Nan::New("withShift").ToLocalChecked();
Local<String> withAltGraphKey = Nan::New("withAltGraph").ToLocalChecked();
Local<String> withAltGraphShiftKey = Nan::New("withAltGraphShift").ToLocalChecked();
size_t keyCodeMapSize = sizeof(keyCodeMap) / sizeof(keyCodeMap[0]);
for (size_t i = 0; i < keyCodeMapSize; i++) {
const char *dom3Code = keyCodeMap[i].dom3Code;
UINT scanCode = keyCodeMap[i].scanCode;
if (dom3Code && scanCode > 0x0000) {
UINT keyCode = MapVirtualKeyEx(scanCode, MAPVK_VSC_TO_VK, keyboardLayout);
Local<String> dom3CodeKey = Nan::New(dom3Code).ToLocalChecked();
Local<Value> unmodified = CharacterForNativeCode(keyboardLayout, keyCode, scanCode, keyboardState, false, false);
Local<Value> withShift = CharacterForNativeCode(keyboardLayout, keyCode, scanCode, keyboardState, true, false);
Local<Value> withAltGraph = CharacterForNativeCode(keyboardLayout, keyCode, scanCode, keyboardState, false, true);
Local<Value> withAltGraphShift = CharacterForNativeCode(keyboardLayout, keyCode, scanCode, keyboardState, true, true);
if (unmodified->IsString() || withShift->IsString() || withAltGraph->IsString() || withAltGraphShift->IsString()) {
Local<Object> entry = Nan::New<Object>();
entry->Set(unmodifiedKey, unmodified);
entry->Set(withShiftKey, withShift);
entry->Set(withAltGraphKey, withAltGraph);
entry->Set(withAltGraphShiftKey, withAltGraphShift);
result->Set(dom3CodeKey, entry);
}
}
}
info.GetReturnValue().Set(result);
}
<|endoftext|> |
<commit_before>#include <test/unit/mcmc/hmc/mock_hmc.hpp>
#include <stan/interface_callbacks/writer/stream_writer.hpp>
#include <stan/mcmc/hmc/nuts/base_nuts.hpp>
#include <stan/mcmc/hmc/integrators/expl_leapfrog.hpp>
#include <boost/random/additive_combine.hpp>
#include <gtest/gtest.h>
typedef boost::ecuyer1988 rng_t;
namespace stan {
namespace mcmc {
class mock_nuts: public base_nuts<mock_model,
mock_hamiltonian,
mock_integrator,
rng_t> {
public:
mock_nuts(const mock_model &m, rng_t& rng)
: base_nuts<mock_model,mock_hamiltonian,mock_integrator,rng_t>(m, rng)
{ }
};
// Mock Hamiltonian
template <typename M, typename BaseRNG>
class divergent_hamiltonian
: public base_hamiltonian<M, ps_point, BaseRNG> {
public:
divergent_hamiltonian(const M& m)
: base_hamiltonian<M, ps_point, BaseRNG>(m) {}
double T(ps_point& z) { return 0; }
double tau(ps_point& z) { return T(z); }
double phi(ps_point& z) { return this->V(z); }
double dG_dt(ps_point& z,
interface_callbacks::writer::base_writer& info_writer,
interface_callbacks::writer::base_writer& error_writer) {
return 2;
}
Eigen::VectorXd dtau_dq(
ps_point& z,
interface_callbacks::writer::base_writer& info_writer,
interface_callbacks::writer::base_writer& error_writer) {
return Eigen::VectorXd::Zero(this->model_.num_params_r());
}
Eigen::VectorXd dtau_dp(ps_point& z) {
return Eigen::VectorXd::Zero(this->model_.num_params_r());
}
Eigen::VectorXd dphi_dq(
ps_point& z,
interface_callbacks::writer::base_writer& info_writer,
interface_callbacks::writer::base_writer& error_writer) {
return Eigen::VectorXd::Zero(this->model_.num_params_r());
}
void init(ps_point& z,
interface_callbacks::writer::base_writer& info_writer,
interface_callbacks::writer::base_writer& error_writer) {
z.V = 0;
}
void sample_p(ps_point& z, BaseRNG& rng) {};
void update_potential_gradient(
ps_point& z,
interface_callbacks::writer::base_writer& info_writer,
interface_callbacks::writer::base_writer& error_writer) {
z.V += 500;
}
};
class divergent_nuts: public base_nuts<mock_model,
divergent_hamiltonian,
expl_leapfrog,
rng_t> {
public:
divergent_nuts(const mock_model &m, rng_t& rng)
: base_nuts<mock_model, divergent_hamiltonian, expl_leapfrog,rng_t>(m, rng)
{ }
};
}
}
TEST(McmcNutsBaseNuts, set_max_depth) {
rng_t base_rng(0);
Eigen::VectorXd q(2);
q(0) = 5;
q(1) = 1;
stan::mcmc::mock_model model(q.size());
stan::mcmc::mock_nuts sampler(model, base_rng);
int old_max_depth = 1;
sampler.set_max_depth(old_max_depth);
EXPECT_EQ(old_max_depth, sampler.get_max_depth());
sampler.set_max_depth(-1);
EXPECT_EQ(old_max_depth, sampler.get_max_depth());
}
TEST(McmcNutsBaseNuts, set_max_delta) {
rng_t base_rng(0);
Eigen::VectorXd q(2);
q(0) = 5;
q(1) = 1;
stan::mcmc::mock_model model(q.size());
stan::mcmc::mock_nuts sampler(model, base_rng);
double old_max_delta = 10;
sampler.set_max_delta(old_max_delta);
EXPECT_EQ(old_max_delta, sampler.get_max_delta());
}
TEST(McmcNutsBaseNuts, build_tree) {
rng_t base_rng(0);
int model_size = 1;
double init_momentum = 1.5;
stan::mcmc::ps_point z_init(model_size);
z_init.q(0) = 0;
z_init.p(0) = init_momentum;
stan::mcmc::ps_point z_propose(model_size);
Eigen::VectorXd rho = z_init.p;
double log_sum_weight = -std::numeric_limits<double>::infinity();
double H0 = -0.1;
int n_leapfrog = 0;
double sum_metro_prob = 0;
stan::mcmc::mock_model model(model_size);
stan::mcmc::mock_nuts sampler(model, base_rng);
sampler.set_nominal_stepsize(1);
sampler.set_stepsize_jitter(0);
sampler.sample_stepsize();
sampler.z() = z_init;
std::stringstream output;
stan::interface_callbacks::writer::stream_writer writer(output);
std::stringstream error_stream;
stan::interface_callbacks::writer::stream_writer error_writer(error_stream);
bool valid_subtree = sampler.build_tree(3, rho, z_propose,
H0, 1, n_leapfrog, log_sum_weight,
sum_metro_prob, writer, error_writer);
EXPECT_TRUE(valid_subtree);
EXPECT_EQ(init_momentum * (n_leapfrog + 1), rho(0));
EXPECT_EQ(8 * init_momentum, sampler.z().q(0));
EXPECT_EQ(init_momentum, sampler.z().p(0));
EXPECT_EQ(8, n_leapfrog);
EXPECT_FLOAT_EQ(H0 + std::log(n_leapfrog), log_sum_weight);
EXPECT_FLOAT_EQ(std::exp(H0) * n_leapfrog, sum_metro_prob);
EXPECT_EQ("", output.str());
EXPECT_EQ("", error_stream.str());
}
TEST(McmcNutsBaseNuts, divergence_test) {
rng_t base_rng(0);
int model_size = 1;
double init_momentum = 1.5;
stan::mcmc::ps_point z_init(model_size);
z_init.q(0) = 0;
z_init.p(0) = init_momentum;
stan::mcmc::ps_point z_propose(model_size);
Eigen::VectorXd rho = z_init.p;
double log_sum_weight = -std::numeric_limits<double>::infinity();
double H0 = -0.1;
int n_leapfrog = 0;
double sum_metro_prob = 0;
stan::mcmc::mock_model model(model_size);
stan::mcmc::divergent_nuts sampler(model, base_rng);
sampler.set_nominal_stepsize(1);
sampler.set_stepsize_jitter(0);
sampler.sample_stepsize();
sampler.z() = z_init;
std::stringstream output;
stan::interface_callbacks::writer::stream_writer writer(output);
std::stringstream error_stream;
stan::interface_callbacks::writer::stream_writer error_writer(error_stream);
bool valid_subtree = 0;
sampler.z().V = -750;
valid_subtree = sampler.build_tree(0, rho, z_propose,
H0, 1, n_leapfrog, log_sum_weight,
sum_metro_prob,
writer, error_writer);
EXPECT_TRUE(valid_subtree);
EXPECT_EQ(0, sampler.divergent_);
sampler.z().V = -250;
valid_subtree = sampler.build_tree(0, rho, z_propose,
H0, 1, n_leapfrog, log_sum_weight,
sum_metro_prob,
writer, error_writer);
EXPECT_TRUE(valid_subtree);
EXPECT_EQ(0, sampler.divergent_);
sampler.z().V = 750;
valid_subtree = sampler.build_tree(0, rho, z_propose,
H0, 1, n_leapfrog, log_sum_weight,
sum_metro_prob,
writer, error_writer);
EXPECT_FALSE(valid_subtree);
EXPECT_EQ(1, sampler.divergent_);
EXPECT_EQ("", output.str());
EXPECT_EQ("", error_stream.str());
}
TEST(McmcNutsBaseNuts, transition) {
rng_t base_rng(0);
int model_size = 1;
double init_momentum = 1.5;
stan::mcmc::ps_point z_init(model_size);
z_init.q(0) = 0;
z_init.p(0) = init_momentum;
stan::mcmc::mock_model model(model_size);
stan::mcmc::mock_nuts sampler(model, base_rng);
sampler.set_nominal_stepsize(1);
sampler.set_stepsize_jitter(0);
sampler.sample_stepsize();
sampler.z() = z_init;
std::stringstream output_stream;
stan::interface_callbacks::writer::stream_writer writer(output_stream);
std::stringstream error_stream;
stan::interface_callbacks::writer::stream_writer error_writer(error_stream);
stan::mcmc::sample init_sample(z_init.q, 0, 0);
stan::mcmc::sample s = sampler.transition(init_sample, writer, error_writer);
EXPECT_EQ(31.5, s.cont_params()(0));
EXPECT_EQ(0, s.log_prob());
EXPECT_EQ(1, s.accept_stat());
EXPECT_EQ("", output_stream.str());
EXPECT_EQ("", error_stream.str());
}
<commit_msg>Updated base_nuts test, adding coverage for rho aggregation across intermediate subtrees<commit_after>#include <test/unit/mcmc/hmc/mock_hmc.hpp>
#include <stan/interface_callbacks/writer/stream_writer.hpp>
#include <stan/mcmc/hmc/nuts/base_nuts.hpp>
#include <stan/mcmc/hmc/integrators/expl_leapfrog.hpp>
#include <vector>
#include <boost/random/additive_combine.hpp>
#include <gtest/gtest.h>
typedef boost::ecuyer1988 rng_t;
namespace stan {
namespace mcmc {
class mock_nuts: public base_nuts<mock_model,
mock_hamiltonian,
mock_integrator,
rng_t> {
public:
mock_nuts(const mock_model &m, rng_t& rng)
: base_nuts<mock_model,mock_hamiltonian,mock_integrator,rng_t>(m, rng)
{ }
};
class rho_inspector_mock_nuts: public base_nuts<mock_model,
mock_hamiltonian,
mock_integrator,
rng_t> {
public:
std::vector<double> rho_values;
rho_inspector_mock_nuts(const mock_model &m, rng_t& rng)
: base_nuts<mock_model,mock_hamiltonian,mock_integrator,rng_t>(m, rng)
{ }
bool compute_criterion(Eigen::VectorXd& p_sharp_minus,
Eigen::VectorXd& p_sharp_plus,
Eigen::VectorXd& rho) {
rho_values.push_back(rho(0));
return true;
}
};
// Mock Hamiltonian
template <typename M, typename BaseRNG>
class divergent_hamiltonian
: public base_hamiltonian<M, ps_point, BaseRNG> {
public:
divergent_hamiltonian(const M& m)
: base_hamiltonian<M, ps_point, BaseRNG>(m) {}
double T(ps_point& z) { return 0; }
double tau(ps_point& z) { return T(z); }
double phi(ps_point& z) { return this->V(z); }
double dG_dt(ps_point& z,
interface_callbacks::writer::base_writer& info_writer,
interface_callbacks::writer::base_writer& error_writer) {
return 2;
}
Eigen::VectorXd dtau_dq(
ps_point& z,
interface_callbacks::writer::base_writer& info_writer,
interface_callbacks::writer::base_writer& error_writer) {
return Eigen::VectorXd::Zero(this->model_.num_params_r());
}
Eigen::VectorXd dtau_dp(ps_point& z) {
return Eigen::VectorXd::Zero(this->model_.num_params_r());
}
Eigen::VectorXd dphi_dq(
ps_point& z,
interface_callbacks::writer::base_writer& info_writer,
interface_callbacks::writer::base_writer& error_writer) {
return Eigen::VectorXd::Zero(this->model_.num_params_r());
}
void init(ps_point& z,
interface_callbacks::writer::base_writer& info_writer,
interface_callbacks::writer::base_writer& error_writer) {
z.V = 0;
}
void sample_p(ps_point& z, BaseRNG& rng) {};
void update_potential_gradient(
ps_point& z,
interface_callbacks::writer::base_writer& info_writer,
interface_callbacks::writer::base_writer& error_writer) {
z.V += 500;
}
};
class divergent_nuts: public base_nuts<mock_model,
divergent_hamiltonian,
expl_leapfrog,
rng_t> {
public:
divergent_nuts(const mock_model &m, rng_t& rng)
: base_nuts<mock_model, divergent_hamiltonian, expl_leapfrog,rng_t>(m, rng)
{ }
};
}
}
TEST(McmcNutsBaseNuts, set_max_depth_test) {
rng_t base_rng(0);
Eigen::VectorXd q(2);
q(0) = 5;
q(1) = 1;
stan::mcmc::mock_model model(q.size());
stan::mcmc::mock_nuts sampler(model, base_rng);
int old_max_depth = 1;
sampler.set_max_depth(old_max_depth);
EXPECT_EQ(old_max_depth, sampler.get_max_depth());
sampler.set_max_depth(-1);
EXPECT_EQ(old_max_depth, sampler.get_max_depth());
}
TEST(McmcNutsBaseNuts, set_max_delta_test) {
rng_t base_rng(0);
Eigen::VectorXd q(2);
q(0) = 5;
q(1) = 1;
stan::mcmc::mock_model model(q.size());
stan::mcmc::mock_nuts sampler(model, base_rng);
double old_max_delta = 10;
sampler.set_max_delta(old_max_delta);
EXPECT_EQ(old_max_delta, sampler.get_max_delta());
}
TEST(McmcNutsBaseNuts, build_tree_test) {
rng_t base_rng(0);
int model_size = 1;
double init_momentum = 1.5;
stan::mcmc::ps_point z_init(model_size);
z_init.q(0) = 0;
z_init.p(0) = init_momentum;
stan::mcmc::ps_point z_propose(model_size);
Eigen::VectorXd p_sharp_left = Eigen::VectorXd::Zero(model_size);
Eigen::VectorXd p_sharp_right = Eigen::VectorXd::Zero(model_size);
Eigen::VectorXd rho = z_init.p;
double log_sum_weight = -std::numeric_limits<double>::infinity();
double H0 = -0.1;
int n_leapfrog = 0;
double sum_metro_prob = 0;
stan::mcmc::mock_model model(model_size);
stan::mcmc::mock_nuts sampler(model, base_rng);
sampler.set_nominal_stepsize(1);
sampler.set_stepsize_jitter(0);
sampler.sample_stepsize();
sampler.z() = z_init;
std::stringstream output;
stan::interface_callbacks::writer::stream_writer writer(output);
std::stringstream error_stream;
stan::interface_callbacks::writer::stream_writer error_writer(error_stream);
bool valid_subtree = sampler.build_tree(3, z_propose,
p_sharp_left, p_sharp_right, rho,
H0, 1, n_leapfrog, log_sum_weight,
sum_metro_prob, writer, error_writer);
EXPECT_TRUE(valid_subtree);
EXPECT_EQ(init_momentum * (n_leapfrog + 1), rho(0));
EXPECT_EQ(1, p_sharp_left(0));
EXPECT_EQ(1, p_sharp_right(0));
EXPECT_EQ(8 * init_momentum, sampler.z().q(0));
EXPECT_EQ(init_momentum, sampler.z().p(0));
EXPECT_EQ(8, n_leapfrog);
EXPECT_FLOAT_EQ(H0 + std::log(n_leapfrog), log_sum_weight);
EXPECT_FLOAT_EQ(std::exp(H0) * n_leapfrog, sum_metro_prob);
EXPECT_EQ("", output.str());
EXPECT_EQ("", error_stream.str());
}
TEST(McmcNutsBaseNuts, rho_aggregation_test) {
rng_t base_rng(0);
int model_size = 1;
double init_momentum = 1.5;
stan::mcmc::ps_point z_init(model_size);
z_init.q(0) = 0;
z_init.p(0) = init_momentum;
stan::mcmc::ps_point z_propose(model_size);
Eigen::VectorXd p_sharp_left = Eigen::VectorXd::Zero(model_size);
Eigen::VectorXd p_sharp_right = Eigen::VectorXd::Zero(model_size);
Eigen::VectorXd rho = z_init.p;
double log_sum_weight = -std::numeric_limits<double>::infinity();
double H0 = -0.1;
int n_leapfrog = 0;
double sum_metro_prob = 0;
stan::mcmc::mock_model model(model_size);
stan::mcmc::rho_inspector_mock_nuts sampler(model, base_rng);
sampler.set_nominal_stepsize(1);
sampler.set_stepsize_jitter(0);
sampler.sample_stepsize();
sampler.z() = z_init;
std::stringstream output;
stan::interface_callbacks::writer::stream_writer writer(output);
std::stringstream error_stream;
stan::interface_callbacks::writer::stream_writer error_writer(error_stream);
sampler.build_tree(3, z_propose,
p_sharp_left, p_sharp_right, rho,
H0, 1, n_leapfrog, log_sum_weight,
sum_metro_prob, writer, error_writer);
EXPECT_EQ(7, sampler.rho_values.size());
EXPECT_EQ(2 * init_momentum, sampler.rho_values.at(0));
EXPECT_EQ(2 * init_momentum, sampler.rho_values.at(1));
EXPECT_EQ(4 * init_momentum, sampler.rho_values.at(2));
EXPECT_EQ(2 * init_momentum, sampler.rho_values.at(3));
EXPECT_EQ(2 * init_momentum, sampler.rho_values.at(4));
EXPECT_EQ(4 * init_momentum, sampler.rho_values.at(5));
EXPECT_EQ(8 * init_momentum, sampler.rho_values.at(6));
}
TEST(McmcNutsBaseNuts, divergence_test) {
rng_t base_rng(0);
int model_size = 1;
double init_momentum = 1.5;
stan::mcmc::ps_point z_init(model_size);
z_init.q(0) = 0;
z_init.p(0) = init_momentum;
stan::mcmc::ps_point z_propose(model_size);
Eigen::VectorXd p_sharp_left = Eigen::VectorXd::Zero(model_size);
Eigen::VectorXd p_sharp_right = Eigen::VectorXd::Zero(model_size);
Eigen::VectorXd rho = z_init.p;
double log_sum_weight = -std::numeric_limits<double>::infinity();
double H0 = -0.1;
int n_leapfrog = 0;
double sum_metro_prob = 0;
stan::mcmc::mock_model model(model_size);
stan::mcmc::divergent_nuts sampler(model, base_rng);
sampler.set_nominal_stepsize(1);
sampler.set_stepsize_jitter(0);
sampler.sample_stepsize();
sampler.z() = z_init;
std::stringstream output;
stan::interface_callbacks::writer::stream_writer writer(output);
std::stringstream error_stream;
stan::interface_callbacks::writer::stream_writer error_writer(error_stream);
bool valid_subtree = 0;
sampler.z().V = -750;
valid_subtree = sampler.build_tree(0, z_propose,
p_sharp_left, p_sharp_right, rho,
H0, 1, n_leapfrog, log_sum_weight,
sum_metro_prob,
writer, error_writer);
EXPECT_TRUE(valid_subtree);
EXPECT_FALSE(sampler.divergent_);
sampler.z().V = -250;
valid_subtree = sampler.build_tree(0, z_propose,
p_sharp_left, p_sharp_right, rho,
H0, 1, n_leapfrog, log_sum_weight,
sum_metro_prob,
writer, error_writer);
EXPECT_TRUE(valid_subtree);
EXPECT_FALSE(sampler.divergent_);
sampler.z().V = 750;
valid_subtree = sampler.build_tree(0, z_propose,
p_sharp_left, p_sharp_right, rho,
H0, 1, n_leapfrog, log_sum_weight,
sum_metro_prob,
writer, error_writer);
EXPECT_FALSE(valid_subtree);
EXPECT_TRUE(sampler.divergent_);
EXPECT_EQ("", output.str());
EXPECT_EQ("", error_stream.str());
}
TEST(McmcNutsBaseNuts, transition) {
rng_t base_rng(0);
int model_size = 1;
double init_momentum = 1.5;
stan::mcmc::ps_point z_init(model_size);
z_init.q(0) = 0;
z_init.p(0) = init_momentum;
stan::mcmc::mock_model model(model_size);
stan::mcmc::mock_nuts sampler(model, base_rng);
sampler.set_nominal_stepsize(1);
sampler.set_stepsize_jitter(0);
sampler.sample_stepsize();
sampler.z() = z_init;
std::stringstream output_stream;
stan::interface_callbacks::writer::stream_writer writer(output_stream);
std::stringstream error_stream;
stan::interface_callbacks::writer::stream_writer error_writer(error_stream);
stan::mcmc::sample init_sample(z_init.q, 0, 0);
// Transition will expand trajectory until max_depth is hit
stan::mcmc::sample s = sampler.transition(init_sample, writer, error_writer);
EXPECT_EQ(sampler.get_max_depth(), sampler.depth_);
EXPECT_EQ((2 << (sampler.get_max_depth() - 1)) - 1, sampler.n_leapfrog_);
EXPECT_FALSE(sampler.divergent_);
EXPECT_EQ(21 * init_momentum, s.cont_params()(0));
EXPECT_EQ(0, s.log_prob());
EXPECT_EQ(1, s.accept_stat());
EXPECT_EQ("", output_stream.str());
EXPECT_EQ("", error_stream.str());
}
<|endoftext|> |
<commit_before>#include "assets_browser.h"
#include "halley/tools/project/project.h"
#include "halley/core/resources/resource_locator.h"
#include "halley/core/resources/standard_resources.h"
#include "halley/ui/widgets/ui_label.h"
#include "halley/ui/widgets/ui_list.h"
#include "animation_editor.h"
#include "asset_editor.h"
#include "asset_editor_window.h"
#include "metadata_editor.h"
#include "new_asset_window.h"
#include "prefab_editor.h"
#include "halley/audio/audio_object.h"
#include "halley/tools/file/filesystem.h"
#include "src/ui/editor_ui_factory.h"
#include "src/ui/project_window.h"
using namespace Halley;
AssetsBrowser::AssetsBrowser(EditorUIFactory& factory, Project& project, ProjectWindow& projectWindow)
: UIWidget("assets_editor", {}, UISizer())
, factory(factory)
, project(project)
, projectWindow(projectWindow)
, curSrcPath(".")
, fuzzyMatcher(false, 100)
{
loadResources();
makeUI();
setAssetSrcMode(true);
}
void AssetsBrowser::openAsset(AssetType type, const String& assetId)
{
getWidgetAs<UITextInput>("assetSearch")->setText("");
auto target = project.getImportAssetsDatabase().getPrimaryInputFile(type, assetId);
openFile(std::move(target));
}
void AssetsBrowser::openFile(const Path& path)
{
if (!path.isEmpty()) {
curSrcPath = path.parentPath();
refreshList();
assetList->setSelectedOptionId(path.toString());
loadAsset(path.toString(), true);
}
}
void AssetsBrowser::replaceAssetTab(AssetType oldType, const String& oldId, AssetType newType, const String& newId)
{
const auto oldTarget = project.getImportAssetsDatabase().getPrimaryInputFile(oldType, oldId);
const auto newTarget = project.getImportAssetsDatabase().getPrimaryInputFile(newType, newId);
assetTabs->replaceAssetTab(oldTarget.toString(), newTarget.toString());
}
bool AssetsBrowser::requestQuit(std::function<void()> callback)
{
return assetTabs->requestQuit(std::move(callback));
}
void AssetsBrowser::saveTab()
{
assetTabs->saveCurrentTab();
}
void AssetsBrowser::saveAllTabs()
{
assetTabs->saveAllTabs();
}
void AssetsBrowser::closeTab()
{
assetTabs->closeCurrentTab();
}
void AssetsBrowser::moveTabFocus(int delta)
{
assetTabs->moveTabFocus(delta);
}
std::shared_ptr<AssetEditorWindow> AssetsBrowser::getActiveWindow() const
{
return assetTabs->getActiveWindow();
}
void AssetsBrowser::loadResources()
{
project.addAssetReloadCallback([=] (gsl::span<const String> assets)
{
refreshAssets(assets);
});
}
void AssetsBrowser::makeUI()
{
UIWidget::add(factory.makeUI("halley/assets_browser"), 1);
assetList = getWidgetAs<UIList>("assetList");
assetList->setSingleClickAccept(false);
assetTabs = std::make_shared<AssetBrowserTabs>(factory, project, projectWindow);
getWidget("assetEditorContainer")->add(assetTabs, 1);
setHandle(UIEventType::ListSelectionChanged, "assetType", [=] (const UIEvent& event)
{
listAssets(fromString<AssetType>(event.getStringData()));
});
setHandle(UIEventType::ListSelectionChanged, "assetList", [=] (const UIEvent& event)
{
loadAsset(event.getStringData(), false);
});
setHandle(UIEventType::ListAccept, "assetList", [=] (const UIEvent& event)
{
loadAsset(event.getStringData(), true);
});
setHandle(UIEventType::TextChanged, "assetSearch", [=] (const UIEvent& event)
{
setFilter(event.getStringData());
});
setHandle(UIEventType::ButtonClicked, "addAsset", [=] (const UIEvent& event)
{
addAsset();
});
setHandle(UIEventType::ButtonClicked, "removeAsset", [=] (const UIEvent& event)
{
removeAsset();
});
setHandle(UIEventType::ButtonClicked, "collapseButton", [=] (const UIEvent& event)
{
setCollapsed(!collapsed);
});
updateAddRemoveButtons();
doSetCollapsed(projectWindow.getSetting(EditorSettingType::Editor, "assetBrowserCollapse").asBool(false));
}
void AssetsBrowser::setAssetSrcMode(bool enabled)
{
assetSrcMode = enabled;
assetTabs->setAssetSrcMode(enabled);
getWidget("assetType")->setActive(!assetSrcMode);
if (assetSrcMode) {
listAssetSources();
} else {
listAssets(AssetType::Sprite);
}
}
void AssetsBrowser::listAssetSources()
{
if (!assetNames) {
assetNames = project.getAssetSrcList();
std::sort(assetNames->begin(), assetNames->end()); // Is this even needed?
fuzzyMatcher.clear();
fuzzyMatcher.addStrings(assetNames.value());
}
if (filter.isEmpty()) {
setListContents(assetNames.value(), curSrcPath, false);
} else {
Vector<String> filteredList;
auto result = fuzzyMatcher.match(filter);
filteredList.reserve(result.size());
for (const auto& r: result) {
filteredList.push_back(r.getString());
}
setListContents(filteredList, curSrcPath, true);
}
}
void AssetsBrowser::listAssets(AssetType type)
{
curType = type;
if (curPaths.find(type) == curPaths.end()) {
curPaths[type] = Path(".");
}
const auto curPath = curPaths[type];
auto assets = project.getGameResources().ofType(type).enumerate();
std::sort(assets.begin(), assets.end());
setListContents(assets, curPath, false);
}
void AssetsBrowser::setListContents(Vector<String> assets, const Path& curPath, bool flat)
{
{
Hash::Hasher hasher;
for (const auto& asset: assets) {
hasher.feed(asset);
}
hasher.feed(curPath.toString());
const auto hash = hasher.digest();
if (curHash == hash) {
return;
}
curHash = hash;
}
std::optional<String> selectOption;
{
Hash::Hasher hasher;
hasher.feed(curPath.toString());
const auto hash = hasher.digest();
if (curDirHash == hash) {
selectOption = assetList->getSelectedOptionId();
}
curDirHash = hash;
}
assetList->setScrollToSelection(false);
clearAssetList();
if (flat) {
for (auto& a: assets) {
addFileToList(a);
}
} else {
std::set<String> dirs;
Vector<String> files;
for (auto& a: assets) {
auto relPath = Path("./" + a).makeRelativeTo(curPath);
if (relPath.getNumberPaths() == 1) {
files.emplace_back(a);
} else {
auto start = relPath.getFront(1);
dirs.insert(start.toString());
}
}
for (const auto& dir: dirs) {
addDirToList(curPath, dir);
}
for (const auto& file: files) {
addFileToList(file);
}
}
if (selectOption) {
assetList->setSelectedOptionId(selectOption.value());
}
assetList->setScrollToSelection(true);
if (pendingOpen) {
assetList->setSelectedOptionId(pendingOpen->toString());
loadAsset(pendingOpen->toString(), true);
pendingOpen.reset();
}
}
void AssetsBrowser::clearAssetList()
{
assetList->clear();
}
void AssetsBrowser::addDirToList(const Path& curPath, const String& dir)
{
const auto icon = std::make_shared<UIImage>(factory.makeDirectoryIcon(dir == ".."));
/*
std::optional<ImportAssetType> assetTypeDir;
if (curPath == ".") {
if (dir == "shader") {
assetTypeDir = ImportAssetType::Shader;
}
}
if (assetTypeDir) {
icon->add(std::make_shared<UIImage>(factory.makeImportAssetTypeIcon(assetTypeDir.value())), 1, {}, UISizerAlignFlags::Centre);
}
*/
auto sizer = std::make_shared<UISizer>();
sizer->add(icon, 0, Vector4f(0, 0, 4, 0));
sizer->add(assetList->makeLabel("", LocalisedString::fromUserString(dir)));
assetList->addItem(dir + "/.", std::move(sizer));
}
void AssetsBrowser::addFileToList(const Path& path)
{
auto type = project.getAssetImporter()->getImportAssetType(path, false);
auto sizer = std::make_shared<UISizer>();
sizer->add(std::make_shared<UIImage>(factory.makeImportAssetTypeIcon(type)), 0, Vector4f(0, 0, 4, 0));
sizer->add(assetList->makeLabel("", LocalisedString::fromUserString(path.getFilename().toString())));
assetList->addItem(path.toString(), std::move(sizer));
//assetList->addTextItem(path.toString(), LocalisedString::fromUserString(path.getFilename().toString()));
}
void AssetsBrowser::refreshList()
{
if (assetSrcMode) {
listAssetSources();
} else {
listAssets(curType);
}
}
void AssetsBrowser::setFilter(const String& f)
{
if (filter != f) {
filter = f.asciiLower();
refreshList();
}
}
void AssetsBrowser::loadAsset(const String& name, bool doubleClick)
{
lastClickedAsset = name;
updateAddRemoveButtons();
auto& curPath = assetSrcMode ? curSrcPath : curPaths[curType];
if (name.endsWith("/.")) {
if (doubleClick) {
curPath = curPath / name;
refreshList();
}
} else {
if (doubleClick) {
assetTabs->load(assetSrcMode ? std::optional<AssetType>() : curType, name);
}
}
}
void AssetsBrowser::refreshAssets(gsl::span<const String> assets)
{
assetNames.reset();
refreshList();
assetTabs->refreshAssets();
}
void AssetsBrowser::updateAddRemoveButtons()
{
// TODO: refactor updateAddRemoveButtons/addAsset/removeAsset?
const auto stem = curSrcPath.getFront(1).string();
const bool canAdd = stem == "prefab" || stem == "scene" || stem == "audio_object" || stem == "audio_event" || stem == "ui";
const bool canRemove = !lastClickedAsset.isEmpty() && !lastClickedAsset.endsWith("/.");
getWidget("addAsset")->setEnabled(canAdd);
getWidget("removeAsset")->setEnabled(canRemove);
}
void AssetsBrowser::addAsset()
{
// TODO: refactor updateAddRemoveButtons/addAsset/removeAsset?
const auto assetType = curSrcPath.getFront(1).string();
getRoot()->addChild(std::make_shared<NewAssetWindow>(factory, [=] (std::optional<String> newName)
{
if (newName) {
if (assetType == "prefab") {
Prefab prefab;
prefab.makeDefault();
addAsset(newName.value() + ".prefab", prefab.toYAML());
} else if (assetType == "scene") {
Scene scene;
scene.makeDefault();
addAsset(newName.value() + ".scene", scene.toYAML());
} else if (assetType == "audio_object") {
AudioObject object;
object.makeDefault();
addAsset(newName.value() + ".yaml", object.toYAML());
} else if (assetType == "audio_event") {
AudioEvent audioEvent;
audioEvent.makeDefault();
addAsset(newName.value() + ".yaml", audioEvent.toYAML());
} else if (assetType == "ui") {
UIDefinition ui;
ui.makeDefault();
addAsset(newName.value() + ".yaml", ui.toYAML());
}
}
}));
}
void AssetsBrowser::addAsset(Path path, std::string_view data)
{
const auto fullPath = curSrcPath / path;
pendingOpen = fullPath;
project.writeAssetToDisk(fullPath, data);
}
void AssetsBrowser::removeAsset()
{
// TODO: refactor updateAddRemoveButtons/addAsset/removeAsset?
assetList->setItemActive(lastClickedAsset, false);
FileSystem::remove(project.getAssetsSrcPath() / lastClickedAsset);
}
void AssetsBrowser::setCollapsed(bool collapsed)
{
doSetCollapsed(collapsed);
projectWindow.setSetting(EditorSettingType::Editor, "assetBrowserCollapse", ConfigNode(collapsed));
}
void AssetsBrowser::doSetCollapsed(bool c)
{
if (collapsed != c) {
collapsed = c;
auto button = getWidgetAs<UIButton>("collapseButton");
button->setLabel(LocalisedString::fromHardcodedString(collapsed ? ">>" : "<< Collapse"));
auto* parent = dynamic_cast<UIWidget*>(button->getParent());
if (parent) {
parent->getSizer()[0].setBorder(collapsed ? Vector4f(-10, 0, -15, 0) : Vector4f(0, 0, 0, 5));
}
//getWidget("collapseBorder")->setActive(!collapsed);
getWidget("assetBrowsePanel")->setActive(!collapsed);
}
}
<commit_msg>Add support for creating new Comet scripts via UI<commit_after>#include "assets_browser.h"
#include "halley/tools/project/project.h"
#include "halley/core/resources/resource_locator.h"
#include "halley/core/resources/standard_resources.h"
#include "halley/ui/widgets/ui_label.h"
#include "halley/ui/widgets/ui_list.h"
#include "animation_editor.h"
#include "asset_editor.h"
#include "asset_editor_window.h"
#include "metadata_editor.h"
#include "new_asset_window.h"
#include "prefab_editor.h"
#include "halley/audio/audio_object.h"
#include "halley/tools/file/filesystem.h"
#include "src/ui/editor_ui_factory.h"
#include "src/ui/project_window.h"
using namespace Halley;
AssetsBrowser::AssetsBrowser(EditorUIFactory& factory, Project& project, ProjectWindow& projectWindow)
: UIWidget("assets_editor", {}, UISizer())
, factory(factory)
, project(project)
, projectWindow(projectWindow)
, curSrcPath(".")
, fuzzyMatcher(false, 100)
{
loadResources();
makeUI();
setAssetSrcMode(true);
}
void AssetsBrowser::openAsset(AssetType type, const String& assetId)
{
getWidgetAs<UITextInput>("assetSearch")->setText("");
auto target = project.getImportAssetsDatabase().getPrimaryInputFile(type, assetId);
openFile(std::move(target));
}
void AssetsBrowser::openFile(const Path& path)
{
if (!path.isEmpty()) {
curSrcPath = path.parentPath();
refreshList();
assetList->setSelectedOptionId(path.toString());
loadAsset(path.toString(), true);
}
}
void AssetsBrowser::replaceAssetTab(AssetType oldType, const String& oldId, AssetType newType, const String& newId)
{
const auto oldTarget = project.getImportAssetsDatabase().getPrimaryInputFile(oldType, oldId);
const auto newTarget = project.getImportAssetsDatabase().getPrimaryInputFile(newType, newId);
assetTabs->replaceAssetTab(oldTarget.toString(), newTarget.toString());
}
bool AssetsBrowser::requestQuit(std::function<void()> callback)
{
return assetTabs->requestQuit(std::move(callback));
}
void AssetsBrowser::saveTab()
{
assetTabs->saveCurrentTab();
}
void AssetsBrowser::saveAllTabs()
{
assetTabs->saveAllTabs();
}
void AssetsBrowser::closeTab()
{
assetTabs->closeCurrentTab();
}
void AssetsBrowser::moveTabFocus(int delta)
{
assetTabs->moveTabFocus(delta);
}
std::shared_ptr<AssetEditorWindow> AssetsBrowser::getActiveWindow() const
{
return assetTabs->getActiveWindow();
}
void AssetsBrowser::loadResources()
{
project.addAssetReloadCallback([=] (gsl::span<const String> assets)
{
refreshAssets(assets);
});
}
void AssetsBrowser::makeUI()
{
UIWidget::add(factory.makeUI("halley/assets_browser"), 1);
assetList = getWidgetAs<UIList>("assetList");
assetList->setSingleClickAccept(false);
assetTabs = std::make_shared<AssetBrowserTabs>(factory, project, projectWindow);
getWidget("assetEditorContainer")->add(assetTabs, 1);
setHandle(UIEventType::ListSelectionChanged, "assetType", [=] (const UIEvent& event)
{
listAssets(fromString<AssetType>(event.getStringData()));
});
setHandle(UIEventType::ListSelectionChanged, "assetList", [=] (const UIEvent& event)
{
loadAsset(event.getStringData(), false);
});
setHandle(UIEventType::ListAccept, "assetList", [=] (const UIEvent& event)
{
loadAsset(event.getStringData(), true);
});
setHandle(UIEventType::TextChanged, "assetSearch", [=] (const UIEvent& event)
{
setFilter(event.getStringData());
});
setHandle(UIEventType::ButtonClicked, "addAsset", [=] (const UIEvent& event)
{
addAsset();
});
setHandle(UIEventType::ButtonClicked, "removeAsset", [=] (const UIEvent& event)
{
removeAsset();
});
setHandle(UIEventType::ButtonClicked, "collapseButton", [=] (const UIEvent& event)
{
setCollapsed(!collapsed);
});
updateAddRemoveButtons();
doSetCollapsed(projectWindow.getSetting(EditorSettingType::Editor, "assetBrowserCollapse").asBool(false));
}
void AssetsBrowser::setAssetSrcMode(bool enabled)
{
assetSrcMode = enabled;
assetTabs->setAssetSrcMode(enabled);
getWidget("assetType")->setActive(!assetSrcMode);
if (assetSrcMode) {
listAssetSources();
} else {
listAssets(AssetType::Sprite);
}
}
void AssetsBrowser::listAssetSources()
{
if (!assetNames) {
assetNames = project.getAssetSrcList();
std::sort(assetNames->begin(), assetNames->end()); // Is this even needed?
fuzzyMatcher.clear();
fuzzyMatcher.addStrings(assetNames.value());
}
if (filter.isEmpty()) {
setListContents(assetNames.value(), curSrcPath, false);
} else {
Vector<String> filteredList;
auto result = fuzzyMatcher.match(filter);
filteredList.reserve(result.size());
for (const auto& r: result) {
filteredList.push_back(r.getString());
}
setListContents(filteredList, curSrcPath, true);
}
}
void AssetsBrowser::listAssets(AssetType type)
{
curType = type;
if (curPaths.find(type) == curPaths.end()) {
curPaths[type] = Path(".");
}
const auto curPath = curPaths[type];
auto assets = project.getGameResources().ofType(type).enumerate();
std::sort(assets.begin(), assets.end());
setListContents(assets, curPath, false);
}
void AssetsBrowser::setListContents(Vector<String> assets, const Path& curPath, bool flat)
{
{
Hash::Hasher hasher;
for (const auto& asset: assets) {
hasher.feed(asset);
}
hasher.feed(curPath.toString());
const auto hash = hasher.digest();
if (curHash == hash) {
return;
}
curHash = hash;
}
std::optional<String> selectOption;
{
Hash::Hasher hasher;
hasher.feed(curPath.toString());
const auto hash = hasher.digest();
if (curDirHash == hash) {
selectOption = assetList->getSelectedOptionId();
}
curDirHash = hash;
}
assetList->setScrollToSelection(false);
clearAssetList();
if (flat) {
for (auto& a: assets) {
addFileToList(a);
}
} else {
std::set<String> dirs;
Vector<String> files;
for (auto& a: assets) {
auto relPath = Path("./" + a).makeRelativeTo(curPath);
if (relPath.getNumberPaths() == 1) {
files.emplace_back(a);
} else {
auto start = relPath.getFront(1);
dirs.insert(start.toString());
}
}
for (const auto& dir: dirs) {
addDirToList(curPath, dir);
}
for (const auto& file: files) {
addFileToList(file);
}
}
if (selectOption) {
assetList->setSelectedOptionId(selectOption.value());
}
assetList->setScrollToSelection(true);
if (pendingOpen) {
assetList->setSelectedOptionId(pendingOpen->toString());
loadAsset(pendingOpen->toString(), true);
pendingOpen.reset();
}
}
void AssetsBrowser::clearAssetList()
{
assetList->clear();
}
void AssetsBrowser::addDirToList(const Path& curPath, const String& dir)
{
const auto icon = std::make_shared<UIImage>(factory.makeDirectoryIcon(dir == ".."));
/*
std::optional<ImportAssetType> assetTypeDir;
if (curPath == ".") {
if (dir == "shader") {
assetTypeDir = ImportAssetType::Shader;
}
}
if (assetTypeDir) {
icon->add(std::make_shared<UIImage>(factory.makeImportAssetTypeIcon(assetTypeDir.value())), 1, {}, UISizerAlignFlags::Centre);
}
*/
auto sizer = std::make_shared<UISizer>();
sizer->add(icon, 0, Vector4f(0, 0, 4, 0));
sizer->add(assetList->makeLabel("", LocalisedString::fromUserString(dir)));
assetList->addItem(dir + "/.", std::move(sizer));
}
void AssetsBrowser::addFileToList(const Path& path)
{
auto type = project.getAssetImporter()->getImportAssetType(path, false);
auto sizer = std::make_shared<UISizer>();
sizer->add(std::make_shared<UIImage>(factory.makeImportAssetTypeIcon(type)), 0, Vector4f(0, 0, 4, 0));
sizer->add(assetList->makeLabel("", LocalisedString::fromUserString(path.getFilename().toString())));
assetList->addItem(path.toString(), std::move(sizer));
//assetList->addTextItem(path.toString(), LocalisedString::fromUserString(path.getFilename().toString()));
}
void AssetsBrowser::refreshList()
{
if (assetSrcMode) {
listAssetSources();
} else {
listAssets(curType);
}
}
void AssetsBrowser::setFilter(const String& f)
{
if (filter != f) {
filter = f.asciiLower();
refreshList();
}
}
void AssetsBrowser::loadAsset(const String& name, bool doubleClick)
{
lastClickedAsset = name;
updateAddRemoveButtons();
auto& curPath = assetSrcMode ? curSrcPath : curPaths[curType];
if (name.endsWith("/.")) {
if (doubleClick) {
curPath = curPath / name;
refreshList();
}
} else {
if (doubleClick) {
assetTabs->load(assetSrcMode ? std::optional<AssetType>() : curType, name);
}
}
}
void AssetsBrowser::refreshAssets(gsl::span<const String> assets)
{
assetNames.reset();
refreshList();
assetTabs->refreshAssets();
}
void AssetsBrowser::updateAddRemoveButtons()
{
// TODO: refactor updateAddRemoveButtons/addAsset/removeAsset?
const auto stem = curSrcPath.getFront(1).string();
const bool canAdd = stem == "prefab" || stem == "scene" || stem == "audio_object" || stem == "audio_event" || stem == "ui" || stem == "comet";
const bool canRemove = !lastClickedAsset.isEmpty() && !lastClickedAsset.endsWith("/.");
getWidget("addAsset")->setEnabled(canAdd);
getWidget("removeAsset")->setEnabled(canRemove);
}
void AssetsBrowser::addAsset()
{
// TODO: refactor updateAddRemoveButtons/addAsset/removeAsset?
const auto assetType = curSrcPath.getFront(1).string();
getRoot()->addChild(std::make_shared<NewAssetWindow>(factory, [=] (std::optional<String> newName)
{
if (newName) {
if (assetType == "prefab") {
Prefab prefab;
prefab.makeDefault();
addAsset(newName.value() + ".prefab", prefab.toYAML());
} else if (assetType == "scene") {
Scene scene;
scene.makeDefault();
addAsset(newName.value() + ".scene", scene.toYAML());
} else if (assetType == "audio_object") {
AudioObject object;
object.makeDefault();
addAsset(newName.value() + ".yaml", object.toYAML());
} else if (assetType == "audio_event") {
AudioEvent audioEvent;
audioEvent.makeDefault();
addAsset(newName.value() + ".yaml", audioEvent.toYAML());
} else if (assetType == "ui") {
UIDefinition ui;
ui.makeDefault();
addAsset(newName.value() + ".yaml", ui.toYAML());
} else if (assetType == "comet") {
ScriptGraph graph;
graph.makeDefault();
addAsset(newName.value() + ".comet", graph.toYAML());
}
}
}));
}
void AssetsBrowser::addAsset(Path path, std::string_view data)
{
const auto fullPath = curSrcPath / path;
pendingOpen = fullPath;
project.writeAssetToDisk(fullPath, data);
}
void AssetsBrowser::removeAsset()
{
// TODO: refactor updateAddRemoveButtons/addAsset/removeAsset?
assetList->setItemActive(lastClickedAsset, false);
FileSystem::remove(project.getAssetsSrcPath() / lastClickedAsset);
}
void AssetsBrowser::setCollapsed(bool collapsed)
{
doSetCollapsed(collapsed);
projectWindow.setSetting(EditorSettingType::Editor, "assetBrowserCollapse", ConfigNode(collapsed));
}
void AssetsBrowser::doSetCollapsed(bool c)
{
if (collapsed != c) {
collapsed = c;
auto button = getWidgetAs<UIButton>("collapseButton");
button->setLabel(LocalisedString::fromHardcodedString(collapsed ? ">>" : "<< Collapse"));
auto* parent = dynamic_cast<UIWidget*>(button->getParent());
if (parent) {
parent->getSizer()[0].setBorder(collapsed ? Vector4f(-10, 0, -15, 0) : Vector4f(0, 0, 0, 5));
}
//getWidget("collapseBorder")->setActive(!collapsed);
getWidget("assetBrowsePanel")->setActive(!collapsed);
}
}
<|endoftext|> |
<commit_before>#define WIN32_LEAN_AND_MEAN
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <utility>
#include <uv.h>
#include <vector>
#include <windows.h>
#include "../../helper/windows/helper.h"
#include "../../lock.h"
#include "../../log.h"
#include "../../message.h"
#include "../../message_buffer.h"
#include "../recent_file_cache.h"
#include "../worker_platform.h"
#include "../worker_thread.h"
#include "subscription.h"
using std::default_delete;
using std::endl;
using std::make_pair;
using std::map;
using std::move;
using std::ostream;
using std::ostringstream;
using std::pair;
using std::shared_ptr;
using std::string;
using std::unique_ptr;
using std::vector;
using std::wostringstream;
using std::wstring;
const size_t DEFAULT_CACHE_SIZE = 4096;
const size_t DEFAULT_CACHE_PREPOPULATION = 1024;
void CALLBACK command_perform_helper(__in ULONG_PTR payload);
void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped);
class WindowsWorkerPlatform : public WorkerPlatform
{
public:
WindowsWorkerPlatform(WorkerThread *thread) : WorkerPlatform(thread), thread_handle{0}, cache{DEFAULT_CACHE_SIZE}
{
int err;
err = uv_mutex_init(&thread_handle_mutex);
if (err) {
report_uv_error(err);
}
freeze();
};
~WindowsWorkerPlatform() override { uv_mutex_destroy(&thread_handle_mutex); }
Result<> wake() override
{
Lock lock(thread_handle_mutex);
if (!thread_handle) {
return ok_result();
}
BOOL success = QueueUserAPC(command_perform_helper, thread_handle, reinterpret_cast<ULONG_PTR>(this));
if (!success) {
return windows_error_result<>("Unable to queue APC");
}
return ok_result();
}
Result<> listen() override
{
{
Lock lock(thread_handle_mutex);
HANDLE pseudo_handle = GetCurrentThread();
BOOL success = DuplicateHandle(GetCurrentProcess(), // Source process
pseudo_handle, // Source handle
GetCurrentProcess(), // Destination process
&thread_handle, // Destination handle
0, // Desired access
FALSE, // Inheritable by new processes
DUPLICATE_SAME_ACCESS // options
);
if (!success) {
return windows_error_result<>("Unable to duplicate thread handle");
}
}
while (true) {
SleepEx(INFINITE, true);
}
return error_result("listen loop ended unexpectedly");
}
Result<bool> handle_add_command(CommandID command,
ChannelID channel,
const string &root_path,
bool recursive) override
{
// Convert the path to a wide-character string
Result<wstring> convr = to_wchar(root_path);
if (convr.is_error()) return convr.propagate<bool>();
wstring &root_path_w = convr.get_value();
// Open a directory handle
HANDLE root = CreateFileW(root_path_w.c_str(), // null-terminated wchar file name
FILE_LIST_DIRECTORY, // desired access
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, // share mode
NULL, // security attributes
OPEN_EXISTING, // creation disposition
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, // flags and attributes
NULL // template file
);
if (root == INVALID_HANDLE_VALUE) {
return windows_error_result<bool>("Unable to open directory handle");
}
// Allocate and persist the subscription
Subscription *sub = new Subscription(channel, root, root_path_w, recursive, this);
auto insert_result = subscriptions.insert(make_pair(channel, sub));
if (!insert_result.second) {
delete sub;
ostringstream msg("Channel collision: ");
msg << channel;
return Result<bool>::make_error(msg.str());
}
ostream &logline = LOGGER << "Added directory root " << root_path;
if (!recursive) logline << " (non-recursive)";
logline << " at channel " << channel << "." << endl;
Result<bool> schedr = sub->schedule(&event_helper);
if (schedr.is_error()) return schedr.propagate<bool>();
if (!schedr.get_value()) {
LOGGER << "Falling back to polling for watch root " << root_path << "." << endl;
return emit(Message(CommandPayloadBuilder::add(channel, string(root_path), recursive, 1).build()))
.propagate(false);
}
cache.prepopulate(root_path, DEFAULT_CACHE_PREPOPULATION);
return ok_result(true);
}
Result<bool> handle_remove_command(CommandID command, ChannelID channel) override
{
auto it = subscriptions.find(channel);
if (it == subscriptions.end()) {
LOGGER << "Channel " << channel << " was already removed." << endl;
return ok_result(true);
}
Result<> r = it->second->stop(command);
if (r.is_error()) return r.propagate<bool>();
LOGGER << "Subscription for channel " << channel << " stopped." << endl;
return ok_result(false);
}
Result<> handle_fs_event(DWORD error_code, DWORD num_bytes, Subscription *sub)
{
// Ensure that the subscription is valid.
ChannelID channel = sub->get_channel();
auto it = subscriptions.find(channel);
if (it == subscriptions.end() || it->second != sub) {
return ok_result();
}
// Subscription termination.
bool terminate = false;
if (error_code == ERROR_OPERATION_ABORTED) {
LOGGER << "Completing termination of channel " << channel << "." << endl;
terminate = true;
} else if (sub->is_terminating()) {
LOGGER << "Filesystem event encountered on terminating channel " << channel << "." << endl;
terminate = true;
}
if (terminate) return remove(sub);
// Handle errors.
if (error_code == ERROR_INVALID_PARAMETER) {
LOGGER << "Attempting to revert to a network-friendly buffer size." << endl;
Result<> resize = sub->use_network_size();
if (resize.is_error()) return emit_fatal_error(sub, move(resize));
return reschedule(sub);
}
if (error_code == ERROR_NOTIFY_ENUM_DIR) {
LOGGER << "Change buffer overflow. Some events may have been lost." << endl;
return reschedule(sub);
}
if (error_code != ERROR_SUCCESS) {
return emit_fatal_error(sub, windows_error_result<>("Completion callback error", error_code));
}
// Schedule the next completion callback.
BYTE *base = sub->get_written(num_bytes);
Result<> next = reschedule(sub);
// Process received events.
MessageBuffer buffer;
ChannelMessageBuffer messages(buffer, channel);
size_t num_events = 0;
bool old_path_seen = false;
string old_path;
while (true) {
PFILE_NOTIFY_INFORMATION info = reinterpret_cast<PFILE_NOTIFY_INFORMATION>(base);
num_events++;
Result<> pr = process_event_payload(info, sub, messages, old_path_seen, old_path);
if (pr.is_error()) {
LOGGER << "Skipping entry " << pr << "." << endl;
}
if (info->NextEntryOffset == 0) {
break;
}
base += info->NextEntryOffset;
}
cache.apply();
cache.prune();
if (!messages.empty()) {
Result<> er = emit_all(messages.begin(), messages.end());
if (er.is_error()) {
LOGGER << "Unable to emit messages: " << er << "." << endl;
} else {
LOGGER << "Filesystem event batch of size " << num_events << " completed. "
<< plural(messages.size(), "message") << " produced." << endl;
}
}
return next.propagate_as_void();
}
private:
Result<> reschedule(Subscription *sub)
{
Result<bool> sch = sub->schedule(&event_helper);
if (sch.is_error()) return emit_fatal_error(sub, sch.propagate_as_void());
if (!sch.get_value()) {
Result<string> root = sub->get_root_path();
if (root.is_error()) return emit_fatal_error(sub, root.propagate_as_void());
LOGGER << "Falling back to polling for path " << root.get_value() << " at channel " << sub->get_channel() << "."
<< endl;
Result<> rem = remove(sub);
rem &= emit(Message(
CommandPayloadBuilder::add(sub->get_channel(), move(root.get_value()), sub->is_recursive(), 1).build()));
return rem;
}
return ok_result();
}
Result<> remove(Subscription *sub)
{
Message response(AckPayload(sub->get_command_id(), sub->get_channel(), true, ""));
// Ensure that the subscription is valid.
ChannelID channel = sub->get_channel();
auto it = subscriptions.find(channel);
if (it == subscriptions.end() || it->second != sub) {
return ok_result();
}
subscriptions.erase(it);
delete sub;
if (sub->get_command_id() != NULL_COMMAND_ID) {
return emit(move(response));
} else {
return ok_result();
}
}
Result<> emit_fatal_error(Subscription *sub, Result<> &&r)
{
assert(r.is_error());
Result<> out = emit(Message(ErrorPayload(sub->get_channel(), string(r.get_error()), true)));
out &= remove(sub);
return out;
}
Result<> process_event_payload(PFILE_NOTIFY_INFORMATION info,
Subscription *sub,
ChannelMessageBuffer &messages,
bool &old_path_seen,
string &old_path)
{
ChannelID channel = sub->get_channel();
wstring relpathw{info->FileName, info->FileNameLength / sizeof(WCHAR)};
wstring pathw = sub->make_absolute(move(relpathw));
Result<string> u8r = to_utf8(pathw);
if (u8r.is_error()) {
LOGGER << "Unable to convert path to utf-8: " << u8r << "." << endl;
return ok_result();
}
string &path = u8r.get_value();
shared_ptr<StatResult> stat;
if (info->Action == FILE_ACTION_REMOVED || info->Action == FILE_ACTION_RENAMED_OLD_NAME) {
stat = cache.former_at_path(path, false, false);
} else {
stat = cache.current_at_path(path, false, false);
if (stat->is_absent()) {
stat = cache.former_at_path(path, false, false);
}
}
EntryKind kind = stat->get_entry_kind();
switch (info->Action) {
case FILE_ACTION_ADDED: messages.created(move(path), kind); break;
case FILE_ACTION_MODIFIED: messages.modified(move(path), kind); break;
case FILE_ACTION_REMOVED: messages.deleted(move(path), kind); break;
case FILE_ACTION_RENAMED_OLD_NAME:
old_path_seen = true;
old_path = move(path);
break;
case FILE_ACTION_RENAMED_NEW_NAME:
if (old_path_seen) {
// Old name received first
messages.renamed(move(old_path), move(path), kind);
old_path_seen = false;
} else {
// No old name. Treat it as a creation
messages.created(move(path), kind);
}
break;
default:
ostringstream out;
out << "Unexpected action " << info->Action << " reported by ReadDirectoryChangesW for " << path;
return error_result(out.str());
break;
}
return ok_result();
}
uv_mutex_t thread_handle_mutex;
HANDLE thread_handle;
map<ChannelID, Subscription *> subscriptions;
RecentFileCache cache;
};
unique_ptr<WorkerPlatform> WorkerPlatform::for_worker(WorkerThread *thread)
{
return unique_ptr<WorkerPlatform>(new WindowsWorkerPlatform(thread));
}
void CALLBACK command_perform_helper(__in ULONG_PTR payload)
{
WindowsWorkerPlatform *platform = reinterpret_cast<WindowsWorkerPlatform *>(payload);
platform->handle_commands();
}
static void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped)
{
Subscription *sub = static_cast<Subscription *>(overlapped->hEvent);
Result<> r = sub->get_platform()->handle_fs_event(error_code, num_bytes, sub);
if (r.is_error()) {
LOGGER << "Unable to handle filesystem events: " << r << "." << endl;
}
}
<commit_msg>Improve Windows event logging to see actual batch contents<commit_after>#define WIN32_LEAN_AND_MEAN
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <utility>
#include <uv.h>
#include <vector>
#include <windows.h>
#include "../../helper/windows/helper.h"
#include "../../lock.h"
#include "../../log.h"
#include "../../message.h"
#include "../../message_buffer.h"
#include "../recent_file_cache.h"
#include "../worker_platform.h"
#include "../worker_thread.h"
#include "subscription.h"
using std::default_delete;
using std::endl;
using std::make_pair;
using std::map;
using std::move;
using std::ostream;
using std::ostringstream;
using std::pair;
using std::shared_ptr;
using std::string;
using std::unique_ptr;
using std::vector;
using std::wostringstream;
using std::wstring;
const size_t DEFAULT_CACHE_SIZE = 4096;
const size_t DEFAULT_CACHE_PREPOPULATION = 1024;
void CALLBACK command_perform_helper(__in ULONG_PTR payload);
void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped);
class WindowsWorkerPlatform : public WorkerPlatform
{
public:
WindowsWorkerPlatform(WorkerThread *thread) : WorkerPlatform(thread), thread_handle{0}, cache{DEFAULT_CACHE_SIZE}
{
int err;
err = uv_mutex_init(&thread_handle_mutex);
if (err) {
report_uv_error(err);
}
freeze();
};
~WindowsWorkerPlatform() override { uv_mutex_destroy(&thread_handle_mutex); }
Result<> wake() override
{
Lock lock(thread_handle_mutex);
if (!thread_handle) {
return ok_result();
}
BOOL success = QueueUserAPC(command_perform_helper, thread_handle, reinterpret_cast<ULONG_PTR>(this));
if (!success) {
return windows_error_result<>("Unable to queue APC");
}
return ok_result();
}
Result<> listen() override
{
{
Lock lock(thread_handle_mutex);
HANDLE pseudo_handle = GetCurrentThread();
BOOL success = DuplicateHandle(GetCurrentProcess(), // Source process
pseudo_handle, // Source handle
GetCurrentProcess(), // Destination process
&thread_handle, // Destination handle
0, // Desired access
FALSE, // Inheritable by new processes
DUPLICATE_SAME_ACCESS // options
);
if (!success) {
return windows_error_result<>("Unable to duplicate thread handle");
}
}
while (true) {
SleepEx(INFINITE, true);
}
return error_result("listen loop ended unexpectedly");
}
Result<bool> handle_add_command(CommandID command,
ChannelID channel,
const string &root_path,
bool recursive) override
{
// Convert the path to a wide-character string
Result<wstring> convr = to_wchar(root_path);
if (convr.is_error()) return convr.propagate<bool>();
wstring &root_path_w = convr.get_value();
// Open a directory handle
HANDLE root = CreateFileW(root_path_w.c_str(), // null-terminated wchar file name
FILE_LIST_DIRECTORY, // desired access
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, // share mode
NULL, // security attributes
OPEN_EXISTING, // creation disposition
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, // flags and attributes
NULL // template file
);
if (root == INVALID_HANDLE_VALUE) {
return windows_error_result<bool>("Unable to open directory handle");
}
// Allocate and persist the subscription
Subscription *sub = new Subscription(channel, root, root_path_w, recursive, this);
auto insert_result = subscriptions.insert(make_pair(channel, sub));
if (!insert_result.second) {
delete sub;
ostringstream msg("Channel collision: ");
msg << channel;
return Result<bool>::make_error(msg.str());
}
ostream &logline = LOGGER << "Added directory root " << root_path;
if (!recursive) logline << " (non-recursive)";
logline << " at channel " << channel << "." << endl;
Result<bool> schedr = sub->schedule(&event_helper);
if (schedr.is_error()) return schedr.propagate<bool>();
if (!schedr.get_value()) {
LOGGER << "Falling back to polling for watch root " << root_path << "." << endl;
return emit(Message(CommandPayloadBuilder::add(channel, string(root_path), recursive, 1).build()))
.propagate(false);
}
cache.prepopulate(root_path, DEFAULT_CACHE_PREPOPULATION);
return ok_result(true);
}
Result<bool> handle_remove_command(CommandID command, ChannelID channel) override
{
auto it = subscriptions.find(channel);
if (it == subscriptions.end()) {
LOGGER << "Channel " << channel << " was already removed." << endl;
return ok_result(true);
}
Result<> r = it->second->stop(command);
if (r.is_error()) return r.propagate<bool>();
LOGGER << "Subscription for channel " << channel << " stopped." << endl;
return ok_result(false);
}
Result<> handle_fs_event(DWORD error_code, DWORD num_bytes, Subscription *sub)
{
// Ensure that the subscription is valid.
ChannelID channel = sub->get_channel();
auto it = subscriptions.find(channel);
if (it == subscriptions.end() || it->second != sub) {
return ok_result();
}
// Subscription termination.
bool terminate = false;
if (error_code == ERROR_OPERATION_ABORTED) {
LOGGER << "Completing termination of channel " << channel << "." << endl;
terminate = true;
} else if (sub->is_terminating()) {
LOGGER << "Filesystem event encountered on terminating channel " << channel << "." << endl;
terminate = true;
}
if (terminate) return remove(sub);
// Handle errors.
if (error_code == ERROR_INVALID_PARAMETER) {
LOGGER << "Attempting to revert to a network-friendly buffer size." << endl;
Result<> resize = sub->use_network_size();
if (resize.is_error()) return emit_fatal_error(sub, move(resize));
return reschedule(sub);
}
if (error_code == ERROR_NOTIFY_ENUM_DIR) {
LOGGER << "Change buffer overflow. Some events may have been lost." << endl;
return reschedule(sub);
}
if (error_code != ERROR_SUCCESS) {
return emit_fatal_error(sub, windows_error_result<>("Completion callback error", error_code));
}
// Schedule the next completion callback.
BYTE *base = sub->get_written(num_bytes);
Result<> next = reschedule(sub);
// Process received events.
MessageBuffer buffer;
ChannelMessageBuffer messages(buffer, channel);
size_t num_events = 0;
bool old_path_seen = false;
string old_path;
while (true) {
PFILE_NOTIFY_INFORMATION info = reinterpret_cast<PFILE_NOTIFY_INFORMATION>(base);
num_events++;
Result<> pr = process_event_payload(info, sub, messages, old_path_seen, old_path);
if (pr.is_error()) {
LOGGER << "Skipping entry " << pr << "." << endl;
}
if (info->NextEntryOffset == 0) {
break;
}
base += info->NextEntryOffset;
}
cache.apply();
cache.prune();
if (!messages.empty()) {
Result<> er = emit_all(messages.begin(), messages.end());
if (er.is_error()) {
LOGGER << "Unable to emit messages: " << er << "." << endl;
} else {
LOGGER << "Filesystem event batch of size " << num_events << " completed. "
<< plural(messages.size(), "message") << " produced." << endl;
}
}
return next.propagate_as_void();
}
private:
Result<> reschedule(Subscription *sub)
{
Result<bool> sch = sub->schedule(&event_helper);
if (sch.is_error()) return emit_fatal_error(sub, sch.propagate_as_void());
if (!sch.get_value()) {
Result<string> root = sub->get_root_path();
if (root.is_error()) return emit_fatal_error(sub, root.propagate_as_void());
LOGGER << "Falling back to polling for path " << root.get_value() << " at channel " << sub->get_channel() << "."
<< endl;
Result<> rem = remove(sub);
rem &= emit(Message(
CommandPayloadBuilder::add(sub->get_channel(), move(root.get_value()), sub->is_recursive(), 1).build()));
return rem;
}
return ok_result();
}
Result<> remove(Subscription *sub)
{
Message response(AckPayload(sub->get_command_id(), sub->get_channel(), true, ""));
// Ensure that the subscription is valid.
ChannelID channel = sub->get_channel();
auto it = subscriptions.find(channel);
if (it == subscriptions.end() || it->second != sub) {
return ok_result();
}
subscriptions.erase(it);
delete sub;
if (sub->get_command_id() != NULL_COMMAND_ID) {
return emit(move(response));
} else {
return ok_result();
}
}
Result<> emit_fatal_error(Subscription *sub, Result<> &&r)
{
assert(r.is_error());
Result<> out = emit(Message(ErrorPayload(sub->get_channel(), string(r.get_error()), true)));
out &= remove(sub);
return out;
}
Result<> process_event_payload(PFILE_NOTIFY_INFORMATION info,
Subscription *sub,
ChannelMessageBuffer &messages,
bool &old_path_seen,
string &old_path)
{
ChannelID channel = sub->get_channel();
wstring relpathw{info->FileName, info->FileNameLength / sizeof(WCHAR)};
wstring pathw = sub->make_absolute(move(relpathw));
Result<string> u8r = to_utf8(pathw);
if (u8r.is_error()) {
LOGGER << "Unable to convert path to utf-8: " << u8r << "." << endl;
return ok_result();
}
string &path = u8r.get_value();
shared_ptr<StatResult> stat;
if (info->Action == FILE_ACTION_REMOVED || info->Action == FILE_ACTION_RENAMED_OLD_NAME) {
stat = cache.former_at_path(path, false, false);
} else {
stat = cache.current_at_path(path, false, false);
if (stat->is_absent()) {
stat = cache.former_at_path(path, false, false);
}
}
EntryKind kind = stat->get_entry_kind();
ostream &logline = LOGGER;
logline << "Event at [" << path << "] ";
switch (info->Action) {
case FILE_ACTION_ADDED:
logline << "FILE_ACTION_ADDED " << kind << "." << endl;
messages.created(move(path), kind);
break;
case FILE_ACTION_MODIFIED:
logline << "FILE_ACTION_MODIFIED " << kind << "." << endl;
messages.modified(move(path), kind);
break;
case FILE_ACTION_REMOVED:
logline << "FILE_ACTION_REMOVED " << kind << "." << endl;
messages.deleted(move(path), kind);
break;
case FILE_ACTION_RENAMED_OLD_NAME:
logline << "FILE_ACTION_RENAMED_OLD_NAME " << kind << "." << endl;
old_path_seen = true;
old_path = move(path);
break;
case FILE_ACTION_RENAMED_NEW_NAME:
logline << "FILE_ACTION_RENAMED_NEW_NAME ";
if (old_path_seen) {
// Old name received first
logline << kind << "." << endl;
messages.renamed(move(old_path), move(path), kind);
old_path_seen = false;
} else {
// No old name. Treat it as a creation
logline << "(unpaired) " << kind << "." << endl;
messages.created(move(path), kind);
}
break;
default:
logline << " with unexpected action " << info->Action << "." << endl;
ostringstream out;
out << "Unexpected action " << info->Action << " reported by ReadDirectoryChangesW for " << path;
return error_result(out.str());
break;
}
return ok_result();
}
uv_mutex_t thread_handle_mutex;
HANDLE thread_handle;
map<ChannelID, Subscription *> subscriptions;
RecentFileCache cache;
};
unique_ptr<WorkerPlatform> WorkerPlatform::for_worker(WorkerThread *thread)
{
return unique_ptr<WorkerPlatform>(new WindowsWorkerPlatform(thread));
}
void CALLBACK command_perform_helper(__in ULONG_PTR payload)
{
WindowsWorkerPlatform *platform = reinterpret_cast<WindowsWorkerPlatform *>(payload);
platform->handle_commands();
}
static void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped)
{
Subscription *sub = static_cast<Subscription *>(overlapped->hEvent);
Result<> r = sub->get_platform()->handle_fs_event(error_code, num_bytes, sub);
if (r.is_error()) {
LOGGER << "Unable to handle filesystem events: " << r << "." << endl;
}
}
<|endoftext|> |
<commit_before>/*
* #### ####
* #### ####
* #### #### ##
* #### #### ####
* #### ############ ############ #### ########## #### ####
* #### #### #### #### #### #### #### ########
* #### #### #### #### #### #### #### ########
* #### #### #### #### #### #### #### #### ####
* #### #### #### #### #### #### #### #### ####
* #### ############ ############ #### ########## #### ####
* #### ####
* ################################ ####
* __ __ __ __ __ ####
* | | | | [__) |_/ (__ |__| | | [__) ####
* |/\| |__| | \ | \ .__) | | |__| | ##
*
*
* DU-INO Arduino Library - Clock Module
* Aaron Mavrinac <aaron@logick.ca>
*/
#include <TimerOne.h>
#include "du-ino_clock.h"
void clock_isr();
DUINO_Clock::DUINO_Clock()
: clock_callback_(NULL)
, external_callback_(NULL)
, state_(false)
, retrigger_flag_(false)
, external_(false)
, period_(0)
{
}
void DUINO_Clock::begin()
{
Timer1.initialize();
}
void DUINO_Clock::set_period(unsigned long period)
{
external_ = false;
period_ = period;
update();
}
void DUINO_Clock::set_bpm(uint16_t bpm)
{
// clock period is microseconds per 16th note
// bpm is quarter notes per minute (or 16th notes per 15,000,000 us)
// halved, for on-off cycle
set_period(7500000 / (unsigned long)bpm);
}
void DUINO_Clock::set_external()
{
period_ = 0;
external_ = true;
update();
}
void DUINO_Clock::on_jack(bool jack_state)
{
if(!external_)
{
set_external();
}
on_clock(jack_state);
}
void DUINO_Clock::on_clock(bool jack_state)
{
state_ = external_ ? jack_state : !state_;
if(clock_callback_)
{
clock_callback_();
}
if(state_)
{
retrigger_flag_ = true;
}
}
bool DUINO_Clock::retrigger()
{
bool flag = retrigger_flag_;
retrigger_flag_ = false;
return flag;
}
void DUINO_Clock::update()
{
Timer1.detachInterrupt();
state_ = retrigger_flag_ = false;
if(!external_)
{
Timer1.attachInterrupt(clock_isr, period_);
}
}
DUINO_Clock Clock;
void clock_isr()
{
Clock.on_clock();
}
<commit_msg>Style fixes.<commit_after>/*
* #### ####
* #### ####
* #### #### ##
* #### #### ####
* #### ############ ############ #### ########## #### ####
* #### #### #### #### #### #### #### ########
* #### #### #### #### #### #### #### ########
* #### #### #### #### #### #### #### #### ####
* #### #### #### #### #### #### #### #### ####
* #### ############ ############ #### ########## #### ####
* #### ####
* ################################ ####
* __ __ __ __ __ ####
* | | | | [__) |_/ (__ |__| | | [__) ####
* |/\| |__| | \ | \ .__) | | |__| | ##
*
*
* DU-INO Arduino Library - Clock Module
* Aaron Mavrinac <aaron@logick.ca>
*/
#include <TimerOne.h>
#include "du-ino_clock.h"
void clock_isr();
DUINO_Clock::DUINO_Clock()
: clock_callback_(NULL)
, external_callback_(NULL)
, state_(false)
, retrigger_flag_(false)
, external_(false)
, period_(0)
{
}
void DUINO_Clock::begin()
{
Timer1.initialize();
}
void DUINO_Clock::set_period(unsigned long period)
{
external_ = false;
period_ = period;
update();
}
void DUINO_Clock::set_bpm(uint16_t bpm)
{
// clock period is microseconds per 16th note
// bpm is quarter notes per minute (or 16th notes per 15,000,000 us)
// halved, for on-off cycle
set_period(7500000 / (unsigned long)bpm);
}
void DUINO_Clock::set_external()
{
period_ = 0;
external_ = true;
update();
}
void DUINO_Clock::on_jack(bool jack_state)
{
if (!external_)
{
set_external();
}
on_clock(jack_state);
}
void DUINO_Clock::on_clock(bool jack_state)
{
state_ = external_ ? jack_state : !state_;
if (clock_callback_)
{
clock_callback_();
}
if (state_)
{
retrigger_flag_ = true;
}
}
bool DUINO_Clock::retrigger()
{
bool flag = retrigger_flag_;
retrigger_flag_ = false;
return flag;
}
void DUINO_Clock::update()
{
Timer1.detachInterrupt();
state_ = retrigger_flag_ = false;
if (!external_)
{
Timer1.attachInterrupt(clock_isr, period_);
}
}
DUINO_Clock Clock;
void clock_isr()
{
Clock.on_clock();
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <boost/utility/string_ref.hpp>
#include <llvm/IR/Module.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/FileSystem.h>
#include "../ast/ast_printer.h"
#include "../ast/decl.h"
#include "../parser/parser.hpp"
#include "../sema/typecheck.h"
#include "../cgen/codegen.h"
#include "../irgen/irgen.h"
using namespace delta;
namespace delta {
extern FILE* inputFile;
const char* currentFileName;
extern std::vector<Decl> globalAST;
}
int yyparse();
namespace {
/// If `args` contains `flag`, removes it and returns true, otherwise returns false.
bool checkFlag(boost::string_ref flag, std::vector<boost::string_ref>& args) {
const auto it = std::find(args.begin(), args.end(), flag);
const bool contains = it != args.end();
if (contains) args.erase(it);
return contains;
}
bool emitMachineCode(llvm::Module& module, llvm::StringRef fileName,
llvm::TargetMachine::CodeGenFileType fileType) {
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::InitializeNativeTargetAsmParser();
std::string targetTriple = llvm::sys::getDefaultTargetTriple();
module.setTargetTriple(targetTriple);
std::string errorMessage;
auto* target = llvm::TargetRegistry::lookupTarget(targetTriple, errorMessage);
if (!target) {
llvm::errs() << errorMessage;
return false;
}
llvm::TargetOptions options;
auto* targetMachine = target->createTargetMachine(targetTriple, "generic", "", options,
llvm::Optional<llvm::Reloc::Model>());
module.setDataLayout(targetMachine->createDataLayout());
std::error_code error;
llvm::raw_fd_ostream file(fileName, error, llvm::sys::fs::F_None);
if (error) {
llvm::errs() << error.message() << '\n';
return false;
}
llvm::legacy::PassManager passManager;
if (targetMachine->addPassesToEmitFile(passManager, file, fileType)) {
llvm::errs() << "TargetMachine can't emit a file of this type\n";
return false;
}
passManager.run(module);
file.flush();
return true;
}
} // anonymous namespace
int main(int argc, char** argv) {
if (argc == 1) {
std::cout << "error: no input files" << std::endl;
return 1;
}
std::vector<boost::string_ref> args(argv + 1, argv + argc);
const bool syntaxOnly = checkFlag("-fsyntax-only", args);
const bool compileOnly = checkFlag("-c", args);
const bool printAST = checkFlag("-print-ast", args);
const bool outputToStdout = checkFlag("-o=stdout", args);
const bool codegenC = checkFlag("-codegen=c", args);
const bool emitAssembly = checkFlag("-emit-assembly", args) || checkFlag("-S", args);
for (boost::string_ref filePath : args) {
inputFile = fopen(filePath.data(), "rb");
if (!inputFile) {
std::cout << "error: no such file: '" << filePath << "'" << std::endl;
return 1;
}
currentFileName = filePath.data();
int result = yyparse();
if (result != 0) return result;
}
typecheck(globalAST);
std::string outputFile;
if (printAST) {
std::cout << globalAST;
} else if (!syntaxOnly) {
if (!codegenC) {
auto& module = irgen::compile(globalAST);
if (!outputToStdout) {
outputFile = emitAssembly ? "output.s" : "output.o";
auto fileType = emitAssembly ? llvm::TargetMachine::CGFT_AssemblyFile
: llvm::TargetMachine::CGFT_ObjectFile;
emitMachineCode(module, outputFile, fileType);
} else {
module.print(llvm::outs(), nullptr);
}
} else {
outputFile = "output.c";
cgen::compile(globalAST, outputToStdout ? "stdout" : outputFile);
}
}
if (!syntaxOnly && !printAST && !compileOnly && !emitAssembly) {
// Compile (if it's C) and link the output.
assert(!outputFile.empty());
const int ccExitStatus = std::system(("cc " + outputFile).c_str());
std::remove(outputFile.c_str());
if (ccExitStatus != 0) exit(ccExitStatus);
}
}
<commit_msg>Simplify nested if structure in main<commit_after>#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <boost/utility/string_ref.hpp>
#include <llvm/IR/Module.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/FileSystem.h>
#include "../ast/ast_printer.h"
#include "../ast/decl.h"
#include "../parser/parser.hpp"
#include "../sema/typecheck.h"
#include "../cgen/codegen.h"
#include "../irgen/irgen.h"
using namespace delta;
namespace delta {
extern FILE* inputFile;
const char* currentFileName;
extern std::vector<Decl> globalAST;
}
int yyparse();
namespace {
/// If `args` contains `flag`, removes it and returns true, otherwise returns false.
bool checkFlag(boost::string_ref flag, std::vector<boost::string_ref>& args) {
const auto it = std::find(args.begin(), args.end(), flag);
const bool contains = it != args.end();
if (contains) args.erase(it);
return contains;
}
bool emitMachineCode(llvm::Module& module, llvm::StringRef fileName,
llvm::TargetMachine::CodeGenFileType fileType) {
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::InitializeNativeTargetAsmParser();
std::string targetTriple = llvm::sys::getDefaultTargetTriple();
module.setTargetTriple(targetTriple);
std::string errorMessage;
auto* target = llvm::TargetRegistry::lookupTarget(targetTriple, errorMessage);
if (!target) {
llvm::errs() << errorMessage;
return false;
}
llvm::TargetOptions options;
auto* targetMachine = target->createTargetMachine(targetTriple, "generic", "", options,
llvm::Optional<llvm::Reloc::Model>());
module.setDataLayout(targetMachine->createDataLayout());
std::error_code error;
llvm::raw_fd_ostream file(fileName, error, llvm::sys::fs::F_None);
if (error) {
llvm::errs() << error.message() << '\n';
return false;
}
llvm::legacy::PassManager passManager;
if (targetMachine->addPassesToEmitFile(passManager, file, fileType)) {
llvm::errs() << "TargetMachine can't emit a file of this type\n";
return false;
}
passManager.run(module);
file.flush();
return true;
}
} // anonymous namespace
int main(int argc, char** argv) {
if (argc == 1) {
std::cout << "error: no input files" << std::endl;
return 1;
}
std::vector<boost::string_ref> args(argv + 1, argv + argc);
const bool syntaxOnly = checkFlag("-fsyntax-only", args);
const bool compileOnly = checkFlag("-c", args);
const bool printAST = checkFlag("-print-ast", args);
const bool outputToStdout = checkFlag("-o=stdout", args);
const bool codegenC = checkFlag("-codegen=c", args);
const bool emitAssembly = checkFlag("-emit-assembly", args) || checkFlag("-S", args);
for (boost::string_ref filePath : args) {
inputFile = fopen(filePath.data(), "rb");
if (!inputFile) {
std::cout << "error: no such file: '" << filePath << "'" << std::endl;
return 1;
}
currentFileName = filePath.data();
int result = yyparse();
if (result != 0) return result;
}
typecheck(globalAST);
if (syntaxOnly) return 0;
if (printAST) {
std::cout << globalAST;
return 0;
}
std::string outputFile;
if (!codegenC) {
auto& module = irgen::compile(globalAST);
if (outputToStdout) {
module.print(llvm::outs(), nullptr);
return 0;
}
outputFile = emitAssembly ? "output.s" : "output.o";
auto fileType = emitAssembly ? llvm::TargetMachine::CGFT_AssemblyFile
: llvm::TargetMachine::CGFT_ObjectFile;
emitMachineCode(module, outputFile, fileType);
} else {
outputFile = "output.c";
cgen::compile(globalAST, outputToStdout ? "stdout" : outputFile);
}
if (compileOnly || emitAssembly) return 0;
// Compile (if it's C) and link the output.
int ccExitStatus = std::system(("cc " + outputFile).c_str());
std::remove(outputFile.c_str());
return ccExitStatus;
}
<|endoftext|> |
<commit_before>//
// Created by jonas on 10.12.15.
//
#include <string.h>
#include <fstream>
#include <iostream>
#include <cmath>
#include "mesh.h"
void get_line( ifstream& file, string& line )
{
while ( !file.eof())
{
getline( file, line );
if ( line.empty() || line.at( 0 ) == '#' || (line.find('\r') != string::npos && line.length() < 3))
{
line.clear();
continue;
}
return;
}
throw ios_base::eofbit;
}
Mesh::Mesh()
{
}
Mesh::~Mesh()
{
}
const string& Mesh::get_name() const
{
return m_name;
}
const int& Mesh::get_vertices() const
{
return m_vertices;
}
const int& Mesh::get_faces() const
{
return m_faces;
}
const int& Mesh::get_edges() const
{
return m_edges;
}
bool Mesh::load( const char* name )
{
// Set the color of the object
m_ambient[0] = m_specular[0] = m_diffuse[0] = 0.4f;
m_ambient[1] = m_specular[1] = m_diffuse[1] = 0.4f;
m_ambient[2] = m_specular[2] = m_diffuse[2] = 0.4f;
m_shining = 50.0f;
if ( strchr( name, '/' ) == nullptr )
m_name = name;
else
m_name = strrchr( name, '/' ) + 1;
m_name.pop_back(); // pop .off
m_name.pop_back();
m_name.pop_back();
m_name.pop_back();
size_t idx;
float max = 0.f;
Vertex<GLfloat> center;
center.x = 0;
center.y = 0;
center.z = 0;
ifstream file;
file.exceptions( ifstream::failbit | ifstream::badbit );
try
{
file.open( name );
string line;
// First line must start with an OFF
get_line( file, line );
if ( line.find( "OFF" ) == string::npos)
{
cerr << "File in wrong format" << endl;
file.close();
return false;
}
// nextline must contain vertices faces and edges
get_line( file, line );
m_vertices = stoi( line, &idx );
line = line.substr(idx);
m_faces = stoi( line, &idx );
line = line.substr(idx);
m_edges = stoi( line, &idx );
// read all the verticies
for( int v = 0; v < m_vertices; v++)
{
get_line(file, line);
Vertex<GLfloat> vert;
vert.x = stof(line, &idx);
line = line.substr(idx);
vert.y = stof(line, &idx);
line = line.substr(idx);
vert.z = stof(line);
m_verts.push_back(vert);
// take new max value
max = fmaxf(fabsf(vert.x), max);
max = fmaxf(fabsf(vert.y), max);
max = fmaxf(fabsf(vert.z), max);
// center of gravety
center.x += vert.x;
center.y += vert.y;
center.z += vert.z;
}
// read all the faces
for( int f = 0; f < m_faces; f++)
{
get_line(file, line);
stoi(line, &idx);
line = line.substr(idx);
Vertex<int> vert;
vert.x = stoi(line, &idx);
line = line.substr(idx);
vert.y = stoi(line, &idx);
line = line.substr(idx);
vert.z = stoi(line);
m_indicies.push_back(vert);
}
file.close();
} catch ( ifstream::failure e )
{
cerr << "Exception: " << e.what() << endl;
return false;
}
catch ( invalid_argument& ia )
{
cerr << "Invalid argument: " << ia.what() << endl;
return false;
}
center.x = 1.f/(float)m_vertices * center.x;
center.y = 1.f/(float)m_vertices * center.y;
center.z = 1.f/(float)m_vertices * center.z;
for( auto vt = m_verts.begin(); vt != m_verts.end(); vt++)
{
Vertex<GLfloat> diff;
diff.x = (*vt).x - center.x;
diff.y = (*vt).y - center.y;
diff.z = (*vt).z - center.z;
vt->x = 1.f/max*diff.x;
vt->y = 1.f/max*diff.y;
vt->z = 1.f/max*diff.z;
}
for( int i = 0; i < m_vertices; i++)
{
Vertex<GLfloat> v;
v.x = 0;
v.y = 0;
v.z = 0;
m_normals.push_back(v);
}
for( Vertex<GLint> index : m_indicies)
{
int a = index.x;
int b = index.y;
int c = index.z;
Vertex<GLfloat> e0;
e0.x = m_verts[b].x-m_verts[a].x;
e0.y = m_verts[b].y-m_verts[a].y;
e0.z = m_verts[b].z-m_verts[a].z;
Vertex<GLfloat> e1;
e1.x = m_verts[c].x-m_verts[a].x;
e1.y = m_verts[c].y-m_verts[a].y;
e1.z = m_verts[c].z-m_verts[a].z;
Vertex<GLfloat> n;
n.x = e0.y*e1.z - e0.z*e1.y;
n.y = e0.z*e1.x - e0.x*e1.z;
n.z = e0.x*e1.y - e0.y*e1.x;
float norm = sqrt(n.x*n.x + n.y*n.y + n.z*n.z);
if( norm > 0.0001f)
{
n.x /= norm;
n.y /= norm;
n.z /= norm;
}
m_normals[a].x += n.x;
m_normals[a].y += n.y;
m_normals[a].z += n.z;
m_normals[b].x += n.x;
m_normals[b].y += n.y;
m_normals[b].z += n.z;
m_normals[c].x += n.x;
m_normals[c].y += n.y;
m_normals[c].z += n.z;
}
for(auto nt = m_normals.begin(); nt != m_normals.end(); nt++)
{
float norm = sqrt((*nt).x*(*nt).x + (*nt).y*(*nt).y + (*nt).z*(*nt).z);
if( norm > 0.0001f)
{
nt->x /= norm;
nt->y /= norm;
nt->z /= norm;
}
}
return true;
}
void Mesh::draw()
{
glMaterialfv(GL_FRONT, GL_AMBIENT, m_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, m_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, m_specular);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, m_shining);
glBegin(GL_TRIANGLES);
glColor3f( 1.0, 1.0, 1.0 );
for( Vertex<GLint> index : m_indicies)
{
glNormal3f( m_normals[index.x].x,m_normals[index.x].y,m_normals[index.x].z);
glVertex3f( m_verts[index.x].x, m_verts[index.x].y, m_verts[index.x].z );
glNormal3f( m_normals[index.y].x,m_normals[index.y].y,m_normals[index.y].z);
glVertex3f( m_verts[index.y].x, m_verts[index.y].y, m_verts[index.y].z );
glNormal3f( m_normals[index.z].x,m_normals[index.z].y,m_normals[index.z].z);
glVertex3f( m_verts[index.z].x, m_verts[index.z].y, m_verts[index.z].z );
}
glEnd();
}
<commit_msg>make the mesh lighter<commit_after>//
// Created by jonas on 10.12.15.
//
#include <string.h>
#include <fstream>
#include <iostream>
#include <cmath>
#include "mesh.h"
void get_line( ifstream& file, string& line )
{
while ( !file.eof())
{
getline( file, line );
if ( line.empty() || line.at( 0 ) == '#' || (line.find('\r') != string::npos && line.length() < 3))
{
line.clear();
continue;
}
return;
}
throw ios_base::eofbit;
}
Mesh::Mesh()
{
}
Mesh::~Mesh()
{
}
const string& Mesh::get_name() const
{
return m_name;
}
const int& Mesh::get_vertices() const
{
return m_vertices;
}
const int& Mesh::get_faces() const
{
return m_faces;
}
const int& Mesh::get_edges() const
{
return m_edges;
}
bool Mesh::load( const char* name )
{
// Set the color of the object
m_ambient[0] = m_specular[0] = m_diffuse[0] = 0.8f;
m_ambient[1] = m_specular[1] = m_diffuse[1] = 0.8f;
m_ambient[2] = m_specular[2] = m_diffuse[2] = 0.8f;
m_shining = 50.0f;
if ( strchr( name, '/' ) == nullptr )
m_name = name;
else
m_name = strrchr( name, '/' ) + 1;
m_name.pop_back(); // pop .off
m_name.pop_back();
m_name.pop_back();
m_name.pop_back();
size_t idx;
float max = 0.f;
Vertex<GLfloat> center;
center.x = 0;
center.y = 0;
center.z = 0;
ifstream file;
file.exceptions( ifstream::failbit | ifstream::badbit );
try
{
file.open( name );
string line;
// First line must start with an OFF
get_line( file, line );
if ( line.find( "OFF" ) == string::npos)
{
cerr << "File in wrong format" << endl;
file.close();
return false;
}
// nextline must contain vertices faces and edges
get_line( file, line );
m_vertices = stoi( line, &idx );
line = line.substr(idx);
m_faces = stoi( line, &idx );
line = line.substr(idx);
m_edges = stoi( line, &idx );
// read all the verticies
for( int v = 0; v < m_vertices; v++)
{
get_line(file, line);
Vertex<GLfloat> vert;
vert.x = stof(line, &idx);
line = line.substr(idx);
vert.y = stof(line, &idx);
line = line.substr(idx);
vert.z = stof(line);
m_verts.push_back(vert);
// take new max value
max = fmaxf(fabsf(vert.x), max);
max = fmaxf(fabsf(vert.y), max);
max = fmaxf(fabsf(vert.z), max);
// center of gravety
center.x += vert.x;
center.y += vert.y;
center.z += vert.z;
}
// read all the faces
for( int f = 0; f < m_faces; f++)
{
get_line(file, line);
stoi(line, &idx);
line = line.substr(idx);
Vertex<int> vert;
vert.x = stoi(line, &idx);
line = line.substr(idx);
vert.y = stoi(line, &idx);
line = line.substr(idx);
vert.z = stoi(line);
m_indicies.push_back(vert);
}
file.close();
} catch ( ifstream::failure e )
{
cerr << "Exception: " << e.what() << endl;
return false;
}
catch ( invalid_argument& ia )
{
cerr << "Invalid argument: " << ia.what() << endl;
return false;
}
center.x = 1.f/(float)m_vertices * center.x;
center.y = 1.f/(float)m_vertices * center.y;
center.z = 1.f/(float)m_vertices * center.z;
for( auto vt = m_verts.begin(); vt != m_verts.end(); vt++)
{
Vertex<GLfloat> diff;
diff.x = (*vt).x - center.x;
diff.y = (*vt).y - center.y;
diff.z = (*vt).z - center.z;
vt->x = 1.f/max*diff.x;
vt->y = 1.f/max*diff.y;
vt->z = 1.f/max*diff.z;
}
for( int i = 0; i < m_vertices; i++)
{
Vertex<GLfloat> v;
v.x = 0;
v.y = 0;
v.z = 0;
m_normals.push_back(v);
}
for( Vertex<GLint> index : m_indicies)
{
int a = index.x;
int b = index.y;
int c = index.z;
Vertex<GLfloat> e0;
e0.x = m_verts[b].x-m_verts[a].x;
e0.y = m_verts[b].y-m_verts[a].y;
e0.z = m_verts[b].z-m_verts[a].z;
Vertex<GLfloat> e1;
e1.x = m_verts[c].x-m_verts[a].x;
e1.y = m_verts[c].y-m_verts[a].y;
e1.z = m_verts[c].z-m_verts[a].z;
Vertex<GLfloat> n;
n.x = e0.y*e1.z - e0.z*e1.y;
n.y = e0.z*e1.x - e0.x*e1.z;
n.z = e0.x*e1.y - e0.y*e1.x;
float norm = sqrt(n.x*n.x + n.y*n.y + n.z*n.z);
if( norm > 0.0001f)
{
n.x /= norm;
n.y /= norm;
n.z /= norm;
}
m_normals[a].x += n.x;
m_normals[a].y += n.y;
m_normals[a].z += n.z;
m_normals[b].x += n.x;
m_normals[b].y += n.y;
m_normals[b].z += n.z;
m_normals[c].x += n.x;
m_normals[c].y += n.y;
m_normals[c].z += n.z;
}
for(auto nt = m_normals.begin(); nt != m_normals.end(); nt++)
{
float norm = sqrt((*nt).x*(*nt).x + (*nt).y*(*nt).y + (*nt).z*(*nt).z);
if( norm > 0.0001f)
{
nt->x /= norm;
nt->y /= norm;
nt->z /= norm;
}
}
return true;
}
void Mesh::draw()
{
glMaterialfv(GL_FRONT, GL_AMBIENT, m_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, m_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, m_specular);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, m_shining);
glBegin(GL_TRIANGLES);
glColor3f( 1.0, 1.0, 1.0 );
for( Vertex<GLint> index : m_indicies)
{
glNormal3f( m_normals[index.x].x,m_normals[index.x].y,m_normals[index.x].z);
glVertex3f( m_verts[index.x].x, m_verts[index.x].y, m_verts[index.x].z );
glNormal3f( m_normals[index.y].x,m_normals[index.y].y,m_normals[index.y].z);
glVertex3f( m_verts[index.y].x, m_verts[index.y].y, m_verts[index.y].z );
glNormal3f( m_normals[index.z].x,m_normals[index.z].y,m_normals[index.z].z);
glVertex3f( m_verts[index.z].x, m_verts[index.z].y, m_verts[index.z].z );
}
glEnd();
}
<|endoftext|> |
<commit_before>#include "make-content-addressed.hh"
#include "references.hh"
namespace nix {
std::map<StorePath, StorePath> makeContentAddressed(
Store & srcStore,
Store & dstStore,
const StorePathSet & storePaths)
{
// FIXME: use closure of storePaths.
auto paths = srcStore.topoSortPaths(storePaths);
std::reverse(paths.begin(), paths.end());
std::map<StorePath, StorePath> remappings;
for (auto & path : paths) {
auto pathS = srcStore.printStorePath(path);
auto oldInfo = srcStore.queryPathInfo(path);
std::string oldHashPart(path.hashPart());
StringSink sink;
srcStore.narFromPath(path, sink);
StringMap rewrites;
StorePathSet references;
bool hasSelfReference = false;
for (auto & ref : oldInfo->references) {
if (ref == path)
hasSelfReference = true;
else {
auto i = remappings.find(ref);
auto replacement = i != remappings.end() ? i->second : ref;
// FIXME: warn about unremapped paths?
if (replacement != ref)
rewrites.insert_or_assign(srcStore.printStorePath(ref), srcStore.printStorePath(replacement));
references.insert(std::move(replacement));
}
}
sink.s = rewriteStrings(sink.s, rewrites);
HashModuloSink hashModuloSink(htSHA256, oldHashPart);
hashModuloSink(sink.s);
auto narHash = hashModuloSink.finish().first;
ValidPathInfo info {
dstStore.makeFixedOutputPath(FileIngestionMethod::Recursive, narHash, path.name(), references, hasSelfReference),
narHash,
};
info.references = std::move(references);
if (hasSelfReference) info.references.insert(info.path);
info.narSize = sink.s.size();
info.ca = FixedOutputHash {
.method = FileIngestionMethod::Recursive,
.hash = info.narHash,
};
printInfo("rewrote '%s' to '%s'", pathS, srcStore.printStorePath(info.path));
auto source = sinkToSource([&](Sink & nextSink) {
RewritingSink rsink2(oldHashPart, std::string(info.path.hashPart()), nextSink);
rsink2(sink.s);
rsink2.flush();
});
dstStore.addToStore(info, *source);
remappings.insert_or_assign(std::move(path), std::move(info.path));
}
return remappings;
}
}
<commit_msg>Fix makeContentAddressed() on self-references<commit_after>#include "make-content-addressed.hh"
#include "references.hh"
namespace nix {
std::map<StorePath, StorePath> makeContentAddressed(
Store & srcStore,
Store & dstStore,
const StorePathSet & storePaths)
{
StorePathSet closure;
srcStore.computeFSClosure(storePaths, closure);
auto paths = srcStore.topoSortPaths(closure);
std::reverse(paths.begin(), paths.end());
std::map<StorePath, StorePath> remappings;
for (auto & path : paths) {
auto pathS = srcStore.printStorePath(path);
auto oldInfo = srcStore.queryPathInfo(path);
std::string oldHashPart(path.hashPart());
StringSink sink;
srcStore.narFromPath(path, sink);
StringMap rewrites;
StorePathSet references;
bool hasSelfReference = false;
for (auto & ref : oldInfo->references) {
if (ref == path)
hasSelfReference = true;
else {
auto i = remappings.find(ref);
auto replacement = i != remappings.end() ? i->second : ref;
// FIXME: warn about unremapped paths?
if (replacement != ref)
rewrites.insert_or_assign(srcStore.printStorePath(ref), srcStore.printStorePath(replacement));
references.insert(std::move(replacement));
}
}
sink.s = rewriteStrings(sink.s, rewrites);
HashModuloSink hashModuloSink(htSHA256, oldHashPart);
hashModuloSink(sink.s);
auto narModuloHash = hashModuloSink.finish().first;
auto dstPath = dstStore.makeFixedOutputPath(
FileIngestionMethod::Recursive, narModuloHash, path.name(), references, hasSelfReference);
printInfo("rewroting '%s' to '%s'", pathS, srcStore.printStorePath(dstPath));
StringSink sink2;
RewritingSink rsink2(oldHashPart, std::string(dstPath.hashPart()), sink2);
rsink2(sink.s);
rsink2.flush();
ValidPathInfo info { dstPath, hashString(htSHA256, sink2.s) };
info.references = std::move(references);
if (hasSelfReference) info.references.insert(info.path);
info.narSize = sink.s.size();
info.ca = FixedOutputHash {
.method = FileIngestionMethod::Recursive,
.hash = narModuloHash,
};
StringSource source(sink2.s);
dstStore.addToStore(info, source);
remappings.insert_or_assign(std::move(path), std::move(info.path));
}
return remappings;
}
}
<|endoftext|> |
<commit_before>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER 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.
*
* WATCHER is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
#include "messageStreamFilter.h"
#include "logger.h"
using namespace watcher;
INIT_LOGGER(MessageStreamFilter, "MessageStreamFilter");
MessageStreamFilter::MessageStreamFilter() :
layer(), messageType(0), region()
{
TRACE_ENTER();
TRACE_EXIT();
}
MessageStreamFilter::MessageStreamFilter(const MessageStreamFilter ©me)
{
TRACE_ENTER();
*this=copyme;
TRACE_EXIT();
}
MessageStreamFilter::~MessageStreamFilter()
{
TRACE_ENTER();
TRACE_EXIT();
}
GUILayer MessageStreamFilter::getLayer() const { return layer; }
void MessageStreamFilter::setLayer(const GUILayer &l) { layer=l; }
unsigned int MessageStreamFilter::getMessageType() const { return messageType; }
void MessageStreamFilter::setMessageType(const unsigned int &t) { messageType=t; }
WatcherRegion MessageStreamFilter::getRegion() const { return region; }
void MessageStreamFilter::setRegion(const WatcherRegion &r) { region=r; }
bool MessageStreamFilter::operator==(const MessageStreamFilter &other) const
{
TRACE_ENTER();
bool retVal=
layer==other.layer &&
messageType==other.messageType &&
region==other.region;
TRACE_EXIT_RET_BOOL(retVal);
return retVal;
}
MessageStreamFilter &MessageStreamFilter::operator=(const MessageStreamFilter &other)
{
TRACE_ENTER();
layer=other.layer;
messageType=other.messageType;
region=other.region;
TRACE_EXIT();
}
//virtual
std::ostream &MessageStreamFilter::toStream(std::ostream &out) const
{
TRACE_ENTER();
out << " layer: " << layer
<< " type: " << messageType
<< " region: " << region;
TRACE_EXIT();
return out;
}
std::ostream &operator<<(std::ostream &out, const MessageStreamFilter &messStreamFilter)
{
return messStreamFilter.operator<<(out);
}
<commit_msg>scope operator<< properly<commit_after>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER 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.
*
* WATCHER is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
#include "messageStreamFilter.h"
#include "logger.h"
using namespace watcher;
INIT_LOGGER(MessageStreamFilter, "MessageStreamFilter");
MessageStreamFilter::MessageStreamFilter() :
layer(), messageType(0), region()
{
TRACE_ENTER();
TRACE_EXIT();
}
MessageStreamFilter::MessageStreamFilter(const MessageStreamFilter ©me)
{
TRACE_ENTER();
*this=copyme;
TRACE_EXIT();
}
MessageStreamFilter::~MessageStreamFilter()
{
TRACE_ENTER();
TRACE_EXIT();
}
GUILayer MessageStreamFilter::getLayer() const { return layer; }
void MessageStreamFilter::setLayer(const GUILayer &l) { layer=l; }
unsigned int MessageStreamFilter::getMessageType() const { return messageType; }
void MessageStreamFilter::setMessageType(const unsigned int &t) { messageType=t; }
WatcherRegion MessageStreamFilter::getRegion() const { return region; }
void MessageStreamFilter::setRegion(const WatcherRegion &r) { region=r; }
bool MessageStreamFilter::operator==(const MessageStreamFilter &other) const
{
TRACE_ENTER();
bool retVal=
layer==other.layer &&
messageType==other.messageType &&
region==other.region;
TRACE_EXIT_RET_BOOL(retVal);
return retVal;
}
MessageStreamFilter &MessageStreamFilter::operator=(const MessageStreamFilter &other)
{
TRACE_ENTER();
layer=other.layer;
messageType=other.messageType;
region=other.region;
TRACE_EXIT();
}
//virtual
std::ostream &MessageStreamFilter::toStream(std::ostream &out) const
{
TRACE_ENTER();
out << " layer: " << layer
<< " type: " << messageType
<< " region: " << region;
TRACE_EXIT();
return out;
}
std::ostream &watcher::operator<<(std::ostream &out, const MessageStreamFilter &messStreamFilter)
{
return messStreamFilter.operator<<(out);
}
<|endoftext|> |
<commit_before>/*******************************************************************************
Copyright (c) 2014, Jan Koester jan.koester@gmx.net
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include <fcntl.h>
#include <cstdlib>
#include <config.h>
#include <errno.h>
#include <signal.h>
#include "os/os.h"
#include "threadpool.h"
#define READEVENT 0
#define SENDEVENT 1
//#define DEBUG_MUTEX
#include "../event.h"
libhttppp::Event::Event(ServerSocket *serversocket) {
_ServerSocket=serversocket;
_ServerSocket->setnonblocking();
_ServerSocket->listenSocket();
_EventEndloop =true;
_Cpool= new ConnectionPool(_ServerSocket);
_Events = new struct kevent[(_ServerSocket->getMaxconnections())];
_WorkerPool = new ThreadPool;
_Mutex = new Mutex;
_firstConnectionContext=NULL;
_lastConnectionContext=NULL;
_firstWorkerContext=NULL;
_lastWorkerContext=NULL;
}
libhttppp::Event::~Event() {
delete _Cpool;
delete[] _Events;
delete _firstConnectionContext;
delete _WorkerPool;
delete _firstWorkerContext;
_lastWorkerContext=NULL;
_lastConnectionContext=NULL;
delete _Mutex;
}
void libhttppp::Event::CtrlHandler(int signum) {
_EventEndloop=false;
}
void libhttppp::Event::runEventloop() {
int srvssocket=_ServerSocket->getSocket();
int maxconnets=_ServerSocket->getMaxconnections();
struct kevent setEvent=(struct kevent) {
0
};
_Kq = kqueue();
EV_SET(&setEvent, srvssocket, EVFILT_READ , EV_ADD || EV_CLEAR , 0, 0, NULL);
if (kevent(_Kq, &setEvent, 1, NULL, 0, NULL) == -1)
_httpexception.Critical("runeventloop","can't create kqueue!");
signal(SIGPIPE, SIG_IGN);
SYSInfo sysinfo;
size_t thrs = sysinfo.getNumberOfProcessors();
for(size_t i=0; i<thrs; i++) {
WorkerContext *curwrkctx=addWorkerContext();
curwrkctx->_CurThread->Create(WorkerThread,curwrkctx);
}
for(WorkerContext *curth=_firstWorkerContext; curth; curth=curth->_nextWorkerContext) {
curth->_CurThread->Join();
}
}
void *libhttppp::Event::WorkerThread(void *wrkevent) {
HTTPException httpexception;
WorkerContext *wctx=(WorkerContext*)wrkevent;
Event *wevent=wctx->_CurEvent;
int srvssocket=wevent->_ServerSocket->getSocket();
int maxconnets=wevent->_ServerSocket->getMaxconnections();
SYSInfo sysinfo;
wctx->_CurThread->setPid(sysinfo.getPid());
struct kevent setEvent=(struct kevent) {
0
};
int nev = 0;
while(wevent->_EventEndloop) {
nev = kevent(wevent->_Kq, NULL, 0, wevent->_Events,maxconnets, NULL);
if(nev<0) {
if(errno== EINTR) {
continue;
} else {
httpexception.Critical("epoll wait failure");
throw httpexception;
}
}
for(int i=0; i<nev; i++) {
ConnectionContext *curct=NULL;
if(wevent->_Events[i].ident == (uintptr_t)srvssocket) {
try {
/*will create warning debug mode that normally because the check already connection
* with this socket if getconnection throw they will be create a new one
*/
wevent->addConnectionContext(&curct);
#ifdef DEBUG_MUTEX
httpexception.Note("runeventloop","Lock ConnectionMutex");
#endif
curct->_Mutex->lock();
ClientSocket *clientsocket=curct->_CurConnection->getClientSocket();
int fd=wevent->_ServerSocket->acceptEvent(clientsocket);
clientsocket->setnonblocking();
curct->_EventCounter=i;
if(fd>0) {
setEvent.fflags=0;
setEvent.filter=EVFILT_READ;
setEvent.flags=EV_ADD;
setEvent.udata=(void*) curct;
setEvent.ident=(uintptr_t)fd;
EV_SET(&setEvent, fd, EVFILT_READ, EV_ADD, 0, 0, (void*) curct);
if (kevent(wevent->_Kq, &setEvent, 1, NULL, 0, NULL) == -1) {
httpexception.Error("runeventloop","can't accep't in kqueue!");
} else {
wevent->ConnectEvent(curct->_CurConnection);
}
#ifdef DEBUG_MUTEX
httpexception.Note("runeventloop","Unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
} else {
#ifdef DEBUG_MUTEX
httpexception.Note("runeventloop","Unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
wevent->delConnectionContext(curct,NULL);
}
} catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
httpexception.Note("runeventloop","Unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
wevent->delConnectionContext(curct,NULL);
if(e.isCritical())
throw e;
}
} else {
curct=(ConnectionContext*)wevent->_Events[i].udata;
switch(wevent->_Events[i].filter) {
case EVFILT_READ: {
#ifdef DEBUG_MUTEX
httpexception.Note("ReadEvent","lock ConnectionMutex");
#endif
curct->_Mutex->lock();
Connection *con=(Connection*)curct->_CurConnection;
try {
char buf[BLOCKSIZE];
int rcvsize=0;
do {
rcvsize=wevent->_ServerSocket->recvData(con->getClientSocket(),buf,BLOCKSIZE);
if(rcvsize>0)
con->addRecvQueue(buf,rcvsize);
} while(rcvsize>0);
wevent->RequestEvent(con);
#ifdef DEBUG_MUTEX
httpexception.Note("ReadEvent","unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
} catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
httpexception.Note("ReadEvent","unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
if(e.isCritical()) {
throw e;
}
if(e.isError()) {
con->cleanRecvData();
goto CLOSECONNECTION;
}
}
}
case EVFILT_WRITE: {
#ifdef DEBUG_MUTEX
httpexception.Note("WriteEvent","lock ConnectionMutex");
#endif
curct->_Mutex->lock();
Connection *con=curct->_CurConnection;
try {
ssize_t sended=0;
while(con->getSendData()) {
sended=wevent->_ServerSocket->sendData(con->getClientSocket(),
(void*)con->getSendData()->getData(),
con->getSendData()->getDataSize());
if(sended>0)
con->resizeSendQueue(sended);
}
wevent->ResponseEvent(con);
} catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
httpexception.Note("WriteEvent","unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
goto CLOSECONNECTION;
}
#ifdef DEBUG_MUTEX
httpexception.Note("WriteEvent","unlock ConnectionMutex");
#endif
if(curct)
curct->_Mutex->unlock();
}
}
if (wevent->_Events[i].flags & EV_ERROR) {
CLOSECONNECTION:
#ifdef DEBUG_MUTEX
httpexception.Note("CloseEvent","ConnectionMutex");
#endif
curct->_Mutex->lock();
Connection *con=(Connection*)curct->_CurConnection;
wevent->DisconnectEvent(con);
try {
EV_SET(&setEvent,con->getClientSocket()->getSocket(),
wevent->_Events[curct->_EventCounter].filter,
EV_DELETE, 0, 0, NULL);
if (kevent(wevent->_Kq,&setEvent, 1, NULL, 0, NULL) == -1)
httpexception.Error("Connection can't delete from kqueue");
#ifdef DEBUG_MUTEX
httpexception.Note("CloseEvent","unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
wevent->delConnectionContext(curct,NULL);
curcon=NULL;
httpexception.Note("Connection shutdown!");
} catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
httpexception.Note("CloseEvent","unlock ConnectionMutex");
#endif
if(curct)
curct->_Mutex->unlock();
httpexception.Note("Can't do Connection shutdown!");
}
}
}
signal(SIGINT, CtrlHandler);
}
return NULL;
}
<commit_msg>reworked kqueue<commit_after>/*******************************************************************************
Copyright (c) 2014, Jan Koester jan.koester@gmx.net
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include <fcntl.h>
#include <cstdlib>
#include <config.h>
#include <errno.h>
#include <signal.h>
#include "os/os.h"
#include "threadpool.h"
#define READEVENT 0
#define SENDEVENT 1
//#define DEBUG_MUTEX
#include "../event.h"
libhttppp::Event::Event(ServerSocket *serversocket) {
_ServerSocket=serversocket;
_ServerSocket->setnonblocking();
_ServerSocket->listenSocket();
_EventEndloop =true;
_Cpool= new ConnectionPool(_ServerSocket);
_Events = new struct kevent[(_ServerSocket->getMaxconnections())];
_WorkerPool = new ThreadPool;
_Mutex = new Mutex;
_firstConnectionContext=NULL;
_lastConnectionContext=NULL;
_firstWorkerContext=NULL;
_lastWorkerContext=NULL;
}
libhttppp::Event::~Event() {
delete _Cpool;
delete[] _Events;
delete _firstConnectionContext;
delete _WorkerPool;
delete _firstWorkerContext;
_lastWorkerContext=NULL;
_lastConnectionContext=NULL;
delete _Mutex;
}
void libhttppp::Event::CtrlHandler(int signum) {
_EventEndloop=false;
}
void libhttppp::Event::runEventloop() {
int srvssocket=_ServerSocket->getSocket();
int maxconnets=_ServerSocket->getMaxconnections();
struct kevent setEvent=(struct kevent) {
0
};
_Kq = kqueue();
EV_SET(&setEvent, srvssocket, EVFILT_READ , EV_ADD || EV_CLEAR , 0, 0, NULL);
if (kevent(_Kq, &setEvent, 1, NULL, 0, NULL) == -1)
_httpexception.Critical("runeventloop","can't create kqueue!");
signal(SIGPIPE, SIG_IGN);
SYSInfo sysinfo;
size_t thrs = sysinfo.getNumberOfProcessors();
for(size_t i=0; i<thrs; i++) {
WorkerContext *curwrkctx=addWorkerContext();
curwrkctx->_CurThread->Create(WorkerThread,curwrkctx);
}
for(WorkerContext *curth=_firstWorkerContext; curth; curth=curth->_nextWorkerContext) {
curth->_CurThread->Join();
}
}
void *libhttppp::Event::WorkerThread(void *wrkevent) {
HTTPException httpexception;
WorkerContext *wctx=(WorkerContext*)wrkevent;
Event *wevent=wctx->_CurEvent;
int srvssocket=wevent->_ServerSocket->getSocket();
int maxconnets=wevent->_ServerSocket->getMaxconnections();
SYSInfo sysinfo;
wctx->_CurThread->setPid(sysinfo.getPid());
struct kevent setEvent=(struct kevent) {
0
};
int nev = 0;
while(wevent->_EventEndloop) {
nev = kevent(wevent->_Kq, NULL, 0, wevent->_Events,maxconnets, NULL);
if(nev<0) {
if(errno== EINTR) {
continue;
} else {
httpexception.Critical("epoll wait failure");
throw httpexception;
}
}
for(int i=0; i<nev; i++) {
ConnectionContext *curct=NULL;
if(wevent->_Events[i].ident == (uintptr_t)srvssocket) {
try {
/*will create warning debug mode that normally because the check already connection
* with this socket if getconnection throw they will be create a new one
*/
wevent->addConnectionContext(&curct);
#ifdef DEBUG_MUTEX
httpexception.Note("runeventloop","Lock ConnectionMutex");
#endif
curct->_Mutex->lock();
ClientSocket *clientsocket=curct->_CurConnection->getClientSocket();
int fd=wevent->_ServerSocket->acceptEvent(clientsocket);
clientsocket->setnonblocking();
curct->_EventCounter=i;
if(fd>0) {
setEvent.fflags=0;
setEvent.filter=EVFILT_READ;
setEvent.flags=EV_ADD;
setEvent.udata=(void*) curct;
setEvent.ident=(uintptr_t)fd;
EV_SET(&setEvent, fd, EVFILT_READ, EV_ADD, 0, 0, (void*) curct);
if (kevent(wevent->_Kq, &setEvent, 1, NULL, 0, NULL) == -1) {
httpexception.Error("runeventloop","can't accep't in kqueue!");
} else {
wevent->ConnectEvent(curct->_CurConnection);
}
#ifdef DEBUG_MUTEX
httpexception.Note("runeventloop","Unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
} else {
#ifdef DEBUG_MUTEX
httpexception.Note("runeventloop","Unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
wevent->delConnectionContext(curct,NULL);
}
} catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
httpexception.Note("runeventloop","Unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
wevent->delConnectionContext(curct,NULL);
if(e.isCritical())
throw e;
}
} else {
curct=(ConnectionContext*)wevent->_Events[i].udata;
switch(wevent->_Events[i].filter) {
case EVFILT_READ: {
#ifdef DEBUG_MUTEX
httpexception.Note("ReadEvent","lock ConnectionMutex");
#endif
curct->_Mutex->lock();
Connection *con=(Connection*)curct->_CurConnection;
try {
char buf[BLOCKSIZE];
int rcvsize=0;
do {
rcvsize=wevent->_ServerSocket->recvData(con->getClientSocket(),buf,BLOCKSIZE);
if(rcvsize>0)
con->addRecvQueue(buf,rcvsize);
} while(rcvsize>0);
wevent->RequestEvent(con);
#ifdef DEBUG_MUTEX
httpexception.Note("ReadEvent","unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
} catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
httpexception.Note("ReadEvent","unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
if(e.isCritical()) {
throw e;
}
if(e.isError()) {
con->cleanRecvData();
goto CLOSECONNECTION;
}
}
}
case EVFILT_WRITE: {
#ifdef DEBUG_MUTEX
httpexception.Note("WriteEvent","lock ConnectionMutex");
#endif
curct->_Mutex->lock();
Connection *con=curct->_CurConnection;
try {
ssize_t sended=0;
while(con->getSendData()) {
sended=wevent->_ServerSocket->sendData(con->getClientSocket(),
(void*)con->getSendData()->getData(),
con->getSendData()->getDataSize());
if(sended>0)
con->resizeSendQueue(sended);
}
wevent->ResponseEvent(con);
} catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
httpexception.Note("WriteEvent","unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
goto CLOSECONNECTION;
}
#ifdef DEBUG_MUTEX
httpexception.Note("WriteEvent","unlock ConnectionMutex");
#endif
if(curct)
curct->_Mutex->unlock();
}
}
if (wevent->_Events[i].flags & EV_ERROR) {
CLOSECONNECTION:
#ifdef DEBUG_MUTEX
httpexception.Note("CloseEvent","ConnectionMutex");
#endif
curct->_Mutex->lock();
Connection *con=(Connection*)curct->_CurConnection;
wevent->DisconnectEvent(con);
try {
EV_SET(&setEvent,con->getClientSocket()->getSocket(),
wevent->_Events[curct->_EventCounter].filter,
EV_DELETE, 0, 0, NULL);
if (kevent(wevent->_Kq,&setEvent, 1, NULL, 0, NULL) == -1)
httpexception.Error("Connection can't delete from kqueue");
#ifdef DEBUG_MUTEX
httpexception.Note("CloseEvent","unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
wevent->delConnectionContext(curct,NULL);
curct=NULL;
httpexception.Note("Connection shutdown!");
} catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
httpexception.Note("CloseEvent","unlock ConnectionMutex");
#endif
if(curct)
curct->_Mutex->unlock();
httpexception.Note("Can't do Connection shutdown!");
}
}
}
signal(SIGINT, CtrlHandler);
}
return NULL;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
Copyright (c) 2014, Jan Koester jan.koester@gmx.net
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include <fcntl.h>
#include <cstdlib>
#include <config.h>
#include <errno.h>
#include <signal.h>
#include "os/os.h"
#include "threadpool.h"
#define READEVENT 0
#define SENDEVENT 1
//#define DEBUG_MUTEX
#include "../event.h"
libhttppp::Event::Event(ServerSocket *serversocket) {
_ServerSocket=serversocket;
_ServerSocket->setnonblocking();
_ServerSocket->listenSocket();
_EventEndloop =true;
_Cpool= new ConnectionPool(_ServerSocket);
_Events = new struct kevent[(_ServerSocket->getMaxconnections())];
_WorkerPool = new ThreadPool;
_Mutex = new Mutex;
_firstConnectionContext=NULL;
_lastConnectionContext=NULL;
_firstWorkerContext=NULL;
_lastWorkerContext=NULL;
}
libhttppp::Event::~Event() {
delete _Cpool;
delete[] _Events;
delete _firstConnectionContext;
delete _WorkerPool;
delete _firstWorkerContext;
_lastWorkerContext=NULL;
_lastConnectionContext=NULL;
delete _Mutex;
}
void libhttppp::Event::CtrlHandler(int signum) {
_EventEndloop=false;
}
void libhttppp::Event::runEventloop() {
int srvssocket=_ServerSocket->getSocket();
int maxconnets=_ServerSocket->getMaxconnections();
struct kevent setEvent=(struct kevent) {
0
};
_Kq = kqueue();
EV_SET(&setEvent, srvssocket, EVFILT_READ , EV_ADD || EV_CLEAR , 0, 0, NULL);
if (kevent(_Kq, &setEvent, 1, NULL, 0, NULL) == -1)
_httpexception.Critical("runeventloop","can't create kqueue!");
signal(SIGPIPE, SIG_IGN);
SYSInfo sysinfo;
size_t thrs = sysinfo.getNumberOfProcessors();
for(size_t i=0; i<thrs; i++) {
WorkerContext *curwrkctx=addWorkerContext();
curwrkctx->_CurThread->Create(WorkerThread,curwrkctx);
}
for(WorkerContext *curth=_firstWorkerContext; curth; curth=curth->_nextWorkerContext) {
curth->_CurThread->Join();
}
}
void *libhttppp::Event::WorkerThread(void *wrkevent) {
HTTPException httpexception;
WorkerContext *wctx=(WorkerContext*)wrkevent;
Event *wevent=wctx->_CurEvent;
int srvssocket=wevent->_ServerSocket->getSocket();
int maxconnets=wevent->_ServerSocket->getMaxconnections();
SYSInfo sysinfo;
wctx->_CurThread->setPid(sysinfo.getPid());
struct kevent setEvent=(struct kevent) {
0
};
int nev = 0;
while(wevent->_EventEndloop) {
nev = kevent(wevent->_Kq, NULL, 0, wevent->_Events,maxconnets, NULL);
if(nev<0) {
if(errno== EINTR) {
continue;
} else {
httpexception.Critical("epoll wait failure");
throw httpexception;
}
}
for(int i=0; i<nev; i++) {
ConnectionContext *curct=NULL;
if(wevent->_Events[i].ident == (uintptr_t)srvssocket) {
try {
/*will create warning debug mode that normally because the check already connection
* with this socket if getconnection throw they will be create a new one
*/
wevent->addConnectionContext(&curct);
#ifdef DEBUG_MUTEX
httpexception.Note("runeventloop","Lock ConnectionMutex");
#endif
curct->_Mutex->lock();
ClientSocket *clientsocket=curct->_CurConnection->getClientSocket();
int fd=wevent->_ServerSocket->acceptEvent(clientsocket);
clientsocket->setnonblocking();
curct->_EventCounter=i;
if(fd>0) {
setEvent.fflags=0;
setEvent.filter=EVFILT_READ;
setEvent.flags=EV_ADD;
setEvent.udata=(void*) curct;
setEvent.ident=(uintptr_t)fd;
EV_SET(&setEvent, fd, EVFILT_READ, EV_ADD, 0, 0, (void*) curct);
if (kevent(wevent->_Kq, &setEvent, 1, NULL, 0, NULL) == -1) {
httpexception.Error("runeventloop","can't accep't in kqueue!");
} else {
wevent->ConnectEvent(curct->_CurConnection);
}
#ifdef DEBUG_MUTEX
httpexception.Note("runeventloop","Unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
} else {
#ifdef DEBUG_MUTEX
httpexception.Note("runeventloop","Unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
wevent->delConnectionContext(curct,NULL);
}
} catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
httpexception.Note("runeventloop","Unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
wevent->delConnectionContext(curct,NULL);
if(e.isCritical())
throw e;
}
} else {
curct=(ConnectionContext*)wevent->_Events[i].udata;
switch(wevent->_Events[i].filter) {
case EVFILT_READ: {
#ifdef DEBUG_MUTEX
httpexception.Note("ReadEvent","lock ConnectionMutex");
#endif
curct->_Mutex->lock();
Connection *con=(Connection*)curct->_CurConnection;
try {
char buf[BLOCKSIZE];
int rcvsize=0;
do {
rcvsize=wevent->_ServerSocket->recvData(con->getClientSocket(),buf,BLOCKSIZE);
if(rcvsize>0)
con->addRecvQueue(buf,rcvsize);
} while(rcvsize>0);
wevent->RequestEvent(con);
#ifdef DEBUG_MUTEX
httpexception.Note("ReadEvent","unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
} catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
httpexception.Note("ReadEvent","unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
if(e.isCritical()) {
throw e;
}
if(e.isError()) {
con->cleanRecvData();
goto CLOSECONNECTION;
}
}
}
case EVFILT_WRITE: {
#ifdef DEBUG_MUTEX
httpexception.Note("WriteEvent","lock ConnectionMutex");
#endif
curct->_Mutex->lock();
Connection *con=curct->_CurConnection;
try {
ssize_t sended=0;
while(con->getSendData()) {
sended=wevent->_ServerSocket->sendData(con->getClientSocket(),
(void*)con->getSendData()->getData(),
con->getSendData()->getDataSize());
if(sended>0)
con->resizeSendQueue(sended);
}
wevent->ResponseEvent(con);
} catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
httpexception.Note("WriteEvent","unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
goto CLOSECONNECTION;
}
#ifdef DEBUG_MUTEX
httpexception.Note("WriteEvent","unlock ConnectionMutex");
#endif
if(curct)
curct->_Mutex->unlock();
}
}
if (wevent->_Events[i].flags & EV_ERROR) {
CLOSECONNECTION:
#ifdef DEBUG_MUTEX
httpexception.Note("CloseEvent","ConnectionMutex");
#endif
curct->_Mutex->lock();
Connection *con=(Connection*)curct->_CurConnection;
wevent->DisconnectEvent(con);
try {
EV_SET(&setEvent,con->getClientSocket()->getSocket(),
wevent->_Events[curct->_EventCounter].filter,
EV_DELETE, 0, 0, NULL);
if (kevent(wevent->_Kq,&setEvent, 1, NULL, 0, NULL) == -1)
httpexception.Error("Connection can't delete from kqueue");
#ifdef DEBUG_MUTEX
httpexception.Note("CloseEvent","unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
wevent->delConnectionContext(curct,NULL);
curct=NULL;
httpexception.Note("Connection shutdown!");
} catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
httpexception.Note("CloseEvent","unlock ConnectionMutex");
#endif
if(curct)
curct->_Mutex->unlock();
httpexception.Note("Can't do Connection shutdown!");
}
}
}
}
signal(SIGINT, CtrlHandler);
}
return NULL;
}
<commit_msg>reworked kqueue<commit_after>/*******************************************************************************
Copyright (c) 2014, Jan Koester jan.koester@gmx.net
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include <fcntl.h>
#include <cstdlib>
#include <config.h>
#include <errno.h>
#include <signal.h>
#include "os/os.h"
#include "threadpool.h"
#define READEVENT 0
#define SENDEVENT 1
//#define DEBUG_MUTEX
#include "../event.h"
libhttppp::Event::Event(ServerSocket *serversocket) {
_ServerSocket=serversocket;
_ServerSocket->setnonblocking();
_ServerSocket->listenSocket();
_EventEndloop =true;
_Cpool= new ConnectionPool(_ServerSocket);
_Events = new struct kevent[(_ServerSocket->getMaxconnections())];
_WorkerPool = new ThreadPool;
_Mutex = new Mutex;
_firstConnectionContext=NULL;
_lastConnectionContext=NULL;
_firstWorkerContext=NULL;
_lastWorkerContext=NULL;
}
libhttppp::Event::~Event() {
delete _Cpool;
delete[] _Events;
delete _firstConnectionContext;
delete _WorkerPool;
delete _firstWorkerContext;
_lastWorkerContext=NULL;
_lastConnectionContext=NULL;
delete _Mutex;
}
void libhttppp::Event::CtrlHandler(int signum) {
_EventEndloop=false;
}
void libhttppp::Event::runEventloop() {
int srvssocket=_ServerSocket->getSocket();
int maxconnets=_ServerSocket->getMaxconnections();
struct kevent setEvent=(struct kevent) {
0
};
_Kq = kqueue();
EV_SET(&setEvent, srvssocket, EVFILT_READ , EV_ADD || EV_CLEAR , 0, 0, NULL);
if (kevent(_Kq, &setEvent, 1, NULL, 0, NULL) == -1)
_httpexception.Critical("runeventloop","can't create kqueue!");
signal(SIGPIPE, SIG_IGN);
SYSInfo sysinfo;
size_t thrs = sysinfo.getNumberOfProcessors();
for(size_t i=0; i<thrs; i++) {
WorkerContext *curwrkctx=addWorkerContext();
curwrkctx->_CurThread->Create(WorkerThread,curwrkctx);
}
for(WorkerContext *curth=_firstWorkerContext; curth; curth=curth->_nextWorkerContext) {
curth->_CurThread->Join();
}
}
void *libhttppp::Event::WorkerThread(void *wrkevent) {
HTTPException httpexception;
WorkerContext *wctx=(WorkerContext*)wrkevent;
Event *wevent=wctx->_CurEvent;
int srvssocket=wevent->_ServerSocket->getSocket();
int maxconnets=wevent->_ServerSocket->getMaxconnections();
SYSInfo sysinfo;
wctx->_CurThread->setPid(sysinfo.getPid());
struct kevent setEvent=(struct kevent) {
0
};
int nev = 0;
while(wevent->_EventEndloop) {
nev = kevent(wevent->_Kq, NULL, 0, wevent->_Events,maxconnets, NULL);
if(nev<0) {
if(errno== EINTR) {
continue;
} else {
httpexception.Critical("epoll wait failure");
throw httpexception;
}
}
for(int i=0; i<nev; i++) {
ConnectionContext *curct=NULL;
if(wevent->_Events[i].ident == (uintptr_t)srvssocket) {
try {
/*will create warning debug mode that normally because the check already connection
* with this socket if getconnection throw they will be create a new one
*/
wevent->addConnectionContext(&curct);
#ifdef DEBUG_MUTEX
httpexception.Note("runeventloop","Lock ConnectionMutex");
#endif
curct->_Mutex->lock();
ClientSocket *clientsocket=curct->_CurConnection->getClientSocket();
int fd=wevent->_ServerSocket->acceptEvent(clientsocket);
clientsocket->setnonblocking();
curct->_EventCounter=i;
if(fd>0) {
setEvent.fflags=0;
setEvent.filter=EVFILT_READ;
setEvent.flags=EV_ADD;
setEvent.udata=(void*) curct;
setEvent.ident=(uintptr_t)fd;
EV_SET(&setEvent, fd, EVFILT_READ, EV_ADD, 0, 0, (void*) curct);
if (kevent(wevent->_Kq, &setEvent, 1, NULL, 0, NULL) == -1) {
httpexception.Error("runeventloop","can't accep't in kqueue!");
} else {
wevent->ConnectEvent(curct->_CurConnection);
}
#ifdef DEBUG_MUTEX
httpexception.Note("runeventloop","Unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
} else {
#ifdef DEBUG_MUTEX
httpexception.Note("runeventloop","Unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
wevent->delConnectionContext(curct,NULL);
}
} catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
httpexception.Note("runeventloop","Unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
wevent->delConnectionContext(curct,NULL);
if(e.isCritical())
throw e;
}
} else {
curct=(ConnectionContext*)wevent->_Events[i].udata;
switch(wevent->_Events[i].filter) {
case EVFILT_READ: {
#ifdef DEBUG_MUTEX
httpexception.Note("ReadEvent","lock ConnectionMutex");
#endif
curct->_Mutex->lock();
ClientSocket *clientsocket=curct->_CurConnection->getClientSocket();
int fd=clientsocket->getSocket();
try {
char buf[BLOCKSIZE];
int rcvsize=0;
rcvsize=wevent->_ServerSocket->recvData(clientsocket,buf,BLOCKSIZE);
switch(rcvsize) {
case -1: {
setEvent.filter=EVFILT_READ;
setEvent.flags=EV_MOD;
EV_SET(&setEvent, fd, EVFILT_READ, EV_MOD, 0, 0, (void*) curct);
if (kevent(wevent->_Kq, &setEvent, 1, NULL, 0, NULL) == -1) {
httpexception.Error("runeventloop","can't mod kqueue!");
}
case 0: {
if(curct->_CurConnection->getSendSize()!=0) {
setEvent.filter=EVFILT_WRITE;
setEvent.flags=EV_MOD;
EV_SET(&setEvent, fd, EVFILT_WRITE, EV_MOD, 0, 0, (void*) curct);
if (kevent(wevent->_Kq, &setEvent, 1, NULL, 0, NULL) == -1) {
httpexception.Error("runeventloop","can't mod kqueue!");
} else {
goto ClOSECONNECTION;
}
}
default: {
curct->_CurConnection->addRecvQueue(buf,rcvsize);
wevent->RequestEvent(curct->_CurConnection);
setEvent.filter=EVFILT_READ;
setEvent.flags=EV_MOD;
EV_SET(&setEvent, fd, EVFILT_READ, EV_MOD, 0, 0, (void*) curct);
if (kevent(wevent->_Kq, &setEvent, 1, NULL, 0, NULL) == -1) {
httpexception.Error("runeventloop","can't mod kqueue!");
}
}
#ifdef DEBUG_MUTEX
httpexception.Note("ReadEvent","unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
}
catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
httpexception.Note("ReadEvent","unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
if(e.isCritical()) {
throw e;
}
if(e.isError()) {
curct->_CurConnection->cleanRecvData();
goto CLOSECONNECTION;
}
}
}
case EVFILT_WRITE: {
#ifdef DEBUG_MUTEX
httpexception.Note("WriteEvent","lock ConnectionMutex");
#endif
curct->_Mutex->lock();
Connection *con=curct->_CurConnection;
try {
ssize_t sended=0;
while(con->getSendData()) {
sended=wevent->_ServerSocket->sendData(con->getClientSocket(),
(void*)con->getSendData()->getData(),
con->getSendData()->getDataSize());
if(sended>0)
con->resizeSendQueue(sended);
}
wevent->ResponseEvent(con);
} catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
httpexception.Note("WriteEvent","unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
goto CLOSECONNECTION;
}
#ifdef DEBUG_MUTEX
httpexception.Note("WriteEvent","unlock ConnectionMutex");
#endif
if(curct)
curct->_Mutex->unlock();
}
}
if (wevent->_Events[i].flags & EV_ERROR) {
CLOSECONNECTION:
#ifdef DEBUG_MUTEX
httpexception.Note("CloseEvent","ConnectionMutex");
#endif
curct->_Mutex->lock();
Connection *con=(Connection*)curct->_CurConnection;
wevent->DisconnectEvent(con);
try {
EV_SET(&setEvent,con->getClientSocket()->getSocket(),
wevent->_Events[curct->_EventCounter].filter,
EV_DELETE, 0, 0, NULL);
if (kevent(wevent->_Kq,&setEvent, 1, NULL, 0, NULL) == -1)
httpexception.Error("Connection can't delete from kqueue");
#ifdef DEBUG_MUTEX
httpexception.Note("CloseEvent","unlock ConnectionMutex");
#endif
curct->_Mutex->unlock();
wevent->delConnectionContext(curct,NULL);
curct=NULL;
httpexception.Note("Connection shutdown!");
} catch(HTTPException &e) {
#ifdef DEBUG_MUTEX
httpexception.Note("CloseEvent","unlock ConnectionMutex");
#endif
if(curct)
curct->_Mutex->unlock();
httpexception.Note("Can't do Connection shutdown!");
}
}
}
}
signal(SIGINT, CtrlHandler);
}
return NULL;
}
<|endoftext|> |
<commit_before>//===-- LineEditor.cpp - line editor --------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/LineEditor/LineEditor.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Config/config.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <stdio.h>
#ifdef HAVE_LIBEDIT
#include <histedit.h>
#endif
using namespace llvm;
std::string LineEditor::getDefaultHistoryPath(StringRef ProgName) {
SmallString<32> Path;
if (sys::path::home_directory(Path)) {
sys::path::append(Path, "." + ProgName + "-history");
return Path.str();
}
return std::string();
}
LineEditor::CompleterConcept::~CompleterConcept() {}
LineEditor::ListCompleterConcept::~ListCompleterConcept() {}
std::string LineEditor::ListCompleterConcept::getCommonPrefix(
const std::vector<Completion> &Comps) {
assert(!Comps.empty());
std::string CommonPrefix = Comps[0].TypedText;
for (std::vector<Completion>::const_iterator I = Comps.begin() + 1,
E = Comps.end();
I != E; ++I) {
size_t Len = std::min(CommonPrefix.size(), I->TypedText.size());
size_t CommonLen = 0;
for (; CommonLen != Len; ++CommonLen) {
if (CommonPrefix[CommonLen] != I->TypedText[CommonLen])
break;
}
CommonPrefix.resize(CommonLen);
}
return CommonPrefix;
}
LineEditor::CompletionAction
LineEditor::ListCompleterConcept::complete(StringRef Buffer, size_t Pos) const {
CompletionAction Action;
std::vector<Completion> Comps = getCompletions(Buffer, Pos);
if (Comps.empty()) {
Action.Kind = CompletionAction::AK_ShowCompletions;
return Action;
}
std::string CommonPrefix = getCommonPrefix(Comps);
// If the common prefix is non-empty we can simply insert it. If there is a
// single completion, this will insert the full completion. If there is more
// than one, this might be enough information to jog the user's memory but if
// not the user can also hit tab again to see the completions because the
// common prefix will then be empty.
if (CommonPrefix.empty()) {
Action.Kind = CompletionAction::AK_ShowCompletions;
for (std::vector<Completion>::iterator I = Comps.begin(), E = Comps.end();
I != E; ++I)
Action.Completions.push_back(I->DisplayText);
} else {
Action.Kind = CompletionAction::AK_Insert;
Action.Text = CommonPrefix;
}
return Action;
}
LineEditor::CompletionAction LineEditor::getCompletionAction(StringRef Buffer,
size_t Pos) const {
if (!Completer) {
CompletionAction Action;
Action.Kind = CompletionAction::AK_ShowCompletions;
return Action;
}
return Completer->complete(Buffer, Pos);
}
#ifdef HAVE_LIBEDIT
// libedit-based implementation.
struct LineEditor::InternalData {
LineEditor *LE;
History *Hist;
EditLine *EL;
unsigned PrevCount;
std::string ContinuationOutput;
};
static const char *ElGetPromptFn(EditLine *EL) {
LineEditor::InternalData *Data;
if (el_get(EL, EL_CLIENTDATA, &Data) == 0)
return Data->LE->getPrompt().c_str();
return "> ";
}
// Handles tab completion.
//
// This function is really horrible. But since the alternative is to get into
// the line editor business, here we are.
static unsigned char ElCompletionFn(EditLine *EL, int ch) {
LineEditor::InternalData *Data;
if (el_get(EL, EL_CLIENTDATA, &Data) == 0) {
if (!Data->ContinuationOutput.empty()) {
// This is the continuation of the AK_ShowCompletions branch below.
FILE *Out;
if (::el_get(EL, EL_GETFP, 1, &Out) != 0)
return CC_ERROR;
// Print the required output (see below).
::fwrite(Data->ContinuationOutput.c_str(),
Data->ContinuationOutput.size(), 1, Out);
// Push a sequence of Ctrl-B characters to move the cursor back to its
// original position.
std::string Prevs(Data->PrevCount, '\02');
::el_push(EL, (char *)Prevs.c_str());
Data->ContinuationOutput.clear();
return CC_REFRESH;
}
const LineInfo *LI = ::el_line(EL);
LineEditor::CompletionAction Action = Data->LE->getCompletionAction(
StringRef(LI->buffer, LI->lastchar - LI->buffer),
LI->cursor - LI->buffer);
switch (Action.Kind) {
case LineEditor::CompletionAction::AK_Insert:
::el_insertstr(EL, Action.Text.c_str());
return CC_REFRESH;
case LineEditor::CompletionAction::AK_ShowCompletions:
if (Action.Completions.empty()) {
return CC_REFRESH_BEEP;
} else {
// Push a Ctrl-E and a tab. The Ctrl-E causes libedit to move the cursor
// to the end of the line, so that when we emit a newline we will be on
// a new blank line. The tab causes libedit to call this function again
// after moving the cursor. There doesn't seem to be anything we can do
// from here to cause libedit to move the cursor immediately. This will
// break horribly if the user has rebound their keys, so for now we do
// not permit user rebinding.
::el_push(EL, (char *)"\05\t");
// This assembles the output for the continuation block above.
raw_string_ostream OS(Data->ContinuationOutput);
// Move cursor to a blank line.
OS << "\n";
// Emit the completions.
for (std::vector<std::string>::iterator I = Action.Completions.begin(),
E = Action.Completions.end();
I != E; ++I) {
OS << *I << "\n";
}
// Fool libedit into thinking nothing has changed. Reprint its prompt
// and the user input. Note that the cursor will remain at the end of
// the line after this.
OS << Data->LE->getPrompt()
<< StringRef(LI->buffer, LI->lastchar - LI->buffer);
// This is the number of characters we need to tell libedit to go back:
// the distance between end of line and the original cursor position.
Data->PrevCount = LI->lastchar - LI->cursor;
return CC_REFRESH;
}
}
} else {
return CC_ERROR;
}
}
LineEditor::LineEditor(StringRef ProgName, StringRef HistoryPath, FILE *In,
FILE *Out, FILE *Err)
: Prompt((ProgName + "> ").str()), HistoryPath(HistoryPath),
Data(new InternalData) {
if (HistoryPath.empty())
this->HistoryPath = getDefaultHistoryPath(ProgName);
Data->LE = this;
Data->Hist = ::history_init();
assert(Data->Hist);
Data->EL = ::el_init(ProgName.str().c_str(), In, Out, Err);
assert(Data->EL);
::el_set(Data->EL, EL_PROMPT, ElGetPromptFn);
::el_set(Data->EL, EL_EDITOR, "emacs");
::el_set(Data->EL, EL_HIST, history, Data->Hist);
::el_set(Data->EL, EL_ADDFN, "tab_complete", "Tab completion function",
ElCompletionFn);
::el_set(Data->EL, EL_BIND, "\t", "tab_complete", NULL);
::el_set(Data->EL, EL_BIND, "^r", "em-inc-search-prev",
NULL); // Cycle through backwards search, entering string
::el_set(Data->EL, EL_BIND, "^w", "ed-delete-prev-word",
NULL); // Delete previous word, behave like bash does.
::el_set(Data->EL, EL_BIND, "\033[3~", "ed-delete-next-char",
NULL); // Fix the delete key.
::el_set(Data->EL, EL_CLIENTDATA, Data.get());
HistEvent HE;
::history(Data->Hist, &HE, H_SETSIZE, 800);
::history(Data->Hist, &HE, H_SETUNIQUE, 1);
loadHistory();
}
LineEditor::~LineEditor() {
saveHistory();
FILE *Out;
if (::el_get(Data->EL, EL_GETFP, 1, &Out) != 0)
Out = 0;
::history_end(Data->Hist);
::el_end(Data->EL);
if (Out)
::fwrite("\n", 1, 1, Out);
}
void LineEditor::saveHistory() {
if (!HistoryPath.empty()) {
HistEvent HE;
::history(Data->Hist, &HE, H_SAVE, HistoryPath.c_str());
}
}
void LineEditor::loadHistory() {
if (!HistoryPath.empty()) {
HistEvent HE;
::history(Data->Hist, &HE, H_LOAD, HistoryPath.c_str());
}
}
Optional<std::string> LineEditor::readLine() const {
// Call el_gets to prompt the user and read the user's input.
int LineLen = 0;
const char *Line = ::el_gets(Data->EL, &LineLen);
// Either of these may mean end-of-file.
if (!Line || LineLen == 0)
return Optional<std::string>();
// Strip any newlines off the end of the string.
while (LineLen > 0 &&
(Line[LineLen - 1] == '\n' || Line[LineLen - 1] == '\r'))
--LineLen;
HistEvent HE;
if (LineLen > 0)
::history(Data->Hist, &HE, H_ENTER, Line);
return std::string(Line, LineLen);
}
#else
// Simple fgets-based implementation.
struct LineEditor::InternalData {
FILE *In;
FILE *Out;
};
LineEditor::LineEditor(StringRef ProgName, StringRef HistoryPath, FILE *In,
FILE *Out, FILE *Err)
: Prompt((ProgName + "> ").str()), Data(new InternalData) {
Data->In = In;
Data->Out = Out;
}
LineEditor::~LineEditor() {
::fwrite("\n", 1, 1, Data->Out);
}
void LineEditor::saveHistory() {}
void LineEditor::loadHistory() {}
Optional<std::string> LineEditor::readLine() const {
::fprintf(Data->Out, "%s", Prompt.c_str());
std::string Line;
do {
char Buf[64];
char *Res = ::fgets(Buf, sizeof(Buf), Data->In);
if (!Res) {
if (Line.empty())
return Optional<std::string>();
else
return Line;
}
Line.append(Buf);
} while (Line.empty() ||
(Line[Line.size() - 1] != '\n' && Line[Line.size() - 1] != '\r'));
while (!Line.empty() &&
(Line[Line.size() - 1] == '\n' || Line[Line.size() - 1] == '\r'))
Line.resize(Line.size() - 1);
return Line;
}
#endif
<commit_msg>Silence GCC warnings.<commit_after>//===-- LineEditor.cpp - line editor --------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/LineEditor/LineEditor.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Config/config.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <stdio.h>
#ifdef HAVE_LIBEDIT
#include <histedit.h>
#endif
using namespace llvm;
std::string LineEditor::getDefaultHistoryPath(StringRef ProgName) {
SmallString<32> Path;
if (sys::path::home_directory(Path)) {
sys::path::append(Path, "." + ProgName + "-history");
return Path.str();
}
return std::string();
}
LineEditor::CompleterConcept::~CompleterConcept() {}
LineEditor::ListCompleterConcept::~ListCompleterConcept() {}
std::string LineEditor::ListCompleterConcept::getCommonPrefix(
const std::vector<Completion> &Comps) {
assert(!Comps.empty());
std::string CommonPrefix = Comps[0].TypedText;
for (std::vector<Completion>::const_iterator I = Comps.begin() + 1,
E = Comps.end();
I != E; ++I) {
size_t Len = std::min(CommonPrefix.size(), I->TypedText.size());
size_t CommonLen = 0;
for (; CommonLen != Len; ++CommonLen) {
if (CommonPrefix[CommonLen] != I->TypedText[CommonLen])
break;
}
CommonPrefix.resize(CommonLen);
}
return CommonPrefix;
}
LineEditor::CompletionAction
LineEditor::ListCompleterConcept::complete(StringRef Buffer, size_t Pos) const {
CompletionAction Action;
std::vector<Completion> Comps = getCompletions(Buffer, Pos);
if (Comps.empty()) {
Action.Kind = CompletionAction::AK_ShowCompletions;
return Action;
}
std::string CommonPrefix = getCommonPrefix(Comps);
// If the common prefix is non-empty we can simply insert it. If there is a
// single completion, this will insert the full completion. If there is more
// than one, this might be enough information to jog the user's memory but if
// not the user can also hit tab again to see the completions because the
// common prefix will then be empty.
if (CommonPrefix.empty()) {
Action.Kind = CompletionAction::AK_ShowCompletions;
for (std::vector<Completion>::iterator I = Comps.begin(), E = Comps.end();
I != E; ++I)
Action.Completions.push_back(I->DisplayText);
} else {
Action.Kind = CompletionAction::AK_Insert;
Action.Text = CommonPrefix;
}
return Action;
}
LineEditor::CompletionAction LineEditor::getCompletionAction(StringRef Buffer,
size_t Pos) const {
if (!Completer) {
CompletionAction Action;
Action.Kind = CompletionAction::AK_ShowCompletions;
return Action;
}
return Completer->complete(Buffer, Pos);
}
#ifdef HAVE_LIBEDIT
// libedit-based implementation.
struct LineEditor::InternalData {
LineEditor *LE;
History *Hist;
EditLine *EL;
unsigned PrevCount;
std::string ContinuationOutput;
};
static const char *ElGetPromptFn(EditLine *EL) {
LineEditor::InternalData *Data;
if (el_get(EL, EL_CLIENTDATA, &Data) == 0)
return Data->LE->getPrompt().c_str();
return "> ";
}
// Handles tab completion.
//
// This function is really horrible. But since the alternative is to get into
// the line editor business, here we are.
static unsigned char ElCompletionFn(EditLine *EL, int ch) {
LineEditor::InternalData *Data;
if (el_get(EL, EL_CLIENTDATA, &Data) == 0) {
if (!Data->ContinuationOutput.empty()) {
// This is the continuation of the AK_ShowCompletions branch below.
FILE *Out;
if (::el_get(EL, EL_GETFP, 1, &Out) != 0)
return CC_ERROR;
// Print the required output (see below).
::fwrite(Data->ContinuationOutput.c_str(),
Data->ContinuationOutput.size(), 1, Out);
// Push a sequence of Ctrl-B characters to move the cursor back to its
// original position.
std::string Prevs(Data->PrevCount, '\02');
::el_push(EL, const_cast<char *>(Prevs.c_str()));
Data->ContinuationOutput.clear();
return CC_REFRESH;
}
const LineInfo *LI = ::el_line(EL);
LineEditor::CompletionAction Action = Data->LE->getCompletionAction(
StringRef(LI->buffer, LI->lastchar - LI->buffer),
LI->cursor - LI->buffer);
switch (Action.Kind) {
case LineEditor::CompletionAction::AK_Insert:
::el_insertstr(EL, Action.Text.c_str());
return CC_REFRESH;
case LineEditor::CompletionAction::AK_ShowCompletions:
if (Action.Completions.empty()) {
return CC_REFRESH_BEEP;
} else {
// Push a Ctrl-E and a tab. The Ctrl-E causes libedit to move the cursor
// to the end of the line, so that when we emit a newline we will be on
// a new blank line. The tab causes libedit to call this function again
// after moving the cursor. There doesn't seem to be anything we can do
// from here to cause libedit to move the cursor immediately. This will
// break horribly if the user has rebound their keys, so for now we do
// not permit user rebinding.
::el_push(EL, const_cast<char *>("\05\t"));
// This assembles the output for the continuation block above.
raw_string_ostream OS(Data->ContinuationOutput);
// Move cursor to a blank line.
OS << "\n";
// Emit the completions.
for (std::vector<std::string>::iterator I = Action.Completions.begin(),
E = Action.Completions.end();
I != E; ++I) {
OS << *I << "\n";
}
// Fool libedit into thinking nothing has changed. Reprint its prompt
// and the user input. Note that the cursor will remain at the end of
// the line after this.
OS << Data->LE->getPrompt()
<< StringRef(LI->buffer, LI->lastchar - LI->buffer);
// This is the number of characters we need to tell libedit to go back:
// the distance between end of line and the original cursor position.
Data->PrevCount = LI->lastchar - LI->cursor;
return CC_REFRESH;
}
}
}
return CC_ERROR;
}
LineEditor::LineEditor(StringRef ProgName, StringRef HistoryPath, FILE *In,
FILE *Out, FILE *Err)
: Prompt((ProgName + "> ").str()), HistoryPath(HistoryPath),
Data(new InternalData) {
if (HistoryPath.empty())
this->HistoryPath = getDefaultHistoryPath(ProgName);
Data->LE = this;
Data->Hist = ::history_init();
assert(Data->Hist);
Data->EL = ::el_init(ProgName.str().c_str(), In, Out, Err);
assert(Data->EL);
::el_set(Data->EL, EL_PROMPT, ElGetPromptFn);
::el_set(Data->EL, EL_EDITOR, "emacs");
::el_set(Data->EL, EL_HIST, history, Data->Hist);
::el_set(Data->EL, EL_ADDFN, "tab_complete", "Tab completion function",
ElCompletionFn);
::el_set(Data->EL, EL_BIND, "\t", "tab_complete", NULL);
::el_set(Data->EL, EL_BIND, "^r", "em-inc-search-prev",
NULL); // Cycle through backwards search, entering string
::el_set(Data->EL, EL_BIND, "^w", "ed-delete-prev-word",
NULL); // Delete previous word, behave like bash does.
::el_set(Data->EL, EL_BIND, "\033[3~", "ed-delete-next-char",
NULL); // Fix the delete key.
::el_set(Data->EL, EL_CLIENTDATA, Data.get());
HistEvent HE;
::history(Data->Hist, &HE, H_SETSIZE, 800);
::history(Data->Hist, &HE, H_SETUNIQUE, 1);
loadHistory();
}
LineEditor::~LineEditor() {
saveHistory();
FILE *Out;
if (::el_get(Data->EL, EL_GETFP, 1, &Out) != 0)
Out = 0;
::history_end(Data->Hist);
::el_end(Data->EL);
if (Out)
::fwrite("\n", 1, 1, Out);
}
void LineEditor::saveHistory() {
if (!HistoryPath.empty()) {
HistEvent HE;
::history(Data->Hist, &HE, H_SAVE, HistoryPath.c_str());
}
}
void LineEditor::loadHistory() {
if (!HistoryPath.empty()) {
HistEvent HE;
::history(Data->Hist, &HE, H_LOAD, HistoryPath.c_str());
}
}
Optional<std::string> LineEditor::readLine() const {
// Call el_gets to prompt the user and read the user's input.
int LineLen = 0;
const char *Line = ::el_gets(Data->EL, &LineLen);
// Either of these may mean end-of-file.
if (!Line || LineLen == 0)
return Optional<std::string>();
// Strip any newlines off the end of the string.
while (LineLen > 0 &&
(Line[LineLen - 1] == '\n' || Line[LineLen - 1] == '\r'))
--LineLen;
HistEvent HE;
if (LineLen > 0)
::history(Data->Hist, &HE, H_ENTER, Line);
return std::string(Line, LineLen);
}
#else
// Simple fgets-based implementation.
struct LineEditor::InternalData {
FILE *In;
FILE *Out;
};
LineEditor::LineEditor(StringRef ProgName, StringRef HistoryPath, FILE *In,
FILE *Out, FILE *Err)
: Prompt((ProgName + "> ").str()), Data(new InternalData) {
Data->In = In;
Data->Out = Out;
}
LineEditor::~LineEditor() {
::fwrite("\n", 1, 1, Data->Out);
}
void LineEditor::saveHistory() {}
void LineEditor::loadHistory() {}
Optional<std::string> LineEditor::readLine() const {
::fprintf(Data->Out, "%s", Prompt.c_str());
std::string Line;
do {
char Buf[64];
char *Res = ::fgets(Buf, sizeof(Buf), Data->In);
if (!Res) {
if (Line.empty())
return Optional<std::string>();
else
return Line;
}
Line.append(Buf);
} while (Line.empty() ||
(Line[Line.size() - 1] != '\n' && Line[Line.size() - 1] != '\r'));
while (!Line.empty() &&
(Line[Line.size() - 1] == '\n' || Line[Line.size() - 1] == '\r'))
Line.resize(Line.size() - 1);
return Line;
}
#endif
<|endoftext|> |
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
#ifndef EXTPROC_POOL_HPP_
#define EXTPROC_POOL_HPP_
#include <sys/types.h> // pid_t
#include "errors.hpp"
#include "concurrency/one_per_thread.hpp"
#include "concurrency/semaphore.hpp"
#include "concurrency/signal.hpp"
#include "containers/archive/interruptible_stream.hpp"
#include "containers/archive/socket_stream.hpp"
#include "containers/intrusive_list.hpp"
#include "extproc/job.hpp"
#include "extproc/spawner.hpp"
namespace extproc {
class job_handle_t;
class pool_t;
// Use this to create one process pool per thread, and access the appropriate
// one (via `get()`).
class pool_group_t {
friend class pool_t;
public:
static const int DEFAULT_MIN_WORKERS = 2;
static const int DEFAULT_MAX_WORKERS = 2;
struct config_t {
config_t()
: min_workers(DEFAULT_MIN_WORKERS), max_workers(DEFAULT_MAX_WORKERS) {}
int min_workers; // >= 0
int max_workers; // >= min_workers, > 0
};
static const config_t DEFAULTS;
pool_group_t(spawner_info_t *info, const config_t &config);
pool_t *get() { return pool_maker_.get(); }
private:
spawner_t spawner_;
config_t config_;
one_per_thread_t<pool_t> pool_maker_;
};
// A per-thread worker pool.
class pool_t : public home_thread_mixin_debug_only_t {
public:
explicit pool_t(pool_group_t *group);
~pool_t();
private:
friend class job_handle_t;
pool_group_t::config_t *config() { return &group_->config_; }
spawner_t *spawner() { return &group_->spawner_; }
// A worker process.
class worker_t :
public intrusive_list_node_t<worker_t>,
public unix_socket_stream_t
{
friend class job_handle_t;
public:
worker_t(pool_t *pool, pid_t pid, scoped_fd_t *fd);
~worker_t();
// Called when we get an error on a worker process socket, which usually
// indicates the worker process' death.
void on_error();
// Inherited from unix_socket_stream_t. Called when epoll finds an error
// condition on our socket. Calls on_error().
virtual void do_on_event(int events);
private:
friend class pool_t;
pool_t *const pool_;
const pid_t pid_;
bool attached_;
DISABLE_COPYING(worker_t);
};
typedef intrusive_list_t<worker_t> workers_t;
private:
// Checks & repairs invariants, namely:
// - num_workers() >= config()->min_workers
void repair_invariants();
// Connects us to a worker. Private; used only by job_handle_t::spawn().
worker_t *acquire_worker();
// Called by job_handle_t to indicate the job has finished or errored.
void release_worker(worker_t *worker) THROWS_NOTHING;
// Called by job_handle_t to interrupt a running job.
void interrupt_worker(worker_t *worker) THROWS_NOTHING;
// Detaches the worker from the pool, sends it SIGKILL, and ignores further
// errors from it (ie. on_event will not call on_error, and hence will not
// crash). Does not block.
//
// This is used by the interruptor-signal logic in
// job_handle_t::{read,write}_interruptible(), where interrupt_worker()
// cannot be used because it destroys the worker.
//
// It is the caller's responsibility to call cleanup_detached_worker() at
// some point in the near future.
void detach_worker(worker_t *worker);
// Cleans up after a detached worker. Destroys the worker. May block.
void cleanup_detached_worker(worker_t *worker);
void spawn_workers(int n);
void end_worker(workers_t *list, worker_t *worker);
int num_workers() {
return idle_workers_.size() + busy_workers_.size() + num_spawning_workers_;
}
private:
pool_group_t *group_;
// Worker processes.
workers_t idle_workers_, busy_workers_;
// Count of the number of workers in the process of being spawned. Necessary
// in order to maintain (min_workers, max_workers) bounds without race
// conditions.
int num_spawning_workers_;
// Used to signify that you're using a worker. In particular, lets us block
// for a worker to become available when we already have
// config_->max_workers workers running.
semaphore_t worker_semaphore_;
};
// A handle to a running job.
class job_handle_t : public interruptible_read_stream_t, public interruptible_write_stream_t {
public:
// When constructed, job handles are "disconnected", not associated with a
// job. They are connected by pool_t::spawn_job().
job_handle_t();
// You MUST call release() to finish a job normally, and you SHOULD call
// interrupt() explicitly to interrupt a job (or signal the interruptor
// during {read,write}_interruptible()).
//
// However, as a convenience in the case of exception-raising code, if the
// handle is connected, the destructor will log a warning and interrupt the
// job.
virtual ~job_handle_t();
bool connected() { return NULL != worker_; }
// Begins running `job` on `pool`. Must be disconnected beforehand. On
// success, returns 0 and connects us to the spawned job. Returns -1 on
// error.
int begin(pool_t *pool, const job_t &job);
// Indicates the job has either finished normally or experienced an I/O
// error; disconnects the job handle.
void release() THROWS_NOTHING;
// Forcibly interrupts a running job; disconnects the job handle.
//
// MAY NOT be called concurrently with any I/O methods. Instead, pass a
// signal to {read,write}_interruptible().
void interrupt() THROWS_NOTHING;
// On either read or write error or interruption, the job handle becomes
// disconnected and must not be used.
virtual MUST_USE int64_t read_interruptible(void *p, int64_t n, signal_t *interruptor);
virtual int64_t write_interruptible(const void *p, int64_t n, signal_t *interruptor);
private:
friend class pool_t;
friend class interruptor_wrapper_t;
void check_attached();
class interruptor_wrapper_t : public signal_t, public signal_t::subscription_t {
public:
interruptor_wrapper_t(job_handle_t *handle, signal_t *signal);
virtual void run() THROWS_NOTHING;
job_handle_t *handle_;
};
pool_t::worker_t *worker_;
DISABLE_COPYING(job_handle_t);
};
} // namespace extproc
#endif // EXTPROC_POOL_HPP_
<commit_msg>Updated copyright notice in extproc/pool.hpp (and only had to recompile a few files).<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef EXTPROC_POOL_HPP_
#define EXTPROC_POOL_HPP_
#include <sys/types.h> // pid_t
#include "errors.hpp"
#include "concurrency/one_per_thread.hpp"
#include "concurrency/semaphore.hpp"
#include "concurrency/signal.hpp"
#include "containers/archive/interruptible_stream.hpp"
#include "containers/archive/socket_stream.hpp"
#include "containers/intrusive_list.hpp"
#include "extproc/job.hpp"
#include "extproc/spawner.hpp"
namespace extproc {
class job_handle_t;
class pool_t;
// Use this to create one process pool per thread, and access the appropriate
// one (via `get()`).
class pool_group_t {
friend class pool_t;
public:
static const int DEFAULT_MIN_WORKERS = 2;
static const int DEFAULT_MAX_WORKERS = 2;
struct config_t {
config_t()
: min_workers(DEFAULT_MIN_WORKERS), max_workers(DEFAULT_MAX_WORKERS) {}
int min_workers; // >= 0
int max_workers; // >= min_workers, > 0
};
static const config_t DEFAULTS;
pool_group_t(spawner_info_t *info, const config_t &config);
pool_t *get() { return pool_maker_.get(); }
private:
spawner_t spawner_;
config_t config_;
one_per_thread_t<pool_t> pool_maker_;
};
// A per-thread worker pool.
class pool_t : public home_thread_mixin_debug_only_t {
public:
explicit pool_t(pool_group_t *group);
~pool_t();
private:
friend class job_handle_t;
pool_group_t::config_t *config() { return &group_->config_; }
spawner_t *spawner() { return &group_->spawner_; }
// A worker process.
class worker_t :
public intrusive_list_node_t<worker_t>,
public unix_socket_stream_t
{
friend class job_handle_t;
public:
worker_t(pool_t *pool, pid_t pid, scoped_fd_t *fd);
~worker_t();
// Called when we get an error on a worker process socket, which usually
// indicates the worker process' death.
void on_error();
// Inherited from unix_socket_stream_t. Called when epoll finds an error
// condition on our socket. Calls on_error().
virtual void do_on_event(int events);
private:
friend class pool_t;
pool_t *const pool_;
const pid_t pid_;
bool attached_;
DISABLE_COPYING(worker_t);
};
typedef intrusive_list_t<worker_t> workers_t;
private:
// Checks & repairs invariants, namely:
// - num_workers() >= config()->min_workers
void repair_invariants();
// Connects us to a worker. Private; used only by job_handle_t::spawn().
worker_t *acquire_worker();
// Called by job_handle_t to indicate the job has finished or errored.
void release_worker(worker_t *worker) THROWS_NOTHING;
// Called by job_handle_t to interrupt a running job.
void interrupt_worker(worker_t *worker) THROWS_NOTHING;
// Detaches the worker from the pool, sends it SIGKILL, and ignores further
// errors from it (ie. on_event will not call on_error, and hence will not
// crash). Does not block.
//
// This is used by the interruptor-signal logic in
// job_handle_t::{read,write}_interruptible(), where interrupt_worker()
// cannot be used because it destroys the worker.
//
// It is the caller's responsibility to call cleanup_detached_worker() at
// some point in the near future.
void detach_worker(worker_t *worker);
// Cleans up after a detached worker. Destroys the worker. May block.
void cleanup_detached_worker(worker_t *worker);
void spawn_workers(int n);
void end_worker(workers_t *list, worker_t *worker);
int num_workers() {
return idle_workers_.size() + busy_workers_.size() + num_spawning_workers_;
}
private:
pool_group_t *group_;
// Worker processes.
workers_t idle_workers_, busy_workers_;
// Count of the number of workers in the process of being spawned. Necessary
// in order to maintain (min_workers, max_workers) bounds without race
// conditions.
int num_spawning_workers_;
// Used to signify that you're using a worker. In particular, lets us block
// for a worker to become available when we already have
// config_->max_workers workers running.
semaphore_t worker_semaphore_;
};
// A handle to a running job.
class job_handle_t : public interruptible_read_stream_t, public interruptible_write_stream_t {
public:
// When constructed, job handles are "disconnected", not associated with a
// job. They are connected by pool_t::spawn_job().
job_handle_t();
// You MUST call release() to finish a job normally, and you SHOULD call
// interrupt() explicitly to interrupt a job (or signal the interruptor
// during {read,write}_interruptible()).
//
// However, as a convenience in the case of exception-raising code, if the
// handle is connected, the destructor will log a warning and interrupt the
// job.
virtual ~job_handle_t();
bool connected() { return NULL != worker_; }
// Begins running `job` on `pool`. Must be disconnected beforehand. On
// success, returns 0 and connects us to the spawned job. Returns -1 on
// error.
int begin(pool_t *pool, const job_t &job);
// Indicates the job has either finished normally or experienced an I/O
// error; disconnects the job handle.
void release() THROWS_NOTHING;
// Forcibly interrupts a running job; disconnects the job handle.
//
// MAY NOT be called concurrently with any I/O methods. Instead, pass a
// signal to {read,write}_interruptible().
void interrupt() THROWS_NOTHING;
// On either read or write error or interruption, the job handle becomes
// disconnected and must not be used.
virtual MUST_USE int64_t read_interruptible(void *p, int64_t n, signal_t *interruptor);
virtual int64_t write_interruptible(const void *p, int64_t n, signal_t *interruptor);
private:
friend class pool_t;
friend class interruptor_wrapper_t;
void check_attached();
class interruptor_wrapper_t : public signal_t, public signal_t::subscription_t {
public:
interruptor_wrapper_t(job_handle_t *handle, signal_t *signal);
virtual void run() THROWS_NOTHING;
job_handle_t *handle_;
};
pool_t::worker_t *worker_;
DISABLE_COPYING(job_handle_t);
};
} // namespace extproc
#endif // EXTPROC_POOL_HPP_
<|endoftext|> |
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/mlir/lite/tf_tfl_passes.h"
#include "mlir/IR/Attributes.h" // from @llvm-project
#include "mlir/IR/Module.h" // from @llvm-project
#include "mlir/Pass/Pass.h" // from @llvm-project
#include "mlir/Pass/PassManager.h" // from @llvm-project
#include "mlir/Transforms/Passes.h" // from @llvm-project
#include "tensorflow/compiler/mlir/lite/quantization/quantization_config.h"
#include "tensorflow/compiler/mlir/lite/quantization/quantization_passes.h"
#include "tensorflow/compiler/mlir/lite/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/decode_constant.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/tf_mlir_translate.h"
namespace mlir {
/// Create a pass to convert from the TFExecutor to the TF control dialect.
std::unique_ptr<OpPassBase<FuncOp>>
CreateTFExecutorToControlDialectConversion();
} // namespace mlir
namespace tensorflow {
void AddQuantizationPasses(const mlir::TFL::QuantizationSpecs& quant_specs,
mlir::OpPassManager* pass_manager) {
pass_manager->addPass(mlir::TFL::CreatePrepareQuantizePass(quant_specs));
pass_manager->addPass(mlir::TFL::CreateQuantizePass());
bool emit_quant_adaptor_ops =
quant_specs.inference_type != quant_specs.inference_input_type;
pass_manager->addPass(
mlir::TFL::CreatePostQuantizePass(emit_quant_adaptor_ops));
if (quant_specs.default_ranges.first.hasValue() ||
quant_specs.default_ranges.second.hasValue()) {
pass_manager->addPass(mlir::TFL::CreateDefaultQuantParamsPass(
quant_specs.default_ranges.first.getValueOr(0.0),
quant_specs.default_ranges.second.getValueOr(0.0)));
pass_manager->addPass(mlir::TFL::CreateQuantizePass());
pass_manager->addPass(
mlir::TFL::CreatePostQuantizePass(emit_quant_adaptor_ops));
}
}
void AddTFToTFLConversionPasses(const mlir::TFL::PassConfig& pass_config,
mlir::OpPassManager* pass_manager) {
pass_manager->addPass(mlir::tf_executor::CreateSwitchFoldPass());
if (pass_config.skip_control_dialect) {
// Merge islands.
pass_manager->addPass(
mlir::tf_executor::CreateTFExecutorIslandCoarseningPass());
// Assuming island coarsening above results in a graph with a single island,
// a canonicalization can be ran to hoist the ops of the single island out.
pass_manager->addPass(mlir::createCanonicalizerPass());
if (pass_config.form_clusters)
pass_manager->addPass(mlir::TFDevice::CreateClusterFormationPass());
} else {
pass_manager->addPass(mlir::CreateTFExecutorToControlDialectConversion());
pass_manager->addPass(mlir::TFControlFlow::CreateRaiseTFControlFlowPass());
}
if (!pass_config.quant_specs.serialized_quant_stats.empty()) {
pass_manager->addPass(
mlir::quant::CreateImportQuantStatsPassForTFControlDialect(
pass_config.quant_specs.serialized_quant_stats));
}
if (pass_config.lower_tensor_list_ops) {
// TODO(haoliang): Add this pass by default.
pass_manager->addPass(mlir::TFL::CreateLowerStaticTensorListPass());
}
// The ophint extractions happen before lots of other passes:
// The assumption of ophint-extraction is each ophinted region is a black-box
// and nodes within this black-box is NOT connected to the nodes OUTSIDE the
// black-box.
// Some passes may merge nodes together (such as const nodes), however, this
// will break the ophint-extraction assumption. (The nodes within the black
// box is not isolated anymore).
// So ophint extraction and legalization needs to happen before
// the canonicalization pass.
if (pass_config.emit_builtin_tflite_ops) {
pass_manager->addPass(mlir::TFL::CreateExtractOphintPass());
// Convert composite op pass will happen after ophint extraction pass.
pass_manager->addPass(mlir::TFL::CreateLegalizeOphintFuncOpPass());
}
// This decomposes resource ops like ResourceGather into read-variable op
// followed by gather. This is used when the saved model import path is used
// during which resources dont get frozen in the python layer.
pass_manager->addNestedPass<mlir::FuncOp>(
mlir::TFDevice::CreateDecomposeResourceOpsPass());
// This pass does resource analysis of saved model global tensors and marks
// those deemed read-only as immutable.
pass_manager->addPass(
mlir::tf_saved_model::CreateOptimizeGlobalTensorsPass());
// This pass marks non-exported functions as symbol visibility 'private'
// those deemed read-only as immutable.
pass_manager->addPass(
mlir::tf_saved_model::
CreateMarkFunctionVisibilityUsingSavedModelLinkagePass());
// Enable fusing composite ops that can be lowered to built-in TFLite ops.
if (pass_config.emit_builtin_tflite_ops) {
pass_manager->addPass(mlir::TFL::CreatePrepareCompositeFunctionsPass());
}
// Legalize while early to allow further constant folding.
// TODO(jpienaar): This may not actually matter as we do canonicalization
// after the legalize below, for now it needs to be below the above passes
// that work on TF dialect and before inliner so that the function calls in
// body and cond are inlined for optimization.
if (pass_config.legalize_tf_while) {
pass_manager->addPass(mlir::TFL::CreateLegalizeTFWhilePass());
}
// Add function inlining pass. Both TF and TFLite dialects are opted into
// function inliner interface.
pass_manager->addPass(mlir::createInlinerPass());
// TODO(jpienaar): Revise post dialect constants.
pass_manager->addPass(mlir::TF::CreateDecodeConstantPass());
// Canonicalization includes const folding, which is utilized here to optimize
// away ops that can't get constant folded after PrepareTF pass. For example,
// tf.Conv2D is split into tf.Transpose and tfl.Conv2D.
pass_manager->addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass());
pass_manager->addNestedPass<mlir::FuncOp>(mlir::createCSEPass());
// This pass does dead code elimination based on symbol visibility.
pass_manager->addPass(mlir::createSymbolDCEPass());
// This pass 'freezes' immutable global tensors and inlines them as tf
// constant ops.
pass_manager->addPass(mlir::tf_saved_model::CreateFreezeGlobalTensorsPass());
if (pass_config.shape_inference) {
// Add a shape inference pass to optimize away the unnecessary casts.
pass_manager->addPass(mlir::TF::CreateTFShapeInferencePass());
}
// The below passes only make sense if Builtin TFLite ops are enabled
// for emission.
if (pass_config.emit_builtin_tflite_ops) {
// Prepare for TFLite dialect, rerun canonicalization, and then legalize to
// the TFLite dialect.
pass_manager->addPass(
mlir::TFL::CreatePrepareTFPass(pass_config.unfold_batch_matmul));
pass_manager->addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass());
pass_manager->addPass(mlir::TFL::CreateLegalizeTFPass());
pass_manager->addPass(mlir::TFL::CreateOptimizePass());
// This pass operates on TensorFlow ops but is triggered after legalization
// so that it can target constants introduced once TensorFlow Identity ops
// are removed during legalization.
pass_manager->addPass(mlir::TFL::CreateOptimizeFunctionalOpsPass());
pass_manager->addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass());
pass_manager->addNestedPass<mlir::FuncOp>(mlir::createCSEPass());
// This pass should be always at the end of the floating point model
// conversion. Some TFL ops like unidirectional
// sequence lstm will have stateful operands and some optimization passes
// will merge those operands if they have identical values & types. However,
// it's not desired by TFL. This pass serves as a "fix" pass to split the
// merged inputs until we have 1st class variable support or reuse
// tf.variable to model this.
pass_manager->addPass(mlir::TFL::CreateSplitMergedOperandsPass());
// Run quantization after all the floating point model conversion is
// completed.
if (pass_config.quant_specs.RunPropagationAndRewriteQuantizationPasses()) {
AddQuantizationPasses(pass_config.quant_specs, pass_manager);
}
}
}
} // namespace tensorflow
namespace mlir {
namespace TFL {
struct StandardPipelineOptions
: public PassPipelineOptions<StandardPipelineOptions> {
// TODO(b/150915052): All the tf_tfl_translate_cl flags should
// move inside this.
};
// NOLINTNEXTLINE
// This creates the standard pass pipeline for TF->TFLite. This
// represents a std configuration for TFLite, for use with APIs like
// tensorflow/python/pywrap_mlir.py::experimental_run_pass_pipeline
// This does not yet include quantization passes.
void CreateTFLStandardPipeline(OpPassManager& pm,
const StandardPipelineOptions& options) {
OpPassManager& func_pm = pm.nest<FuncOp>();
// tf_executor dialect passes - Cleaning up the IR.
func_pm.addPass(tf_executor::CreateSwitchFoldPass());
func_pm.addPass(tf_executor::CreateTFExecutorGraphPruningPass());
func_pm.addPass(tf_executor::CreateTFExecutorIslandCoarseningPass());
// more cleanup of executor dialect and raise to control flow.
pm.addPass(mlir::CreateTFExecutorToControlDialectConversion());
pm.addPass(mlir::TFControlFlow::CreateRaiseTFControlFlowPass());
// This is needed for control flow support with TF TensorList.
pm.addPass(mlir::TFL::CreateLowerStaticTensorListPass());
// Saved model pass to mark global tensors immutable.
pm.addPass(mlir::tf_saved_model::CreateOptimizeGlobalTensorsPass());
// Used to mark non-exported functions in saved model private.
pm.addPass(mlir::tf_saved_model::
CreateMarkFunctionVisibilityUsingSavedModelLinkagePass());
// Op fusion pass.
pm.addPass(mlir::TFL::CreatePrepareCompositeFunctionsPass());
pm.addNestedPass<mlir::FuncOp>(mlir::TFL::CreateLegalizeTFWhilePass());
pm.addPass(mlir::createInlinerPass());
// Canonicalize, CSE etc.
pm.addPass(mlir::TF::CreateDecodeConstantPass());
pm.addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass());
pm.addNestedPass<mlir::FuncOp>(mlir::createCSEPass());
// DCE for private symbols.
pm.addPass(mlir::createSymbolDCEPass());
// freeze global tensors.
pm.addPass(mlir::tf_saved_model::CreateFreezeGlobalTensorsPass());
// TFLite dialect passes.
pm.addPass(mlir::TFL::CreatePrepareTFPass(true));
pm.addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass());
pm.addPass(mlir::TFL::CreateLegalizeTFPass());
pm.addPass(mlir::TFL::CreateOptimizePass());
pm.addPass(mlir::TFL::CreateOptimizeFunctionalOpsPass());
// Canonicalize, CSE etc.
pm.addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass());
pm.addNestedPass<mlir::FuncOp>(mlir::createCSEPass());
// Pass for stateful operands like LSTM.
pm.addPass(mlir::TFL::CreateSplitMergedOperandsPass());
pm.addPass(mlir::TFL::CreateWhileOutlinePass());
pm.addPass(mlir::TFL::CreateRuntimeTypeVerifyPass());
}
// Registers a pass pipeline for the standard TFL passes.
static mlir::PassPipelineRegistration<StandardPipelineOptions> pipeline(
"tfl-standard-pipeline",
"Run the standard passes involved in transforming/optimizing the TF "
"program to TFLite after "
"importing into MLIR.",
CreateTFLStandardPipeline);
} // namespace TFL
} // namespace mlir
<commit_msg>Tweak passes: fuse lstms & inline & dce before lower tensor list ops.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/mlir/lite/tf_tfl_passes.h"
#include "mlir/IR/Attributes.h" // from @llvm-project
#include "mlir/IR/Module.h" // from @llvm-project
#include "mlir/Pass/Pass.h" // from @llvm-project
#include "mlir/Pass/PassManager.h" // from @llvm-project
#include "mlir/Transforms/Passes.h" // from @llvm-project
#include "tensorflow/compiler/mlir/lite/quantization/quantization_config.h"
#include "tensorflow/compiler/mlir/lite/quantization/quantization_passes.h"
#include "tensorflow/compiler/mlir/lite/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/decode_constant.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/tf_mlir_translate.h"
namespace mlir {
/// Create a pass to convert from the TFExecutor to the TF control dialect.
std::unique_ptr<OpPassBase<FuncOp>>
CreateTFExecutorToControlDialectConversion();
} // namespace mlir
namespace tensorflow {
void AddQuantizationPasses(const mlir::TFL::QuantizationSpecs& quant_specs,
mlir::OpPassManager* pass_manager) {
pass_manager->addPass(mlir::TFL::CreatePrepareQuantizePass(quant_specs));
pass_manager->addPass(mlir::TFL::CreateQuantizePass());
bool emit_quant_adaptor_ops =
quant_specs.inference_type != quant_specs.inference_input_type;
pass_manager->addPass(
mlir::TFL::CreatePostQuantizePass(emit_quant_adaptor_ops));
if (quant_specs.default_ranges.first.hasValue() ||
quant_specs.default_ranges.second.hasValue()) {
pass_manager->addPass(mlir::TFL::CreateDefaultQuantParamsPass(
quant_specs.default_ranges.first.getValueOr(0.0),
quant_specs.default_ranges.second.getValueOr(0.0)));
pass_manager->addPass(mlir::TFL::CreateQuantizePass());
pass_manager->addPass(
mlir::TFL::CreatePostQuantizePass(emit_quant_adaptor_ops));
}
}
void AddTFToTFLConversionPasses(const mlir::TFL::PassConfig& pass_config,
mlir::OpPassManager* pass_manager) {
pass_manager->addPass(mlir::tf_executor::CreateSwitchFoldPass());
if (pass_config.skip_control_dialect) {
// Merge islands.
pass_manager->addPass(
mlir::tf_executor::CreateTFExecutorIslandCoarseningPass());
// Assuming island coarsening above results in a graph with a single island,
// a canonicalization can be ran to hoist the ops of the single island out.
pass_manager->addPass(mlir::createCanonicalizerPass());
if (pass_config.form_clusters)
pass_manager->addPass(mlir::TFDevice::CreateClusterFormationPass());
} else {
pass_manager->addPass(mlir::CreateTFExecutorToControlDialectConversion());
pass_manager->addPass(mlir::TFControlFlow::CreateRaiseTFControlFlowPass());
}
if (!pass_config.quant_specs.serialized_quant_stats.empty()) {
pass_manager->addPass(
mlir::quant::CreateImportQuantStatsPassForTFControlDialect(
pass_config.quant_specs.serialized_quant_stats));
}
// Note:
// We need to fuse composite ops before LowerStaticTensorList pass.
// The tensorflow list is not supported right now by that pass.
// Enable fusing composite ops that can be lowered to built-in TFLite ops.
if (pass_config.emit_builtin_tflite_ops) {
pass_manager->addPass(mlir::TFL::CreatePrepareCompositeFunctionsPass());
}
// This pass marks non-exported functions as symbol visibility 'private'
// those deemed read-only as immutable.
pass_manager->addPass(
mlir::tf_saved_model::
CreateMarkFunctionVisibilityUsingSavedModelLinkagePass());
pass_manager->addPass(mlir::createInlinerPass());
pass_manager->addPass(mlir::createSymbolDCEPass());
if (pass_config.lower_tensor_list_ops) {
// TODO(haoliang): Add this pass by default.
pass_manager->addPass(mlir::TFL::CreateLowerStaticTensorListPass());
}
// The ophint extractions happen before lots of other passes:
// The assumption of ophint-extraction is each ophinted region is a black-box
// and nodes within this black-box is NOT connected to the nodes OUTSIDE the
// black-box.
// Some passes may merge nodes together (such as const nodes), however, this
// will break the ophint-extraction assumption. (The nodes within the black
// box is not isolated anymore).
// So ophint extraction and legalization needs to happen before
// the canonicalization pass.
if (pass_config.emit_builtin_tflite_ops) {
pass_manager->addPass(mlir::TFL::CreateExtractOphintPass());
// Convert composite op pass will happen after ophint extraction pass.
pass_manager->addPass(mlir::TFL::CreateLegalizeOphintFuncOpPass());
}
// This decomposes resource ops like ResourceGather into read-variable op
// followed by gather. This is used when the saved model import path is used
// during which resources dont get frozen in the python layer.
pass_manager->addNestedPass<mlir::FuncOp>(
mlir::TFDevice::CreateDecomposeResourceOpsPass());
// This pass does resource analysis of saved model global tensors and marks
// those deemed read-only as immutable.
pass_manager->addPass(
mlir::tf_saved_model::CreateOptimizeGlobalTensorsPass());
// Legalize while early to allow further constant folding.
// TODO(jpienaar): This may not actually matter as we do canonicalization
// after the legalize below, for now it needs to be below the above passes
// that work on TF dialect and before inliner so that the function calls in
// body and cond are inlined for optimization.
if (pass_config.legalize_tf_while) {
pass_manager->addPass(mlir::TFL::CreateLegalizeTFWhilePass());
}
// Add function inlining pass. Both TF and TFLite dialects are opted into
// function inliner interface.
pass_manager->addPass(mlir::createInlinerPass());
// TODO(jpienaar): Revise post dialect constants.
pass_manager->addPass(mlir::TF::CreateDecodeConstantPass());
// Canonicalization includes const folding, which is utilized here to optimize
// away ops that can't get constant folded after PrepareTF pass. For example,
// tf.Conv2D is split into tf.Transpose and tfl.Conv2D.
pass_manager->addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass());
pass_manager->addNestedPass<mlir::FuncOp>(mlir::createCSEPass());
// This pass does dead code elimination based on symbol visibility.
pass_manager->addPass(mlir::createSymbolDCEPass());
// This pass 'freezes' immutable global tensors and inlines them as tf
// constant ops.
pass_manager->addPass(mlir::tf_saved_model::CreateFreezeGlobalTensorsPass());
if (pass_config.shape_inference) {
// Add a shape inference pass to optimize away the unnecessary casts.
pass_manager->addPass(mlir::TF::CreateTFShapeInferencePass());
}
// The below passes only make sense if Builtin TFLite ops are enabled
// for emission.
if (pass_config.emit_builtin_tflite_ops) {
// Prepare for TFLite dialect, rerun canonicalization, and then legalize to
// the TFLite dialect.
pass_manager->addPass(
mlir::TFL::CreatePrepareTFPass(pass_config.unfold_batch_matmul));
pass_manager->addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass());
pass_manager->addPass(mlir::TFL::CreateLegalizeTFPass());
pass_manager->addPass(mlir::TFL::CreateOptimizePass());
// This pass operates on TensorFlow ops but is triggered after legalization
// so that it can target constants introduced once TensorFlow Identity ops
// are removed during legalization.
pass_manager->addPass(mlir::TFL::CreateOptimizeFunctionalOpsPass());
pass_manager->addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass());
pass_manager->addNestedPass<mlir::FuncOp>(mlir::createCSEPass());
// This pass should be always at the end of the floating point model
// conversion. Some TFL ops like unidirectional
// sequence lstm will have stateful operands and some optimization passes
// will merge those operands if they have identical values & types. However,
// it's not desired by TFL. This pass serves as a "fix" pass to split the
// merged inputs until we have 1st class variable support or reuse
// tf.variable to model this.
pass_manager->addPass(mlir::TFL::CreateSplitMergedOperandsPass());
// Run quantization after all the floating point model conversion is
// completed.
if (pass_config.quant_specs.RunPropagationAndRewriteQuantizationPasses()) {
AddQuantizationPasses(pass_config.quant_specs, pass_manager);
}
}
}
} // namespace tensorflow
namespace mlir {
namespace TFL {
struct StandardPipelineOptions
: public PassPipelineOptions<StandardPipelineOptions> {
// TODO(b/150915052): All the tf_tfl_translate_cl flags should
// move inside this.
};
// NOLINTNEXTLINE
// This creates the standard pass pipeline for TF->TFLite. This
// represents a std configuration for TFLite, for use with APIs like
// tensorflow/python/pywrap_mlir.py::experimental_run_pass_pipeline
// This does not yet include quantization passes.
void CreateTFLStandardPipeline(OpPassManager& pm,
const StandardPipelineOptions& options) {
OpPassManager& func_pm = pm.nest<FuncOp>();
// tf_executor dialect passes - Cleaning up the IR.
func_pm.addPass(tf_executor::CreateSwitchFoldPass());
func_pm.addPass(tf_executor::CreateTFExecutorGraphPruningPass());
func_pm.addPass(tf_executor::CreateTFExecutorIslandCoarseningPass());
// more cleanup of executor dialect and raise to control flow.
pm.addPass(mlir::CreateTFExecutorToControlDialectConversion());
pm.addPass(mlir::TFControlFlow::CreateRaiseTFControlFlowPass());
// This is needed for control flow support with TF TensorList.
pm.addPass(mlir::TFL::CreateLowerStaticTensorListPass());
// Saved model pass to mark global tensors immutable.
pm.addPass(mlir::tf_saved_model::CreateOptimizeGlobalTensorsPass());
// Used to mark non-exported functions in saved model private.
pm.addPass(mlir::tf_saved_model::
CreateMarkFunctionVisibilityUsingSavedModelLinkagePass());
// Op fusion pass.
pm.addPass(mlir::TFL::CreatePrepareCompositeFunctionsPass());
pm.addNestedPass<mlir::FuncOp>(mlir::TFL::CreateLegalizeTFWhilePass());
pm.addPass(mlir::createInlinerPass());
// Canonicalize, CSE etc.
pm.addPass(mlir::TF::CreateDecodeConstantPass());
pm.addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass());
pm.addNestedPass<mlir::FuncOp>(mlir::createCSEPass());
// DCE for private symbols.
pm.addPass(mlir::createSymbolDCEPass());
// freeze global tensors.
pm.addPass(mlir::tf_saved_model::CreateFreezeGlobalTensorsPass());
// TFLite dialect passes.
pm.addPass(mlir::TFL::CreatePrepareTFPass(true));
pm.addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass());
pm.addPass(mlir::TFL::CreateLegalizeTFPass());
pm.addPass(mlir::TFL::CreateOptimizePass());
pm.addPass(mlir::TFL::CreateOptimizeFunctionalOpsPass());
// Canonicalize, CSE etc.
pm.addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass());
pm.addNestedPass<mlir::FuncOp>(mlir::createCSEPass());
// Pass for stateful operands like LSTM.
pm.addPass(mlir::TFL::CreateSplitMergedOperandsPass());
pm.addPass(mlir::TFL::CreateWhileOutlinePass());
pm.addPass(mlir::TFL::CreateRuntimeTypeVerifyPass());
}
// Registers a pass pipeline for the standard TFL passes.
static mlir::PassPipelineRegistration<StandardPipelineOptions> pipeline(
"tfl-standard-pipeline",
"Run the standard passes involved in transforming/optimizing the TF "
"program to TFLite after "
"importing into MLIR.",
CreateTFLStandardPipeline);
} // namespace TFL
} // namespace mlir
<|endoftext|> |
<commit_before>#ifndef ATL_HELPER_PATTERN_MATCH_HPP
#define ATL_HELPER_PATTERN_MATCH_HPP
#include <helpers/misc.hpp>
#include <print.hpp>
namespace atl
{
namespace pattern_match
{
using make_type::tt;
struct Match;
typedef std::function<bool (Match&, Any const&)> Matcher;
struct Match
{
/* If we're given a raw string, store the type we see at
* that position when doing a match, and make sure all
* occurances of that string are of the same type (ie for
* ast("a", "b", "a"), (1 "foo" 1) would match, but (1 1
* "foo") would not)*/
std::map<std::string, Type> seen_types;
virtual bool operator()(std::string const& ss, Any const& tt)
{
auto found = seen_types.find(ss);
if(found != seen_types.end())
{ return found->second == typify(tt); }
else
{
seen_types.emplace(ss, typify(tt));
return true;
}
}
virtual bool operator()(long expected_tag, Any const& tt)
{ return static_cast<Type::value_type>(expected_tag) == tt._tag; }
bool operator()(Any const& value, Any const& tt)
{ return value == tt; }
bool operator()(Matcher const& fn, Any const& tt)
{ return fn(*this, tt); }
};
/* Like Match, but assumes an unwrapped string is matching a
* particular symbol and an int is referring to a Fixnum.
*/
struct LiteralMatch
: public Match
{
virtual bool operator()(std::string const& ss, Any const& tt) override
{ return is<Symbol>(tt) && unwrap<Symbol>(tt).name == ss; }
virtual bool operator()(long fixnum, Any const& tt) override
{ return is<Fixnum>(tt) && unwrap<Fixnum>(tt).value == fixnum; }
};
struct _DispatchMatcher
{
Ast::const_iterator itr, end;
Match& run;
_DispatchMatcher(Match& run_, Ast::const_iterator itr_, Ast::const_iterator end_)
: itr(itr_)
, end(end_)
, run(run_)
{}
template<class Test>
bool operator()(Test const& test)
{
if(itr == end) { return false; }
bool value = run(test, *itr);
++itr;
return value;
}
};
template<class T>
Matcher capture(T& passed_hold)
{
auto hold = &passed_hold;
return [hold](Match&, Any const& expr)
{
if(is<T>(expr))
{
*hold = unwrap<T>(expr);
return true;
}
return false;
};
}
template<class T>
Matcher capture_ptr(T const*& passed_hold)
{
auto hold = &passed_hold;
return [hold](Match&, Any const& expr)
{
if(is<T>(expr))
{
*hold = &unwrap<T>(expr);
return true;
}
return false;
};
}
template<class ... Args>
Matcher ast(Args ... args)
{
auto tup = std::make_tuple(args...);
return [tup](Match& match, Any const& expr) -> bool
{
Ast::const_iterator begin, end;
switch(expr._tag)
{
case tag<Ast>::value:
{
auto const& ast = reinterpret_cast<Ast const&>(expr);
begin = ast.begin();
end = ast.end();
break;
}
default:
return false;
}
auto run = _DispatchMatcher(match, begin, end);
return and_tuple(run, tup) && (run.itr == run.end);
};
}
/* I have a bunch of tests that want to match a function type;
* add a quicker way to build those
*/
template<class T>
Matcher fnt(T const& arg0)
{ return ast(wrap<Type>(tag<FunctionConstructor>::value), arg0); }
template<class T, class U>
Matcher fnt(T const& arg0, U const& arg1)
{ return ast(wrap<Type>(tag<FunctionConstructor>::value), arg0, arg1); }
template<class T, class ... Rest>
Matcher fnt(T const& arg0, Rest ... rest)
{ return ast(wrap<Type>(tag<FunctionConstructor>::value), arg0, fnt(rest...)); }
/* Helper for declaring asts of types (something that seems to come up a bit in tests). */
template<class ... Args>
Matcher types()
{ return ast(tag<Args>::value...); }
bool match(Matcher const& pattern, Any const& expr)
{
Match context;
return pattern(context, expr);
}
template<class T>
bool match(T const& pattern, Any const& expr)
{
Match matcher;
return matcher(pattern, expr);
}
bool literal_match(Matcher const& pattern, Any const& expr)
{
LiteralMatch context;
return pattern(context, expr);
}
template<class T>
bool literal_match(T const& pattern, Any const& expr)
{
LiteralMatch matcher;
return matcher(pattern, expr);
}
}
}
#endif
<commit_msg>pattern_match: Consolidate type declaration<commit_after>#ifndef ATL_HELPER_PATTERN_MATCH_HPP
#define ATL_HELPER_PATTERN_MATCH_HPP
#include <helpers/misc.hpp>
#include <print.hpp>
namespace atl
{
namespace pattern_match
{
using make_type::tt;
struct Match;
typedef std::function<bool (Match&, Any const&)> Matcher;
struct Match
{
/* If we're given a raw string, store the type we see at
* that position when doing a match, and make sure all
* occurances of that string are of the same type (ie for
* ast("a", "b", "a"), (1 "foo" 1) would match, but (1 1
* "foo") would not)*/
std::map<std::string, Type> seen_types;
virtual bool operator()(std::string const& ss, Any const& tt)
{
auto found = seen_types.find(ss);
if(found != seen_types.end())
{ return found->second == typify(tt); }
else
{
seen_types.emplace(ss, typify(tt));
return true;
}
}
virtual bool operator()(long expected_tag, Any const& tt)
{ return static_cast<Type::value_type>(expected_tag) == tt._tag; }
bool operator()(Any const& value, Any const& tt)
{ return value == tt; }
bool operator()(Matcher const& fn, Any const& tt)
{ return fn(*this, tt); }
};
/* Like Match, but assumes an unwrapped string is matching a
* particular symbol and an int is referring to a Fixnum.
*/
struct LiteralMatch
: public Match
{
virtual bool operator()(std::string const& ss, Any const& tt) override
{ return is<Symbol>(tt) && unwrap<Symbol>(tt).name == ss; }
virtual bool operator()(long fixnum, Any const& tt) override
{ return is<Fixnum>(tt) && unwrap<Fixnum>(tt).value == fixnum; }
};
struct _DispatchMatcher
{
typedef Ast::const_iterator iterator;
iterator itr, end;
Match& run;
_DispatchMatcher(Match& run_, iterator itr_, iterator end_)
: itr(itr_)
, end(end_)
, run(run_)
{}
template<class Test>
bool operator()(Test const& test)
{
if(itr == end) { return false; }
bool value = run(test, *itr);
++itr;
return value;
}
};
template<class T>
Matcher capture(T& passed_hold)
{
auto hold = &passed_hold;
return [hold](Match&, Any const& expr)
{
if(is<T>(expr))
{
*hold = unwrap<T>(expr);
return true;
}
return false;
};
}
template<class T>
Matcher capture_ptr(T const*& passed_hold)
{
auto hold = &passed_hold;
return [hold](Match&, Any const& expr)
{
if(is<T>(expr))
{
*hold = &unwrap<T>(expr);
return true;
}
return false;
};
}
template<class ... Args>
Matcher ast(Args ... args)
{
auto tup = std::make_tuple(args...);
return [tup](Match& match, Any const& expr) -> bool
{
Ast::const_iterator begin, end;
switch(expr._tag)
{
case tag<Ast>::value:
{
auto const& ast = reinterpret_cast<Ast const&>(expr);
begin = ast.begin();
end = ast.end();
break;
}
default:
return false;
}
auto run = _DispatchMatcher(match, begin, end);
return and_tuple(run, tup) && (run.itr == run.end);
};
}
/* I have a bunch of tests that want to match a function type;
* add a quicker way to build those
*/
template<class T>
Matcher fnt(T const& arg0)
{ return ast(wrap<Type>(tag<FunctionConstructor>::value), arg0); }
template<class T, class U>
Matcher fnt(T const& arg0, U const& arg1)
{ return ast(wrap<Type>(tag<FunctionConstructor>::value), arg0, arg1); }
template<class T, class ... Rest>
Matcher fnt(T const& arg0, Rest ... rest)
{ return ast(wrap<Type>(tag<FunctionConstructor>::value), arg0, fnt(rest...)); }
/* Helper for declaring asts of types (something that seems to come up a bit in tests). */
template<class ... Args>
Matcher types()
{ return ast(tag<Args>::value...); }
bool match(Matcher const& pattern, Any const& expr)
{
Match context;
return pattern(context, expr);
}
template<class T>
bool match(T const& pattern, Any const& expr)
{
Match matcher;
return matcher(pattern, expr);
}
bool literal_match(Matcher const& pattern, Any const& expr)
{
LiteralMatch context;
return pattern(context, expr);
}
template<class T>
bool literal_match(T const& pattern, Any const& expr)
{
LiteralMatch matcher;
return matcher(pattern, expr);
}
}
}
#endif
<|endoftext|> |
<commit_before>//===--- ArchetypeBuilder.cpp - Generic Requirement Builder -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Support for collecting a set of generic requirements, both explicitly stated
// and inferred, and computing the archetypes and required witness tables from
// those requirements.
//
//===----------------------------------------------------------------------===//
#include "ArchetypeBuilder.h"
#include "TypeChecker.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
using llvm::DenseMap;
/// \brief A type that will be mapped down to some archetype, which gathers
/// all of the requirements and nested types of that archetype.
struct ArchetypeBuilder::PotentialArchetype {
PotentialArchetype(StringRef DisplayName, Optional<unsigned> Index = Nothing)
: DisplayName(DisplayName.str()), Index(Index), Archetype(nullptr) { }
/// \brief The name used to describe this archetype.
std::string DisplayName;
/// \brief The index of the computed archetype.
Optional<unsigned> Index;
/// \brief The list of protocols to which this archetype will conform.
llvm::SetVector<ProtocolDecl *> ConformsTo;
/// \brief The set of nested typed stored within this protocol.
DenseMap<Identifier, PotentialArchetype *> NestedTypes;
/// \brief The actual archetype, once it has been assigned.
ArchetypeType *Archetype;
/// \brief Retrieve (or create) a nested type with the given name.
PotentialArchetype *getNestedType(Identifier Name) {
PotentialArchetype *&Result = NestedTypes[Name];
if (!Result) {
// FIXME: The 'This' hack is pretty ugly.
if (Name.str() == "This")
Result = this;
else
Result = new PotentialArchetype(DisplayName + "." + Name.get());
}
return Result;
}
/// \brief Retrieve (or build) the archetype corresponding to the potential
/// archetype.
ArchetypeType *getArchetype(TypeChecker &TC) {
if (!Archetype) {
// Allocate a new archetype.
SmallVector<ProtocolDecl *, 4> Protos(ConformsTo.begin(),
ConformsTo.end());
Archetype = ArchetypeType::getNew(TC.Context, DisplayName, Protos, Index);
// For each of the protocols we conform to, find the appropriate nested
// types and add archetype mappings for them.
// FIXME: This hideousness is caused by the hideousness inherent in
// the AssociatedTypeMap anti-design. Fix that, and this becomes less
// horrible.
for (auto Proto : ConformsTo) {
for (auto Member : Proto->getMembers()) {
auto AssocType = dyn_cast<TypeAliasDecl>(Member);
if (!AssocType)
continue;
ArchetypeType *AssocArchetype
= AssocType->getDeclaredType()->castTo<ArchetypeType>();
TC.Context.AssociatedTypeMap[Archetype][AssocArchetype]
= getNestedType(AssocType->getName())->getArchetype(TC);
}
}
}
return Archetype;
}
void dump(llvm::raw_ostream &Out, unsigned Indent) {
// Print name.
StringRef Name = DisplayName;
std::size_t DotPos = Name.rfind('.');
if (DotPos != StringRef::npos)
Name = Name.substr(DotPos+1);
Out.indent(Indent) << Name;
// Print requirements.
if (!ConformsTo.empty()) {
Out << " : ";
if (ConformsTo.size() != 1)
Out << "protocol<";
bool First = true;
for (auto Proto : ConformsTo) {
if (First)
First = false;
else
Out << ", ";
Out << Proto->getName().str();
}
if (ConformsTo.size() != 1)
Out << ">";
}
Out << "\n";
// Print nested types.
for (const auto &Nested : NestedTypes) {
Nested.second->dump(Out, Indent + 2);
}
}
};
struct ArchetypeBuilder::Implementation {
SmallVector<TypeAliasDecl *, 4> GenericParams;
DenseMap<TypeAliasDecl *, PotentialArchetype *> PotentialArchetypes;
};
ArchetypeBuilder::ArchetypeBuilder(TypeChecker &TC)
: TC(TC), Impl(new Implementation)
{
}
ArchetypeBuilder::~ArchetypeBuilder() {}
auto ArchetypeBuilder::resolveType(Type T) -> PotentialArchetype * {
auto IdType = dyn_cast<IdentifierType>(T);
if (!IdType)
return nullptr;
PotentialArchetype *Current = nullptr;
if (!IdType->Components[0].Value.is<ValueDecl *>())
return nullptr;
// The first type needs to be known as a potential archetype, e.g., a
// generic parameter.
TypeAliasDecl *FirstType
= dyn_cast<TypeAliasDecl>(IdType->Components[0].Value.get<ValueDecl *>());
if (!FirstType)
return nullptr;
DenseMap<TypeAliasDecl *, PotentialArchetype *>::iterator Known
= Impl->PotentialArchetypes.find(FirstType);
if (Known == Impl->PotentialArchetypes.end())
return nullptr;
// Resolve nested types.
Current = Known->second;
for (unsigned I = 1, N = IdType->Components.size(); I != N; ++I) {
Current = Current->getNestedType(IdType->Components[I].Id);
}
return Current;
}
bool ArchetypeBuilder::addGenericParameter(TypeAliasDecl *GenericParam,
Optional<unsigned> Index) {
Impl->GenericParams.push_back(GenericParam);
// Create a potential archetype for this generic parameter.
assert(!Impl->PotentialArchetypes[GenericParam]);
auto PA = new PotentialArchetype(GenericParam->getName().str(), Index);
Impl->PotentialArchetypes[GenericParam] = PA;
// Add each of the requirements placed on this generic parameter.
for (auto Inherited : GenericParam->getInherited()) {
SmallVector<ProtocolDecl *, 4> ConformsTo;
if (Inherited.getType()->isExistentialType(ConformsTo)) {
for (auto Proto : ConformsTo)
if (addConformanceRequirement(PA, Proto))
return true;
}
}
return false;
}
bool ArchetypeBuilder::addConformanceRequirement(PotentialArchetype *T,
ProtocolDecl *Proto){
// If we've already added this requirement, we're done.
if (!T->ConformsTo.insert(Proto))
return false;
// Add all of the inherited protocol requirements, recursively.
for (auto Inherited : Proto->getInherited()) {
SmallVector<ProtocolDecl *, 4> InheritedProtos;
if (Inherited.getType()->isExistentialType(InheritedProtos)) {
for (auto InheritedProto : InheritedProtos) {
if (addConformanceRequirement(T, InheritedProto))
return true;
}
}
}
// Add requirements for each of the associated types.
for (auto Member : Proto->getMembers()) {
if (auto AssocType = dyn_cast<TypeAliasDecl>(Member)) {
// FIXME: Another 'This' hack.
if (AssocType->getName().str() == "This")
continue;
// Add requirements placed directly on this associated type.
auto AssocPA = T->getNestedType(AssocType->getName());
for (auto Inherited : AssocType->getInherited()) {
SmallVector<ProtocolDecl *, 4> InheritedProtos;
if (Inherited.getType()->isExistentialType(InheritedProtos)) {
for (auto InheritedProto : InheritedProtos) {
if (addConformanceRequirement(AssocPA, InheritedProto))
return true;
}
}
}
continue;
}
// FIXME: Requirement declarations.
}
return false;
}
bool ArchetypeBuilder::addRequirement(const Requirement &Req) {
switch (Req.getKind()) {
case RequirementKind::Conformance: {
PotentialArchetype *PA = resolveType(Req.getSubject());
if (!PA) {
// FIXME: Diagnose this failure.
return true;
}
SmallVector<ProtocolDecl *, 4> ConformsTo;
if (!Req.getProtocol()->isExistentialType(ConformsTo)) {
// FIXME: Diagnose this failure here, rather than over in type-checking.
return true;
}
// Add each of the protocols.
for (auto Proto : ConformsTo)
if (addConformanceRequirement(PA, Proto))
return true;
return false;
}
case RequirementKind::SameType: {
// FIXME: Implement same-type constraints.
return false;
}
}
llvm_unreachable("Unhandled requirement?");
}
llvm::DenseMap<TypeAliasDecl *, ArchetypeType *>
ArchetypeBuilder::assignArchetypes() {
llvm::DenseMap<TypeAliasDecl *, ArchetypeType *> Archetypes;
for (const auto& PA : Impl->PotentialArchetypes) {
Archetypes[PA.first] = PA.second->getArchetype(TC);
}
return std::move(Archetypes);
}
void ArchetypeBuilder::dump() {
llvm::errs() << "Archetypes to build:\n";
for (const auto& PA : Impl->PotentialArchetypes) {
PA.second->dump(llvm::errs(), 2);
}
}
<commit_msg>It is considered poor form to 'new' memory without 'delete'ing it.<commit_after>//===--- ArchetypeBuilder.cpp - Generic Requirement Builder -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Support for collecting a set of generic requirements, both explicitly stated
// and inferred, and computing the archetypes and required witness tables from
// those requirements.
//
//===----------------------------------------------------------------------===//
#include "ArchetypeBuilder.h"
#include "TypeChecker.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
using llvm::DenseMap;
/// \brief A type that will be mapped down to some archetype, which gathers
/// all of the requirements and nested types of that archetype.
struct ArchetypeBuilder::PotentialArchetype {
PotentialArchetype(StringRef DisplayName, Optional<unsigned> Index = Nothing)
: DisplayName(DisplayName.str()), Index(Index), Archetype(nullptr) { }
~PotentialArchetype() {
for (auto Nested : NestedTypes) {
if (Nested.second != this) {
delete Nested.second;
}
}
}
/// \brief The name used to describe this archetype.
std::string DisplayName;
/// \brief The index of the computed archetype.
Optional<unsigned> Index;
/// \brief The list of protocols to which this archetype will conform.
llvm::SetVector<ProtocolDecl *> ConformsTo;
/// \brief The set of nested typed stored within this protocol.
DenseMap<Identifier, PotentialArchetype *> NestedTypes;
/// \brief The actual archetype, once it has been assigned.
ArchetypeType *Archetype;
/// \brief Retrieve (or create) a nested type with the given name.
PotentialArchetype *getNestedType(Identifier Name) {
PotentialArchetype *&Result = NestedTypes[Name];
if (!Result) {
// FIXME: The 'This' hack is pretty ugly.
if (Name.str() == "This")
Result = this;
else
Result = new PotentialArchetype(DisplayName + "." + Name.get());
}
return Result;
}
/// \brief Retrieve (or build) the archetype corresponding to the potential
/// archetype.
ArchetypeType *getArchetype(TypeChecker &TC) {
if (!Archetype) {
// Allocate a new archetype.
SmallVector<ProtocolDecl *, 4> Protos(ConformsTo.begin(),
ConformsTo.end());
Archetype = ArchetypeType::getNew(TC.Context, DisplayName, Protos, Index);
// For each of the protocols we conform to, find the appropriate nested
// types and add archetype mappings for them.
// FIXME: This hideousness is caused by the hideousness inherent in
// the AssociatedTypeMap anti-design. Fix that, and this becomes less
// horrible.
for (auto Proto : ConformsTo) {
for (auto Member : Proto->getMembers()) {
auto AssocType = dyn_cast<TypeAliasDecl>(Member);
if (!AssocType)
continue;
ArchetypeType *AssocArchetype
= AssocType->getDeclaredType()->castTo<ArchetypeType>();
TC.Context.AssociatedTypeMap[Archetype][AssocArchetype]
= getNestedType(AssocType->getName())->getArchetype(TC);
}
}
}
return Archetype;
}
void dump(llvm::raw_ostream &Out, unsigned Indent) {
// Print name.
StringRef Name = DisplayName;
std::size_t DotPos = Name.rfind('.');
if (DotPos != StringRef::npos)
Name = Name.substr(DotPos+1);
Out.indent(Indent) << Name;
// Print requirements.
if (!ConformsTo.empty()) {
Out << " : ";
if (ConformsTo.size() != 1)
Out << "protocol<";
bool First = true;
for (auto Proto : ConformsTo) {
if (First)
First = false;
else
Out << ", ";
Out << Proto->getName().str();
}
if (ConformsTo.size() != 1)
Out << ">";
}
Out << "\n";
// Print nested types.
for (const auto &Nested : NestedTypes) {
Nested.second->dump(Out, Indent + 2);
}
}
};
struct ArchetypeBuilder::Implementation {
SmallVector<TypeAliasDecl *, 4> GenericParams;
DenseMap<TypeAliasDecl *, PotentialArchetype *> PotentialArchetypes;
};
ArchetypeBuilder::ArchetypeBuilder(TypeChecker &TC)
: TC(TC), Impl(new Implementation)
{
}
ArchetypeBuilder::~ArchetypeBuilder() {
for (auto PA : Impl->PotentialArchetypes)
delete PA.second;
}
auto ArchetypeBuilder::resolveType(Type T) -> PotentialArchetype * {
auto IdType = dyn_cast<IdentifierType>(T);
if (!IdType)
return nullptr;
PotentialArchetype *Current = nullptr;
if (!IdType->Components[0].Value.is<ValueDecl *>())
return nullptr;
// The first type needs to be known as a potential archetype, e.g., a
// generic parameter.
TypeAliasDecl *FirstType
= dyn_cast<TypeAliasDecl>(IdType->Components[0].Value.get<ValueDecl *>());
if (!FirstType)
return nullptr;
DenseMap<TypeAliasDecl *, PotentialArchetype *>::iterator Known
= Impl->PotentialArchetypes.find(FirstType);
if (Known == Impl->PotentialArchetypes.end())
return nullptr;
// Resolve nested types.
Current = Known->second;
for (unsigned I = 1, N = IdType->Components.size(); I != N; ++I) {
Current = Current->getNestedType(IdType->Components[I].Id);
}
return Current;
}
bool ArchetypeBuilder::addGenericParameter(TypeAliasDecl *GenericParam,
Optional<unsigned> Index) {
Impl->GenericParams.push_back(GenericParam);
// Create a potential archetype for this generic parameter.
assert(!Impl->PotentialArchetypes[GenericParam]);
auto PA = new PotentialArchetype(GenericParam->getName().str(), Index);
Impl->PotentialArchetypes[GenericParam] = PA;
// Add each of the requirements placed on this generic parameter.
for (auto Inherited : GenericParam->getInherited()) {
SmallVector<ProtocolDecl *, 4> ConformsTo;
if (Inherited.getType()->isExistentialType(ConformsTo)) {
for (auto Proto : ConformsTo)
if (addConformanceRequirement(PA, Proto))
return true;
}
}
return false;
}
bool ArchetypeBuilder::addConformanceRequirement(PotentialArchetype *T,
ProtocolDecl *Proto){
// If we've already added this requirement, we're done.
if (!T->ConformsTo.insert(Proto))
return false;
// Add all of the inherited protocol requirements, recursively.
for (auto Inherited : Proto->getInherited()) {
SmallVector<ProtocolDecl *, 4> InheritedProtos;
if (Inherited.getType()->isExistentialType(InheritedProtos)) {
for (auto InheritedProto : InheritedProtos) {
if (addConformanceRequirement(T, InheritedProto))
return true;
}
}
}
// Add requirements for each of the associated types.
for (auto Member : Proto->getMembers()) {
if (auto AssocType = dyn_cast<TypeAliasDecl>(Member)) {
// FIXME: Another 'This' hack.
if (AssocType->getName().str() == "This")
continue;
// Add requirements placed directly on this associated type.
auto AssocPA = T->getNestedType(AssocType->getName());
for (auto Inherited : AssocType->getInherited()) {
SmallVector<ProtocolDecl *, 4> InheritedProtos;
if (Inherited.getType()->isExistentialType(InheritedProtos)) {
for (auto InheritedProto : InheritedProtos) {
if (addConformanceRequirement(AssocPA, InheritedProto))
return true;
}
}
}
continue;
}
// FIXME: Requirement declarations.
}
return false;
}
bool ArchetypeBuilder::addRequirement(const Requirement &Req) {
switch (Req.getKind()) {
case RequirementKind::Conformance: {
PotentialArchetype *PA = resolveType(Req.getSubject());
if (!PA) {
// FIXME: Diagnose this failure.
return true;
}
SmallVector<ProtocolDecl *, 4> ConformsTo;
if (!Req.getProtocol()->isExistentialType(ConformsTo)) {
// FIXME: Diagnose this failure here, rather than over in type-checking.
return true;
}
// Add each of the protocols.
for (auto Proto : ConformsTo)
if (addConformanceRequirement(PA, Proto))
return true;
return false;
}
case RequirementKind::SameType: {
// FIXME: Implement same-type constraints.
return false;
}
}
llvm_unreachable("Unhandled requirement?");
}
llvm::DenseMap<TypeAliasDecl *, ArchetypeType *>
ArchetypeBuilder::assignArchetypes() {
llvm::DenseMap<TypeAliasDecl *, ArchetypeType *> Archetypes;
for (const auto& PA : Impl->PotentialArchetypes) {
Archetypes[PA.first] = PA.second->getArchetype(TC);
}
return std::move(Archetypes);
}
void ArchetypeBuilder::dump() {
llvm::errs() << "Archetypes to build:\n";
for (const auto& PA : Impl->PotentialArchetypes) {
PA.second->dump(llvm::errs(), 2);
}
}
<|endoftext|> |
<commit_before>// from lib/THC/THCTensorMasked.cu:
#include "THClTensorMath.h"
#include "THClGeneral.h"
#include "THClBlas.h"
#include "THClTensorCopy.h"
//#include "THClTensorRandom.h"
#include "THClApply.h"
#include "THClReduce.h"
// #include <thrust/device_ptr.h>
// #include <thrust/fill.h>
// #include <thrust/functional.h>
// #include <thrust/reduce.h>
// #include <thrust/inner_product.h>
// The largest consecutive integer representable in float32 (2^24)
#define FLOAT32_MAX_CONSECUTIVE_INT 16777216.0f
class TensorMaskedFillOp : public HasOperator2, public HasScalars {
public:
int getNumScalars() const { return 1; }
float getScalar( int index ) const { return value; }
TensorMaskedFillOp(float v) : value(v) {}
std::string operator2() const {
return "if( *in1 != 0.0f ) { *out = val1; }";
}
// void operator()(float* t, float* mask) {
// // Really mask should be `0` or `1` but we can't propagate errors here.
// if (*mask != 0.0f) {
// *t = value;
// }
// }
float value;
};
//struct TensorMaskedCopyOp {
// TensorMaskedCopyOp(float* s, float* bm, float* ps)
// : src(s),
// baseMask(bm),
// maskPrefixSum(ps) {
// }
// /*__device__*/ /*__forceline__*/ void operator()(float* out, float* mask) {
// // Really mask should be `0` or `1` but we can't propagate errors here.
// if (*mask != 0.0f) {
// // We've already checked that this offset is <= 2^24, so this is ok.
// int srcOffset = (int) (mask - baseMask);
// *out = src[(int) maskPrefixSum[srcOffset]];
// }
// }
// // Where we are copying from
// float* src;
// // The base address of mask so we can calculate offset
// float* baseMask;
// // The index we are copying from
// float* maskPrefixSum;
//};
//class TensorMaskedSelectOp : public HasOperator3, public HasScalars {
//public:
// int getNumScalars() const { return 1; }
// string operator3() const {
// return "if(*out != 0.0f){out[(int)*in1] = *in2; }";
// }
// TensorMaskedSelectOp(float* t) : out(t) {}
// void operator()(float* mask, float* maskPrefixSum, float* in) {
// // Really mask should be `0` or `1` but we can't propagate errors here.
// if (*mask != 0.0f) {
// out[(int) *maskPrefixSum] = *in;
// }
// }
// float* out;
//};
void THClTensor_maskedFill(THClState* state,
THClTensor *tensor, THClTensor *mask, float value)
{
THAssert(THClTensor_checkGPU(state, 2, tensor, mask));
THArgCheck(THClTensor_nElement(state, tensor) ==
THClTensor_nElement(state, mask),
2, "sizes do not match");
if (!THClTensor_pointwiseApply2(state, tensor, mask, TensorMaskedFillOp(value))) {
THArgCheck(false, 2, CLTORCH_DIM_WARNING);
}
}
//void THClTensor_maskedCopy(THClState* state,
// THClTensor *tensor, THClTensor *mask, THClTensor *src)
//{
// THAssert(THClTensor_checkGPU(state, 3, tensor, src, mask));
// long maskSize = THClTensor_nElement(state, mask);
// long tensorSize = THClTensor_nElement(state, tensor);
// long srcSize = THClTensor_nElement(state, src);
// // Since we are performing a prefix sum of mask, it cannot exceed
// // the size allowed in consecutive integers in float32
// THArgCheck(maskSize <= (long) FLOAT32_MAX_CONSECUTIVE_INT,
// 3, "mask nElements exceeds single-precision float "
// "consecutive integer precision size (2^24)");
// // `mask` and `tensor` must have the same number of elements
// THArgCheck(maskSize == tensorSize, 2,
// "mask and tensor must have the same number of elements");
// THClTensor* contigMask = THClTensor_newContiguous(state, mask);
// long oneElements = (long) THClTensor_sumall(state, contigMask);
// // The number of `1` elements present in the mask must be <= the
// // number of elements available in `src`
// if (oneElements > srcSize) {
// THClTensor_free(state, contigMask);
// THArgCheck(false, 2, "source nElements must be == mask `1` elements");
// }
// // Use a prefix sum to determine the copy locations of the masked elements
// THClTensor* maskPrefixSum = THClTensor_new(state);
// THClTensor_resizeAs(state, maskPrefixSum, contigMask);
// // We are getting elements from `src` based on an offset from
// // `maskPrefixSum`, so that should be made contiguous too
// THClTensor* contigSrc = THClTensor_newContiguous(state, src);
//// thrust::device_ptr<float>
// maskData(THClTensor_data(state, contigMask));
//// thrust::device_ptr<float>
// maskPrefixSumData(THClTensor_data(state, maskPrefixSum));
//// thrust::exclusive_scan(maskData,
// maskData + THClTensor_nElement(state, contigMask),
// maskPrefixSumData);
// // update `tensor` where `mask` == 1 but pull from `src` at
// // maskPrefixSum
// bool status = THClTensor_pointwiseApply2(
// state, tensor, contigMask,
// TensorMaskedCopyOp(THClTensor_data(state, contigSrc),
// THClTensor_data(state, contigMask),
// THClTensor_data(state, maskPrefixSum)));
// THClTensor_free(state, contigSrc);
// THClTensor_free(state, maskPrefixSum);
// THClTensor_free(state, contigMask);
// THArgCheck(status, 2, CLTORCH_DIM_WARNING);
// THError("Not implemented");
//}
//void THClTensor_maskedSelect(THClState* state,
// THClTensor *tensor, THClTensor *src, THClTensor *mask)
//{
// THAssert(THClTensor_checkGPU(state, 3, tensor, src, mask));
// THArgCheck(THClTensor_nElement(state, mask) == THClTensor_nElement(state, src),
// 2, "sizes do not match");
// // Since we are performing a prefix sum of mask, it cannot exceed
// // the size allowed in consecutive integers in float32
// THArgCheck(THClTensor_nElement(state, mask) <=
// (long) FLOAT32_MAX_CONSECUTIVE_INT,
// 3, "mask nElements exceeds single-precision float "
// "consecutive integer precision size (2^24)");
// // Determine our output size
// THClTensor* contigMask = THClTensor_newContiguous(state, mask);
// long totalElements = (long) THClTensor_sumall(state, contigMask);
// // This should be contiguous already, so no need to make it contig
// // for the apply kernel
// THClTensor_resize1d(state, tensor, totalElements);
// // Use a prefix sum to determine the output locations of the masked elements
// THClTensor* maskPrefixSum = THClTensor_new(state);
// THClTensor_resizeAs(state, maskPrefixSum, contigMask);
//// thrust::device_ptr<float>
// maskData(THClTensor_data(state, contigMask));
//// thrust::device_ptr<float>
// maskPrefixSumData(THClTensor_data(state, maskPrefixSum));
//// thrust::exclusive_scan(maskData,
// maskData + THClTensor_nElement(state, contigMask),
// maskPrefixSumData);
// // Then copy over the masked elements at their desired output index
// bool status = THClTensor_pointwiseApply3(
// state, contigMask, maskPrefixSum,
// src, TensorMaskedSelectOp(THClTensor_data(state, tensor)));
// THClTensor_free(state, contigMask);
// THClTensor_free(state, maskPrefixSum);
// THArgCheck(status, 2, CLTORCH_DIM_WARNING);
// THError("Not implemented");
//}
//void THClTensor_maskedFillByte(THClState* state, THClTensor *tensor, THByteTensor *mask, float value)
//{
// THAssert(THClTensor_checkGPU(state, 1, tensor));
// THLongStorage* maskSize = THByteTensor_newSizeOf(mask);
// THClTensor* maskCl = THClTensor_newWithSize(state, maskSize, NULL);
// THLongStorage_free(maskSize);
// THClTensor_copyByte(state, maskCl, mask);
// THClTensor_maskedFill(state, tensor, maskCl, value);
// THClTensor_free(state, maskCl);
//}
//void THClTensor_maskedCopyByte(THClState* state, THClTensor *tensor, THByteTensor *mask, THClTensor *src)
//{
// THAssert(THClTensor_checkGPU(state, 2, tensor, src));
// THLongStorage* maskSize = THByteTensor_newSizeOf(mask);
// THClTensor* maskCl = THClTensor_newWithSize(state, maskSize, NULL);
// THLongStorage_free(maskSize);
// THClTensor_copyByte(state, maskCl, mask);
// THClTensor_maskedCopy(state, tensor, maskCl, src);
// THClTensor_free(state, maskCl);
//}
//void THClTensor_maskedSelectByte(THClState* state, THClTensor *tensor, THClTensor *src, THByteTensor *mask)
//{
// THAssert(THClTensor_checkGPU(state, 2, tensor, src));
// THLongStorage* maskSize = THByteTensor_newSizeOf(mask);
// THClTensor* maskCl = THClTensor_newWithSize(state, maskSize, NULL);
// THLongStorage_free(maskSize);
// THClTensor_copyByte(state, maskCl, mask);
// THClTensor_maskedSelect(state, tensor, src, maskCl);
// THClTensor_free(state, maskCl);
//}
<commit_msg>remove some dead code<commit_after>// from lib/THC/THCTensorMasked.cu:
#include "THClTensorMath.h"
#include "THClGeneral.h"
#include "THClBlas.h"
#include "THClTensorCopy.h"
//#include "THClTensorRandom.h"
#include "THClApply.h"
#include "THClReduce.h"
// The largest consecutive integer representable in float32 (2^24)
#define FLOAT32_MAX_CONSECUTIVE_INT 16777216.0f
class TensorMaskedFillOp : public HasOperator2, public HasScalars {
public:
int getNumScalars() const { return 1; }
float getScalar( int index ) const { return value; }
TensorMaskedFillOp(float v) : value(v) {}
std::string operator2() const {
return "if( *in1 != 0.0f ) { *out = val1; }";
}
float value;
};
//struct TensorMaskedCopyOp {
// TensorMaskedCopyOp(float* s, float* bm, float* ps)
// : src(s),
// baseMask(bm),
// maskPrefixSum(ps) {
// }
// /*__device__*/ /*__forceline__*/ void operator()(float* out, float* mask) {
// // Really mask should be `0` or `1` but we can't propagate errors here.
// if (*mask != 0.0f) {
// // We've already checked that this offset is <= 2^24, so this is ok.
// int srcOffset = (int) (mask - baseMask);
// *out = src[(int) maskPrefixSum[srcOffset]];
// }
// }
// // Where we are copying from
// float* src;
// // The base address of mask so we can calculate offset
// float* baseMask;
// // The index we are copying from
// float* maskPrefixSum;
//};
//class TensorMaskedSelectOp : public HasOperator3, public HasScalars {
//public:
// int getNumScalars() const { return 1; }
// string operator3() const {
// return "if(*out != 0.0f){out[(int)*in1] = *in2; }";
// }
// TensorMaskedSelectOp(float* t) : out(t) {}
// void operator()(float* mask, float* maskPrefixSum, float* in) {
// // Really mask should be `0` or `1` but we can't propagate errors here.
// if (*mask != 0.0f) {
// out[(int) *maskPrefixSum] = *in;
// }
// }
// float* out;
//};
void THClTensor_maskedFill(THClState* state,
THClTensor *tensor, THClTensor *mask, float value)
{
THAssert(THClTensor_checkGPU(state, 2, tensor, mask));
THArgCheck(THClTensor_nElement(state, tensor) ==
THClTensor_nElement(state, mask),
2, "sizes do not match");
if (!THClTensor_pointwiseApply2(state, tensor, mask, TensorMaskedFillOp(value))) {
THArgCheck(false, 2, CLTORCH_DIM_WARNING);
}
}
//void THClTensor_maskedCopy(THClState* state,
// THClTensor *tensor, THClTensor *mask, THClTensor *src)
//{
// THAssert(THClTensor_checkGPU(state, 3, tensor, src, mask));
// long maskSize = THClTensor_nElement(state, mask);
// long tensorSize = THClTensor_nElement(state, tensor);
// long srcSize = THClTensor_nElement(state, src);
// // Since we are performing a prefix sum of mask, it cannot exceed
// // the size allowed in consecutive integers in float32
// THArgCheck(maskSize <= (long) FLOAT32_MAX_CONSECUTIVE_INT,
// 3, "mask nElements exceeds single-precision float "
// "consecutive integer precision size (2^24)");
// // `mask` and `tensor` must have the same number of elements
// THArgCheck(maskSize == tensorSize, 2,
// "mask and tensor must have the same number of elements");
// THClTensor* contigMask = THClTensor_newContiguous(state, mask);
// long oneElements = (long) THClTensor_sumall(state, contigMask);
// // The number of `1` elements present in the mask must be <= the
// // number of elements available in `src`
// if (oneElements > srcSize) {
// THClTensor_free(state, contigMask);
// THArgCheck(false, 2, "source nElements must be == mask `1` elements");
// }
// // Use a prefix sum to determine the copy locations of the masked elements
// THClTensor* maskPrefixSum = THClTensor_new(state);
// THClTensor_resizeAs(state, maskPrefixSum, contigMask);
// // We are getting elements from `src` based on an offset from
// // `maskPrefixSum`, so that should be made contiguous too
// THClTensor* contigSrc = THClTensor_newContiguous(state, src);
//// thrust::device_ptr<float>
// maskData(THClTensor_data(state, contigMask));
//// thrust::device_ptr<float>
// maskPrefixSumData(THClTensor_data(state, maskPrefixSum));
//// thrust::exclusive_scan(maskData,
// maskData + THClTensor_nElement(state, contigMask),
// maskPrefixSumData);
// // update `tensor` where `mask` == 1 but pull from `src` at
// // maskPrefixSum
// bool status = THClTensor_pointwiseApply2(
// state, tensor, contigMask,
// TensorMaskedCopyOp(THClTensor_data(state, contigSrc),
// THClTensor_data(state, contigMask),
// THClTensor_data(state, maskPrefixSum)));
// THClTensor_free(state, contigSrc);
// THClTensor_free(state, maskPrefixSum);
// THClTensor_free(state, contigMask);
// THArgCheck(status, 2, CLTORCH_DIM_WARNING);
// THError("Not implemented");
//}
//void THClTensor_maskedSelect(THClState* state,
// THClTensor *tensor, THClTensor *src, THClTensor *mask)
//{
// THAssert(THClTensor_checkGPU(state, 3, tensor, src, mask));
// THArgCheck(THClTensor_nElement(state, mask) == THClTensor_nElement(state, src),
// 2, "sizes do not match");
// // Since we are performing a prefix sum of mask, it cannot exceed
// // the size allowed in consecutive integers in float32
// THArgCheck(THClTensor_nElement(state, mask) <=
// (long) FLOAT32_MAX_CONSECUTIVE_INT,
// 3, "mask nElements exceeds single-precision float "
// "consecutive integer precision size (2^24)");
// // Determine our output size
// THClTensor* contigMask = THClTensor_newContiguous(state, mask);
// long totalElements = (long) THClTensor_sumall(state, contigMask);
// // This should be contiguous already, so no need to make it contig
// // for the apply kernel
// THClTensor_resize1d(state, tensor, totalElements);
// // Use a prefix sum to determine the output locations of the masked elements
// THClTensor* maskPrefixSum = THClTensor_new(state);
// THClTensor_resizeAs(state, maskPrefixSum, contigMask);
//// thrust::device_ptr<float>
// maskData(THClTensor_data(state, contigMask));
//// thrust::device_ptr<float>
// maskPrefixSumData(THClTensor_data(state, maskPrefixSum));
//// thrust::exclusive_scan(maskData,
// maskData + THClTensor_nElement(state, contigMask),
// maskPrefixSumData);
// // Then copy over the masked elements at their desired output index
// bool status = THClTensor_pointwiseApply3(
// state, contigMask, maskPrefixSum,
// src, TensorMaskedSelectOp(THClTensor_data(state, tensor)));
// THClTensor_free(state, contigMask);
// THClTensor_free(state, maskPrefixSum);
// THArgCheck(status, 2, CLTORCH_DIM_WARNING);
// THError("Not implemented");
//}
//void THClTensor_maskedFillByte(THClState* state, THClTensor *tensor, THByteTensor *mask, float value)
//{
// THAssert(THClTensor_checkGPU(state, 1, tensor));
// THLongStorage* maskSize = THByteTensor_newSizeOf(mask);
// THClTensor* maskCl = THClTensor_newWithSize(state, maskSize, NULL);
// THLongStorage_free(maskSize);
// THClTensor_copyByte(state, maskCl, mask);
// THClTensor_maskedFill(state, tensor, maskCl, value);
// THClTensor_free(state, maskCl);
//}
//void THClTensor_maskedCopyByte(THClState* state, THClTensor *tensor, THByteTensor *mask, THClTensor *src)
//{
// THAssert(THClTensor_checkGPU(state, 2, tensor, src));
// THLongStorage* maskSize = THByteTensor_newSizeOf(mask);
// THClTensor* maskCl = THClTensor_newWithSize(state, maskSize, NULL);
// THLongStorage_free(maskSize);
// THClTensor_copyByte(state, maskCl, mask);
// THClTensor_maskedCopy(state, tensor, maskCl, src);
// THClTensor_free(state, maskCl);
//}
//void THClTensor_maskedSelectByte(THClState* state, THClTensor *tensor, THClTensor *src, THByteTensor *mask)
//{
// THAssert(THClTensor_checkGPU(state, 2, tensor, src));
// THLongStorage* maskSize = THByteTensor_newSizeOf(mask);
// THClTensor* maskCl = THClTensor_newWithSize(state, maskSize, NULL);
// THLongStorage_free(maskSize);
// THClTensor_copyByte(state, maskCl, mask);
// THClTensor_maskedSelect(state, tensor, src, maskCl);
// THClTensor_free(state, maskCl);
//}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007 Tobias Koenig <tokoe@kde.org>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "kabcmodel.h"
#include <kabc/addressee.h>
#include <kabc/contactgroup.h>
#include <kicon.h>
#include <klocale.h>
#include <akonadi/item.h>
#include <akonadi/itemfetchjob.h>
#include <akonadi/itemfetchscope.h>
#include <akonadi/collection.h>
using namespace Akonadi;
class KABCModel::Private
{
public:
};
KABCModel::KABCModel( QObject *parent )
: Akonadi::ItemModel( parent ),
d( new Private() )
{
fetchScope().fetchFullPayload();
}
KABCModel::~KABCModel()
{
delete d;
}
QStringList KABCModel::mimeTypes() const
{
return QStringList()
<< QLatin1String("text/uri-list")
<< KABC::Addressee::mimeType();
}
int KABCModel::rowCount( const QModelIndex& ) const
{
if ( !collection().contentMimeTypes().contains( KABC::Addressee::mimeType() ) )
return 1;
return ItemModel::rowCount();
}
int KABCModel::columnCount( const QModelIndex& ) const
{
if ( !collection().contentMimeTypes().contains( KABC::Addressee::mimeType() ) )
return 1;
return 4;
}
QVariant KABCModel::data( const QModelIndex &index, int role ) const
{
// pass through the queries for ItemModel
if ( role == ItemModel::IdRole || role == ItemModel::MimeTypeRole )
return ItemModel::data( index, role );
if ( !index.isValid() )
return QVariant();
if ( index.row() >= rowCount() )
return QVariant();
if ( !collection().contentMimeTypes().contains( KABC::Addressee::mimeType() ) ) {
if ( role == Qt::DisplayRole )
// FIXME: i18n when strings unfreeze for 4.4
return QString::fromLatin1( "This model can only handle contact folders. The current collection holds mimetypes: %1").arg(
collection().contentMimeTypes().join( QLatin1String(",") ) );
return QVariant();
}
const Item item = itemForIndex( index );
if ( item.mimeType() == KABC::Addressee::mimeType() ) {
if ( !item.hasPayload<KABC::Addressee>() )
return QVariant();
const KABC::Addressee addr = item.payload<KABC::Addressee>();
if ( role == Qt::DecorationRole ) {
if ( index.column() == 0 ) {
const KABC::Picture picture = addr.photo();
if ( picture.isIntern() ) {
return picture.data().scaled( QSize( 16, 16 ) );
} else {
return KIcon( QLatin1String( "x-office-contact" ) );
}
}
return QVariant();
} else if ( role == Qt::DisplayRole ) {
switch ( index.column() ) {
case 0:
if ( !addr.formattedName().isEmpty() )
return addr.formattedName();
else
return addr.assembledName();
case 1:
return addr.givenName();
break;
case 2:
return addr.familyName();
break;
case 3:
return addr.preferredEmail();
break;
default:
break;
}
}
} else if ( item.mimeType() == KABC::ContactGroup::mimeType() ) {
if ( !item.hasPayload<KABC::ContactGroup>() )
return QVariant();
if ( role == Qt::DecorationRole ) {
if ( index.column() == 0 )
return KIcon( QLatin1String( "x-mail-distribution-list" ) );
else
return QVariant();
} else if ( role == Qt::DisplayRole ) {
switch ( index.column() ) {
case 0:
{
const KABC::ContactGroup group = item.payload<KABC::ContactGroup>();
return group.name();
}
break;
default:
break;
}
}
}
return QVariant();
}
QVariant KABCModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
if ( role != Qt::DisplayRole )
return QVariant();
if ( orientation != Qt::Horizontal )
return QVariant();
if ( !collection().contentMimeTypes().contains( KABC::Addressee::mimeType() ) )
return QVariant();
switch ( section ) {
case 0:
return i18nc( "@title:column, name of a person", "Name" );
break;
case 1:
return KABC::Addressee::givenNameLabel();
break;
case 2:
return KABC::Addressee::familyNameLabel();
break;
case 3:
return KABC::Addressee::emailLabel();
break;
default:
break;
}
return QVariant();
}
<commit_msg>Make the kabc model deal with the no-content and invalid collection cases as well.<commit_after>/*
Copyright (c) 2007 Tobias Koenig <tokoe@kde.org>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "kabcmodel.h"
#include <kabc/addressee.h>
#include <kabc/contactgroup.h>
#include <kicon.h>
#include <klocale.h>
#include <akonadi/item.h>
#include <akonadi/itemfetchjob.h>
#include <akonadi/itemfetchscope.h>
#include <akonadi/collection.h>
using namespace Akonadi;
class KABCModel::Private
{
public:
bool collectionIsValid( const Collection& collection )
{
return !collection.isValid()
|| collection.contentMimeTypes().contains( KABC::Addressee::mimeType() )
|| collection.contentMimeTypes() == QStringList( QLatin1String("inode/directory") );
}
};
KABCModel::KABCModel( QObject *parent )
: Akonadi::ItemModel( parent ),
d( new Private() )
{
fetchScope().fetchFullPayload();
}
KABCModel::~KABCModel()
{
delete d;
}
QStringList KABCModel::mimeTypes() const
{
return QStringList()
<< QLatin1String("text/uri-list")
<< KABC::Addressee::mimeType();
}
int KABCModel::rowCount( const QModelIndex& ) const
{
if ( !d->collectionIsValid( collection() ) )
return 1;
return ItemModel::rowCount();
}
int KABCModel::columnCount( const QModelIndex& ) const
{
if ( !d->collectionIsValid( collection() ) )
return 1;
return 4;
}
QVariant KABCModel::data( const QModelIndex &index, int role ) const
{
// pass through the queries for ItemModel
if ( role == ItemModel::IdRole || role == ItemModel::MimeTypeRole )
return ItemModel::data( index, role );
if ( !index.isValid() )
return QVariant();
if ( index.row() >= rowCount() )
return QVariant();
if ( !d->collectionIsValid( collection() ) )
if ( role == Qt::DisplayRole )
// FIXME: i18n when strings unfreeze for 4.4
return QString::fromLatin1( "This model can only handle contact folders. The current collection holds mimetypes: %1").arg(
collection().contentMimeTypes().join( QLatin1String(",") ) );
return QVariant();
}
const Item item = itemForIndex( index );
if ( item.mimeType() == KABC::Addressee::mimeType() ) {
if ( !item.hasPayload<KABC::Addressee>() )
return QVariant();
const KABC::Addressee addr = item.payload<KABC::Addressee>();
if ( role == Qt::DecorationRole ) {
if ( index.column() == 0 ) {
const KABC::Picture picture = addr.photo();
if ( picture.isIntern() ) {
return picture.data().scaled( QSize( 16, 16 ) );
} else {
return KIcon( QLatin1String( "x-office-contact" ) );
}
}
return QVariant();
} else if ( role == Qt::DisplayRole ) {
switch ( index.column() ) {
case 0:
if ( !addr.formattedName().isEmpty() )
return addr.formattedName();
else
return addr.assembledName();
case 1:
return addr.givenName();
break;
case 2:
return addr.familyName();
break;
case 3:
return addr.preferredEmail();
break;
default:
break;
}
}
} else if ( item.mimeType() == KABC::ContactGroup::mimeType() ) {
if ( !item.hasPayload<KABC::ContactGroup>() )
return QVariant();
if ( role == Qt::DecorationRole ) {
if ( index.column() == 0 )
return KIcon( QLatin1String( "x-mail-distribution-list" ) );
else
return QVariant();
} else if ( role == Qt::DisplayRole ) {
switch ( index.column() ) {
case 0:
{
const KABC::ContactGroup group = item.payload<KABC::ContactGroup>();
return group.name();
}
break;
default:
break;
}
}
}
return QVariant();
}
QVariant KABCModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
if ( role != Qt::DisplayRole )
return QVariant();
if ( orientation != Qt::Horizontal )
return QVariant();
if ( !d->collectionIsValid( collection() ) )
return QVariant();
switch ( section ) {
case 0:
return i18nc( "@title:column, name of a person", "Name" );
break;
case 1:
return KABC::Addressee::givenNameLabel();
break;
case 2:
return KABC::Addressee::familyNameLabel();
break;
case 3:
return KABC::Addressee::emailLabel();
break;
default:
break;
}
return QVariant();
}
<|endoftext|> |
<commit_before>/*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __transformixlib_CXX_
#define __transformixlib_CXX_
#include "transformixlib.h"
#ifdef _ELASTIX_USE_MEVISDICOMTIFF
#include "itkUseMevisDicomTiff.h"
#endif
#include "elxTransformixMain.h"
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include "itkObject.h"
#include "itkDataObject.h"
#include <itksys/SystemTools.hxx>
#include <itksys/SystemInformation.hxx>
#include "elxTimer.h"
namespace transformix
{
/**
* ******************* Constructor ***********************
*/
TRANSFORMIX::TRANSFORMIX()
{
this->m_ResultImage = 0;
} // end Constructor
/**
* ******************* Destructor ***********************
*/
TRANSFORMIX::~TRANSFORMIX()
{
this->m_ResultImage = 0;
} // end Destructor
/**
* ******************* Destructor ***********************
*/
TRANSFORMIX::ImagePointer
TRANSFORMIX::GetResultImage( void )
{
return this->m_ResultImage;
}
/**
* ******************* TransformImage ***********************
*/
int
TRANSFORMIX::TransformImage(
ImagePointer inputImage,
ParameterMapType & parameterMap,
std::string outputPath,
bool performLogging,
bool performCout )
{
/** Some typedef's.*/
typedef elx::TransformixMain TransformixMainType;
typedef TransformixMainType::Pointer TransformixMainPointer;
typedef TransformixMainType::ArgumentMapType ArgumentMapType;
typedef ArgumentMapType::value_type ArgumentMapEntryType;
typedef elx::ElastixMain ElastixMainType;
typedef ElastixMainType::DataObjectContainerType DataObjectContainerType;
typedef ElastixMainType::DataObjectContainerPointer DataObjectContainerPointer;
/** Declare an instance of the Transformix class. */
TransformixMainPointer transformix;
DataObjectContainerPointer movingImageContainer = 0;
DataObjectContainerPointer ResultImageContainer = 0;
/** Initialize. */
int returndummy = 0;
ArgumentMapType argMap;
bool outFolderPresent = false;
std::string outFolder = "";
std::string logFileName = "";
std::string key;
std::string value;
if( !outputPath.empty() )
{
key = "-out";
value = outputPath;
/** Make sure that last character of the output folder equals a '/'. */
if( value.find_last_of( "/" ) != value.size() -1 )
{
value.append("/");
}
outFolderPresent = true;
}
else
{
/** Put command line parameters into parameterFileList. */
//there must be an "-out", this is checked later in code!!
key = "-out";
value = "output_path_not_set";
}
/** Save this information. */
outFolder = value;
/** Attempt to save the arguments in the ArgumentMap. */
if( argMap.count( key ) == 0 )
{
argMap.insert( ArgumentMapEntryType( key.c_str(), value.c_str() ) );
}
else if( performCout )
{
/** Duplicate arguments. */
std::cerr << "WARNING!" << std::endl;
std::cerr << "Argument "<< key.c_str() << "is only required once." << std::endl;
std::cerr << "Arguments " << key.c_str() << " " << value.c_str() << "are ignored" << std::endl;
}
if( performLogging )
{
/** Check if the output directory exists. */
bool outFolderExists = itksys::SystemTools::FileIsDirectory( outFolder.c_str() );
if( !outFolderExists )
{
if( performCout )
{
std::cerr << "ERROR: the output directory does not exist." << std::endl;
std::cerr << "You are responsible for creating it." << std::endl;
}
return( -2 );
}
else
{
/** Setup xout. */
if( performLogging )
{
logFileName = outFolder + "transformix.log";
}
}
}
/** The argv0 argument, required for finding the component.dll/so's. */
argMap.insert( ArgumentMapEntryType( "-argv0", "transformix" ) );
/** Setup xout. */
int returndummy2 = elx::xoutSetup( logFileName.c_str() , performLogging , performCout );
if( returndummy2 && performCout )
{
if( performCout )
{
std::cerr << "ERROR while setting up xout." << std::endl;
}
return( returndummy2 );
}
elxout << std::endl;
/** Declare a timer, start it and print the start time. */
tmr::Timer::Pointer totaltimer = tmr::Timer::New();
totaltimer->StartTimer();
elxout << "transformix is started at " << totaltimer->PrintStartTime()
<< ".\n" << std::endl;
/**
* ********************* START TRANSFORMATION *******************
*/
/** Set transformix. */
transformix = TransformixMainType::New();
/** Set stuff from input or needed for output */
movingImageContainer = DataObjectContainerType::New();
movingImageContainer->CreateElementAt( 0 ) = inputImage;
transformix->SetMovingImageContainer( movingImageContainer );
transformix->SetResultImageContainer( ResultImageContainer );
/** Run transformix. */
returndummy = transformix->Run( argMap, parameterMap );
/** Check if transformix run without errors. */
if ( returndummy != 0 )
{
xl::xout["error"] << "Errors occurred" << std::endl;
return returndummy;
}
/** Get the result image */
ResultImageContainer = transformix->GetResultImageContainer();
/** Stop timer and print it. */
totaltimer->StopTimer();
elxout << "\nTransformix has finished at " <<
totaltimer->PrintStopTime() << "." << std::endl;
elxout << "Elapsed time: " <<
totaltimer->PrintElapsedTimeDHMS() << ".\n" << std::endl;
this->m_ResultImage = ResultImageContainer->ElementAt( 0 );
/** Clean up. */
transformix = 0;
TransformixMainType::UnloadComponents();
/** Exit and return the error code. */
return returndummy;
} // end TransformImage()
} // namespace transformix
#endif // end #ifndef __transformixlib_CXX_
<commit_msg>KH<commit_after>/*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __transformixlib_CXX_
#define __transformixlib_CXX_
#include "transformixlib.h"
#ifdef _ELASTIX_USE_MEVISDICOMTIFF
#include "itkUseMevisDicomTiff.h"
#endif
#include "elxTransformixMain.h"
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include "itkObject.h"
#include "itkDataObject.h"
#include <itksys/SystemTools.hxx>
#include <itksys/SystemInformation.hxx>
#include "elxTimer.h"
namespace transformix
{
/**
* ******************* Constructor ***********************
*/
TRANSFORMIX::TRANSFORMIX()
{
this->m_ResultImage = 0;
} // end Constructor
/**
* ******************* Destructor ***********************
*/
TRANSFORMIX::~TRANSFORMIX()
{
this->m_ResultImage = 0;
} // end Destructor
/**
* ******************* GetResultImage ***********************
*/
TRANSFORMIX::ImagePointer
TRANSFORMIX::GetResultImage( void )
{
return this->m_ResultImage;
}
/**
* ******************* TransformImage ***********************
*/
int
TRANSFORMIX::TransformImage(
ImagePointer inputImage,
ParameterMapType & parameterMap,
std::string outputPath,
bool performLogging,
bool performCout )
{
/** Some typedef's.*/
typedef elx::TransformixMain TransformixMainType;
typedef TransformixMainType::Pointer TransformixMainPointer;
typedef TransformixMainType::ArgumentMapType ArgumentMapType;
typedef ArgumentMapType::value_type ArgumentMapEntryType;
typedef elx::ElastixMain ElastixMainType;
typedef ElastixMainType::DataObjectContainerType DataObjectContainerType;
typedef ElastixMainType::DataObjectContainerPointer DataObjectContainerPointer;
/** Declare an instance of the Transformix class. */
TransformixMainPointer transformix;
DataObjectContainerPointer movingImageContainer = 0;
DataObjectContainerPointer ResultImageContainer = 0;
/** Initialize. */
int returndummy = 0;
ArgumentMapType argMap;
bool outFolderPresent = false;
std::string outFolder = "";
std::string logFileName = "";
std::string key;
std::string value;
if( !outputPath.empty() )
{
key = "-out";
value = outputPath;
/** Make sure that last character of the output folder equals a '/'. */
if( value.find_last_of( "/" ) != value.size() -1 )
{
value.append("/");
}
outFolderPresent = true;
}
else
{
/** Put command line parameters into parameterFileList. */
//there must be an "-out", this is checked later in code!!
key = "-out";
value = "output_path_not_set";
}
/** Save this information. */
outFolder = value;
/** Attempt to save the arguments in the ArgumentMap. */
if( argMap.count( key ) == 0 )
{
argMap.insert( ArgumentMapEntryType( key.c_str(), value.c_str() ) );
}
else if( performCout )
{
/** Duplicate arguments. */
std::cerr << "WARNING!" << std::endl;
std::cerr << "Argument "<< key.c_str() << "is only required once." << std::endl;
std::cerr << "Arguments " << key.c_str() << " " << value.c_str() << "are ignored" << std::endl;
}
if( performLogging )
{
/** Check if the output directory exists. */
bool outFolderExists = itksys::SystemTools::FileIsDirectory( outFolder.c_str() );
if( !outFolderExists )
{
if( performCout )
{
std::cerr << "ERROR: the output directory does not exist." << std::endl;
std::cerr << "You are responsible for creating it." << std::endl;
}
return( -2 );
}
else
{
/** Setup xout. */
if( performLogging )
{
logFileName = outFolder + "transformix.log";
}
}
}
/** The argv0 argument, required for finding the component.dll/so's. */
argMap.insert( ArgumentMapEntryType( "-argv0", "transformix" ) );
/** Setup xout. */
int returndummy2 = elx::xoutSetup( logFileName.c_str() , performLogging , performCout );
if( returndummy2 && performCout )
{
if( performCout )
{
std::cerr << "ERROR while setting up xout." << std::endl;
}
return( returndummy2 );
}
elxout << std::endl;
/** Declare a timer, start it and print the start time. */
tmr::Timer::Pointer totaltimer = tmr::Timer::New();
totaltimer->StartTimer();
elxout << "transformix is started at " << totaltimer->PrintStartTime()
<< ".\n" << std::endl;
/**
* ********************* START TRANSFORMATION *******************
*/
/** Set transformix. */
transformix = TransformixMainType::New();
/** Set stuff from input or needed for output */
movingImageContainer = DataObjectContainerType::New();
movingImageContainer->CreateElementAt( 0 ) = inputImage;
transformix->SetMovingImageContainer( movingImageContainer );
transformix->SetResultImageContainer( ResultImageContainer );
/** Run transformix. */
returndummy = transformix->Run( argMap, parameterMap );
/** Check if transformix run without errors. */
if ( returndummy != 0 )
{
xl::xout["error"] << "Errors occurred" << std::endl;
return returndummy;
}
/** Get the result image */
ResultImageContainer = transformix->GetResultImageContainer();
/** Stop timer and print it. */
totaltimer->StopTimer();
elxout << "\nTransformix has finished at " <<
totaltimer->PrintStopTime() << "." << std::endl;
elxout << "Elapsed time: " <<
totaltimer->PrintElapsedTimeDHMS() << ".\n" << std::endl;
this->m_ResultImage = ResultImageContainer->ElementAt( 0 );
/** Clean up. */
transformix = 0;
TransformixMainType::UnloadComponents();
/** Exit and return the error code. */
return returndummy;
} // end TransformImage()
} // namespace transformix
#endif // end #ifndef __transformixlib_CXX_
<|endoftext|> |
<commit_before>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
#ifndef DO_GEOMETRY_BBOX_HPP
#define DO_GEOMETRY_BBOX_HPP
#include <stdexcept>
#include <vector>
#include <DO/Core/EigenExtension.hpp>
namespace DO {
class BBox
{
Point2d _top_left, _bottom_right;
public:
//! Default constructor.
BBox() {}
//! Constructor from the BBox end points.
BBox(const Point2d& top_left, const Point2d& bottom_right)
: _top_left(top_left), _bottom_right(bottom_right)
{
if ( _top_left.x() > _bottom_right.x() ||
_top_left.y() > _bottom_right.y() )
{
const char *msg = "Top-left and bottom-right corners are wrong!";
throw std::logic_error(msg);
}
}
//! Constructor from a point set.
BBox(const Point2d *begin, const Point2d *end)
{
if (!begin)
{
const char *msg = "The array of points seems wrong.";
throw std::logic_error(msg);
}
_top_left = _bottom_right = *begin;
for (const Point2d *p = begin; p != end; ++p)
{
_top_left.x() = std::min(_top_left.x(), p->x());
_top_left.y() = std::min(_top_left.y(), p->y());
_bottom_right.x() = std::max(_bottom_right.x(), p->x());
_bottom_right.y() = std::max(_bottom_right.y(), p->y());
}
}
//! Constructor from a point set.
BBox(const std::vector<Point2d>& points);
Point2d& top_left() { return _top_left; }
Point2d& bottom_right() { return _bottom_right; }
double& x1() { return _top_left.x(); }
double& y1() { return _top_left.y(); }
double& x2() { return _bottom_right.x(); }
double& y2() { return _bottom_right.y(); }
const Point2d& top_left() const { return _top_left; }
const Point2d& bottom_right() const { return _bottom_right; }
Point2d top_right() const { return _top_left+Point2d(width(), 0); }
Point2d bottom_left() const { return _bottom_right-Point2d(width(), 0); }
double x1() const { return _top_left.x(); }
double y1() const { return _top_left.y(); }
double x2() const { return _bottom_right.x(); }
double y2() const { return _bottom_right.y(); }
double width() const { return std::abs(_bottom_right.x() - _top_left.x()); }
double height() const { return std::abs(_bottom_right.y() - _top_left.y()); }
Vector2d sizes() const { return _bottom_right - _top_left; }
Point2d center() const { return 0.5*(_top_left + _bottom_right); }
static BBox infinite()
{
BBox b;
b.top_left().fill(-std::numeric_limits<double>::infinity());
b.bottom_right().fill(std::numeric_limits<double>::infinity());
return b;
}
static BBox zero()
{
BBox b(Point2d::Zero(), Point2d::Zero());
return b;
}
};
// Utility functions.
double area(const BBox& bbox);
bool inside(const Point2d& p, const BBox& bbox);
bool degenerate(const BBox& bbox, double eps = 1e-3);
bool intersect(const BBox& bbox1, const BBox& bbox2);
double jaccard_similarity(const BBox& bbox1, const BBox& bbox2);
double jaccard_distance(const BBox& bbox1, const BBox& bbox2);
//! I/O.
std::ostream& operator<<(std::ostream& os, const BBox& bbox);
//! Intersection test.
BBox intersection(const BBox& bbox1, const BBox& bbox2);
} /* namespace DO */
#endif /* DO_GEOMETRY_BBOX_HPP */
<commit_msg>MAINT: fix BBox constructor.<commit_after>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
#ifndef DO_GEOMETRY_BBOX_HPP
#define DO_GEOMETRY_BBOX_HPP
#include <stdexcept>
#include <vector>
#include <DO/Core/EigenExtension.hpp>
namespace DO {
class BBox
{
public:
//! Default constructor.
BBox() = default;
//! Constructor from the BBox end points.
BBox(const Point2d& top_left, const Point2d& bottom_right)
: _top_left(top_left), _bottom_right(bottom_right)
{
if ( _top_left.x() > _bottom_right.x() ||
_top_left.y() > _bottom_right.y() )
{
const char *msg = "Top-left and bottom-right corners are wrong!";
throw std::logic_error(msg);
}
}
//! Constructor from a point set.
BBox(const Point2d *begin, const Point2d *end)
{
if (!begin)
{
const char *msg = "The array of points seems wrong.";
throw std::logic_error(msg);
}
_top_left = _bottom_right = *begin;
for (const Point2d *p = begin; p != end; ++p)
{
_top_left.x() = std::min(_top_left.x(), p->x());
_top_left.y() = std::min(_top_left.y(), p->y());
_bottom_right.x() = std::max(_bottom_right.x(), p->x());
_bottom_right.y() = std::max(_bottom_right.y(), p->y());
}
}
//! Constructor from a point set.
BBox(const std::vector<Point2d>& points)
: BBox(&points.front(), &points.back())
{
}
Point2d& top_left() { return _top_left; }
Point2d& bottom_right() { return _bottom_right; }
double& x1() { return _top_left.x(); }
double& y1() { return _top_left.y(); }
double& x2() { return _bottom_right.x(); }
double& y2() { return _bottom_right.y(); }
const Point2d& top_left() const { return _top_left; }
const Point2d& bottom_right() const { return _bottom_right; }
Point2d top_right() const { return _top_left+Point2d(width(), 0); }
Point2d bottom_left() const { return _bottom_right-Point2d(width(), 0); }
double x1() const { return _top_left.x(); }
double y1() const { return _top_left.y(); }
double x2() const { return _bottom_right.x(); }
double y2() const { return _bottom_right.y(); }
double width() const { return std::abs(_bottom_right.x() - _top_left.x()); }
double height() const { return std::abs(_bottom_right.y() - _top_left.y()); }
Vector2d sizes() const { return _bottom_right - _top_left; }
Point2d center() const { return 0.5*(_top_left + _bottom_right); }
static BBox infinite()
{
BBox b;
b.top_left().fill(-std::numeric_limits<double>::infinity());
b.bottom_right().fill(std::numeric_limits<double>::infinity());
return b;
}
static BBox zero()
{
BBox b(Point2d::Zero(), Point2d::Zero());
return b;
}
private:
Point2d _top_left;
Point2d _bottom_right;
};
// Utility functions.
double area(const BBox& bbox);
bool inside(const Point2d& p, const BBox& bbox);
bool degenerate(const BBox& bbox, double eps = 1e-3);
bool intersect(const BBox& bbox1, const BBox& bbox2);
double jaccard_similarity(const BBox& bbox1, const BBox& bbox2);
double jaccard_distance(const BBox& bbox1, const BBox& bbox2);
//! I/O.
std::ostream& operator<<(std::ostream& os, const BBox& bbox);
//! Intersection test.
BBox intersection(const BBox& bbox1, const BBox& bbox2);
} /* namespace DO */
#endif /* DO_GEOMETRY_BBOX_HPP */
<|endoftext|> |
<commit_before>//
// Copyright (c) 2013 Bruno Jouhier <bruno.jouhier@sage.com>
// MIT License
//
// Most of the code borrowed from v8's src/isolate.cc, hence the following copyright notice
// Copyright 2012 the V8 project authors. All rights reserved.
#define ENABLE_DEBUGGER_SUPPORT
#include "api.h"
#include "objects.h"
#include "vm-state-inl.h"
#include <node.h>
#include <v8.h>
using namespace v8;
// BEGIN CODE COPIED FROM api.cc
#define ENTER_V8(isolate) \
ASSERT((isolate)->IsInitialized()); \
i::VMState<i::OTHER> __state__((isolate))
#define ON_BAILOUT(isolate, location, code) \
if (IsDeadCheck(isolate, location) || \
IsExecutionTerminatingCheck(isolate)) { \
code; \
UNREACHABLE(); \
}
static void DefaultFatalErrorHandler(const char* location,
const char* message) {
i::Isolate* isolate = i::Isolate::Current();
if (isolate->IsInitialized()) {
i::VMState<i::OTHER> state(isolate);
API_Fatal(location, message);
} else {
API_Fatal(location, message);
}
}
static FatalErrorCallback GetFatalErrorHandler() {
i::Isolate* isolate = i::Isolate::Current();
if (isolate->exception_behavior() == NULL) {
isolate->set_exception_behavior(DefaultFatalErrorHandler);
}
return isolate->exception_behavior();
}
static bool ReportV8Dead(const char* location) {
FatalErrorCallback callback = GetFatalErrorHandler();
callback(location, "V8 is no longer usable");
return true;
}
static inline bool IsDeadCheck(i::Isolate* isolate, const char* location) {
return !isolate->IsInitialized()
&& i::V8::IsDead() ? ReportV8Dead(location) : false;
}
static inline bool IsExecutionTerminatingCheck(i::Isolate* isolate) {
if (!isolate->IsInitialized()) return false;
if (isolate->has_scheduled_exception()) {
return isolate->scheduled_exception() ==
isolate->heap()->termination_exception();
}
return false;
}
// END CODE COPIED FROM api.cc
// Got this the API boilerplate from v8::Object::GetPrototype()
// and the details from Isolate::CaptureCurrentStackTrace
Local<Value> internalGetStackFrame(Handle<Value> handle, int continuation) {
i::Isolate* isolate = i::Isolate::Current();
ON_BAILOUT(isolate, "Galaxy_stack::GetStackFrame()", return Local<v8::Value>());
ENTER_V8(isolate);
i::Handle<i::JSGeneratorObject> gen = Utils::OpenHandle(*handle);
i::Handle<i::JSFunction> fun(gen->function(), isolate);
i::Handle<i::Script> script(i::Script::cast(fun->shared()->script()));
i::Address pc = gen->function()->code()->instruction_start();
int script_line_offset = script->line_offset()->value();
int position = fun->code()->SourcePosition(pc + (continuation >= 0 ? continuation : gen->continuation()));
int line_number = GetScriptLineNumber(script, position);
// line_number is already shifted by the script_line_offset.
int relative_line_number = line_number - script_line_offset;
i::Handle<i::FixedArray> line_ends(i::FixedArray::cast(script->line_ends()));
int start = (relative_line_number == 0) ? 0 : i::Smi::cast(line_ends->get(relative_line_number - 1))->value() + 1;
int column_offset = position - start;
if (relative_line_number == 0) {
// For the case where the code is on the same line as the script
// tag.
column_offset += script->column_offset()->value();
}
i::Handle<i::Object> script_name(script->name(), isolate);
i::Handle<i::Object> fun_name(fun->shared()->name(), isolate);
if (!fun_name->BooleanValue()) {
fun_name = i::Handle<i::Object>(fun->shared()->inferred_name(), isolate);
}
i::Handle<i::JSObject> stack_frame = isolate->factory()->NewJSObject(isolate->object_function());
i::Handle<i::String> column_key = isolate->factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("column"));
i::Handle<i::String> line_key = isolate->factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("lineNumber"));
i::Handle<i::String> script_key = isolate->factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("scriptName"));
i::Handle<i::String> function_key = isolate->factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("functionName"));
i::JSObject::SetLocalPropertyIgnoreAttributes(stack_frame, script_key, script_name, NONE);
i::JSObject::SetLocalPropertyIgnoreAttributes(stack_frame, line_key, i::Handle<i::Smi>(i::Smi::FromInt(line_number + 1), isolate), NONE);
i::JSObject::SetLocalPropertyIgnoreAttributes(stack_frame, column_key, i::Handle<i::Smi>(i::Smi::FromInt(column_offset + 1), isolate), NONE);
i::JSObject::SetLocalPropertyIgnoreAttributes(stack_frame, function_key, fun_name, NONE);
return Utils::ToLocal(stack_frame);
}
Local<Value> internalGetContinuation(Handle<Value> handle) {
i::Isolate* isolate = i::Isolate::Current();
ON_BAILOUT(isolate, "Galaxy_stack::GetContinuation()", return Local<v8::Value>());
ENTER_V8(isolate);
i::Handle<i::JSGeneratorObject> gen = Utils::OpenHandle(*handle);
return Number::New(gen->continuation());
}
Handle<Value> GetStackFrame(const Arguments& args) {
HandleScope scope;
int len = args.Length();
if (!(len == 1 || len == 2)) {
ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
return scope.Close(Undefined());
}
if (!args[0]->IsObject()) {
ThrowException(Exception::TypeError(String::New("Wrong argument type")));
return scope.Close(Undefined());
}
int continuation = -1;
if (len == 2) {
if (!args[1]->IsNumber()) {
ThrowException(Exception::TypeError(String::New("Wrong argument type")));
return scope.Close(Undefined());
}
continuation = args[1]->NumberValue();
}
Local<Value> result = internalGetStackFrame(args[0], continuation);
return scope.Close(result);
}
Handle<Value> GetContinuation(const Arguments& args) {
HandleScope scope;
if (args.Length() != 1) {
ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
return scope.Close(Undefined());
}
if (!args[0]->IsObject()) {
ThrowException(Exception::TypeError(String::New("Wrong argument type")));
return scope.Close(Undefined());
}
Local<Value> result = internalGetContinuation(args[0]);
return scope.Close(result);
}
void init(Handle<Object> exports) {
exports->Set(String::NewSymbol("getStackFrame"), FunctionTemplate::New(GetStackFrame)->GetFunction());
exports->Set(String::NewSymbol("getContinuation"), FunctionTemplate::New(GetContinuation)->GetFunction());
}
NODE_MODULE(galaxy_stack, init)<commit_msg>fixed for node 0.11.5 using NODE_SET_METHOD<commit_after>//
// Copyright (c) 2013 Bruno Jouhier <bruno.jouhier@sage.com>
// MIT License
//
// Most of the code borrowed from v8's src/isolate.cc, hence the following copyright notice
// Copyright 2012 the V8 project authors. All rights reserved.
#define ENABLE_DEBUGGER_SUPPORT
#include "api.h"
#include "objects.h"
#include "vm-state-inl.h"
#include <node.h>
#include <v8.h>
// BEGIN CODE COPIED FROM api.cc
#define ENTER_V8(isolate) \
ASSERT((isolate)->IsInitialized()); \
i::VMState<i::OTHER> __state__((isolate))
#define ON_BAILOUT(isolate, location, code) \
if (IsDeadCheck(isolate, location) || \
IsExecutionTerminatingCheck(isolate)) { \
code; \
UNREACHABLE(); \
}
static void DefaultFatalErrorHandler(const char* location,
const char* message) {
i::Isolate* isolate = i::Isolate::Current();
if (isolate->IsInitialized()) {
i::VMState<i::OTHER> state(isolate);
API_Fatal(location, message);
} else {
API_Fatal(location, message);
}
}
static v8::FatalErrorCallback GetFatalErrorHandler() {
i::Isolate* isolate = i::Isolate::Current();
if (isolate->exception_behavior() == NULL) {
isolate->set_exception_behavior(DefaultFatalErrorHandler);
}
return isolate->exception_behavior();
}
static bool ReportV8Dead(const char* location) {
v8::FatalErrorCallback callback = GetFatalErrorHandler();
callback(location, "V8 is no longer usable");
return true;
}
static inline bool IsDeadCheck(i::Isolate* isolate, const char* location) {
return !isolate->IsInitialized()
&& i::V8::IsDead() ? ReportV8Dead(location) : false;
}
static inline bool IsExecutionTerminatingCheck(i::Isolate* isolate) {
if (!isolate->IsInitialized()) return false;
if (isolate->has_scheduled_exception()) {
return isolate->scheduled_exception() ==
isolate->heap()->termination_exception();
}
return false;
}
// END CODE COPIED FROM api.cc
// Got this the API boilerplate from v8::Object::GetPrototype()
// and the details from Isolate::CaptureCurrentStackTrace
v8::Local<v8::Value> internalGetStackFrame(v8::Handle<v8::Value> handle, int continuation) {
i::Isolate* isolate = i::Isolate::Current();
ON_BAILOUT(isolate, "Galaxy_stack::GetStackFrame()", return v8::Local<v8::Value>());
ENTER_V8(isolate);
i::Handle<i::JSGeneratorObject> gen = v8::Utils::OpenHandle(*handle);
i::Handle<i::JSFunction> fun(gen->function(), isolate);
i::Handle<i::Script> script(i::Script::cast(fun->shared()->script()));
i::Address pc = gen->function()->code()->instruction_start();
int script_line_offset = script->line_offset()->value();
int position = fun->code()->SourcePosition(pc + (continuation >= 0 ? continuation : gen->continuation()));
int line_number = GetScriptLineNumber(script, position);
// line_number is already shifted by the script_line_offset.
int relative_line_number = line_number - script_line_offset;
i::Handle<i::FixedArray> line_ends(i::FixedArray::cast(script->line_ends()));
int start = (relative_line_number == 0) ? 0 : i::Smi::cast(line_ends->get(relative_line_number - 1))->value() + 1;
int column_offset = position - start;
if (relative_line_number == 0) {
// For the case where the code is on the same line as the script
// tag.
column_offset += script->column_offset()->value();
}
i::Handle<i::Object> script_name(script->name(), isolate);
i::Handle<i::Object> fun_name(fun->shared()->name(), isolate);
if (!fun_name->BooleanValue()) {
fun_name = i::Handle<i::Object>(fun->shared()->inferred_name(), isolate);
}
i::Handle<i::JSObject> stack_frame = isolate->factory()->NewJSObject(isolate->object_function());
i::Handle<i::String> column_key = isolate->factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("column"));
i::Handle<i::String> line_key = isolate->factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("lineNumber"));
i::Handle<i::String> script_key = isolate->factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("scriptName"));
i::Handle<i::String> function_key = isolate->factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("functionName"));
i::JSObject::SetLocalPropertyIgnoreAttributes(stack_frame, script_key, script_name, NONE);
i::JSObject::SetLocalPropertyIgnoreAttributes(stack_frame, line_key, i::Handle<i::Smi>(i::Smi::FromInt(line_number + 1), isolate), NONE);
i::JSObject::SetLocalPropertyIgnoreAttributes(stack_frame, column_key, i::Handle<i::Smi>(i::Smi::FromInt(column_offset + 1), isolate), NONE);
i::JSObject::SetLocalPropertyIgnoreAttributes(stack_frame, function_key, fun_name, NONE);
return v8::Utils::ToLocal(stack_frame);
}
v8::Local<v8::Value> internalGetContinuation(v8::Handle<v8::Value> handle) {
i::Isolate* isolate = i::Isolate::Current();
ON_BAILOUT(isolate, "Galaxy_stack::GetContinuation()", return v8::Local<v8::Value>());
ENTER_V8(isolate);
i::Handle<i::JSGeneratorObject> gen = v8::Utils::OpenHandle(*handle);
return v8::Number::New(gen->continuation());
}
void GetStackFrame(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope;
int len = args.Length();
if (!(len == 1 || len == 2)) {
v8::ThrowException(v8::Exception::TypeError(v8::String::New("Wrong number of arguments")));
args.GetReturnValue().Set(scope.Close(v8::Undefined()));
return;
}
if (!args[0]->IsObject()) {
v8::ThrowException(v8::Exception::TypeError(v8::String::New("Wrong argument type")));
args.GetReturnValue().Set(scope.Close(v8::Undefined()));
return;
}
int continuation = -1;
if (len == 2) {
if (!args[1]->IsNumber()) {
v8::ThrowException(v8::Exception::TypeError(v8::String::New("Wrong argument type")));
args.GetReturnValue().Set(scope.Close(v8::Undefined()));
return;
}
continuation = args[1]->NumberValue();
}
v8::Local<v8::Value> result = internalGetStackFrame(args[0], continuation);
args.GetReturnValue().Set(scope.Close(result));
}
void GetContinuation(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope;
if (args.Length() != 1) {
v8::ThrowException(v8::Exception::TypeError(v8::String::New("Wrong number of arguments")));
args.GetReturnValue().Set(scope.Close(v8::Undefined()));
return;
}
if (!args[0]->IsObject()) {
v8::ThrowException(v8::Exception::TypeError(v8::String::New("Wrong argument type")));
args.GetReturnValue().Set(scope.Close(v8::Undefined()));
return;
}
v8::Local<v8::Value> result = internalGetContinuation(args[0]);
args.GetReturnValue().Set(scope.Close(result));
}
void init(v8::Handle<v8::Object> exports) {
NODE_SET_METHOD(exports, "getStackFrame", GetStackFrame);
NODE_SET_METHOD(exports, "getContinuation", GetContinuation);
}
NODE_MODULE(galaxy_stack, init)
<|endoftext|> |
<commit_before>#ifndef PRESET_CHOOSER_HPP
#define PRESET_CHOOSER_HPP
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#include <wx/panel.h>
#include <wx/sizer.h>
#include <wx/bmpcbox.h>
#endif
#include "Print.hpp"
#include "misc_ui.hpp"
#include "Preset.hpp"
#include "GUI.hpp"
#include "Settings.hpp"
namespace Slic3r { namespace GUI {
using Choosers = std::vector<wxBitmapComboBox*>;
using chooser_name_list = std::vector<wxString>;
using chooser_name_map = std::array<chooser_name_list, preset_types>;
class PresetChooser : public wxPanel {
public:
/// Build a panel to contain a sizer for dropdowns for preset selection.
PresetChooser(wxWindow* parent, Print& print);
PresetChooser(wxWindow* parent, Print& print, Settings& external_settings, preset_store& external_presets);
std::array<Choosers, preset_types> preset_choosers;
/// Load the presets from the backing store and set up the choosers
void load(std::array<Presets, preset_types> presets);
/// Call load() with the app's own presets
void load() { this->load(this->_presets); }
/// Const reference to internal name map (used for testing)
const chooser_name_map& _chooser_names() const { return this->__chooser_names; }
/// Set the selection of one of the preset lists to the entry matching the
/// supplied name.
/// @param[in] name Name of preset to select. Case-sensitive.
/// @param[in] group Type of preset to change.
/// @param[in] index Preset chooser index to operate on (default is 0)
///
/// Note: If index is greater than the number of active presets, nothing
/// happens.
/// Note: If name is not found, nothing happens.
void select_preset_by_name(wxString name, preset_t group, size_t index);
/// Set the selection of one of the preset lists to the entry matching the
/// supplied name.
/// @param[in] name Name of preset to select. Case-sensitive.
/// @param[in] chooser Direct pointer to the appropriate wxBitmapComboBox
///
/// Note: If name is not found, nothing happens.
void select_preset_by_name(wxString name, wxBitmapComboBox* chooser);
/// Cycle through active presets and prompt user to save dirty configs, if necessary.
bool prompt_unsaved_changes();
private:
wxSizer* local_sizer {};
void _on_change_combobox(preset_t preset, wxBitmapComboBox* choice);
chooser_name_map __chooser_names;
/// Reference to a Slic3r::Settings object.
Settings& _settings;
/// Reference to owning Plater's print
Print& _print;
/// Reference to owning Application's preset database.
preset_store& _presets;
void _on_select_preset(preset_t preset);
};
}} // Slic3r::GUI
#endif // PRESET_CHOOSER_HPP
<commit_msg>select_preset_by_name returns whether or not it has an effect.<commit_after>#ifndef PRESET_CHOOSER_HPP
#define PRESET_CHOOSER_HPP
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#include <wx/panel.h>
#include <wx/sizer.h>
#include <wx/bmpcbox.h>
#endif
#include "Print.hpp"
#include "misc_ui.hpp"
#include "Preset.hpp"
#include "GUI.hpp"
#include "Settings.hpp"
namespace Slic3r { namespace GUI {
using Choosers = std::vector<wxBitmapComboBox*>;
using chooser_name_list = std::vector<wxString>;
using chooser_name_map = std::array<chooser_name_list, preset_types>;
class PresetChooser : public wxPanel {
public:
/// Build a panel to contain a sizer for dropdowns for preset selection.
PresetChooser(wxWindow* parent, Print& print);
PresetChooser(wxWindow* parent, Print& print, Settings& external_settings, preset_store& external_presets);
std::array<Choosers, preset_types> preset_choosers;
/// Load the presets from the backing store and set up the choosers
void load(std::array<Presets, preset_types> presets);
/// Call load() with the app's own presets
void load() { this->load(this->_presets); }
/// Const reference to internal name map (used for testing)
const chooser_name_map& _chooser_names() const { return this->__chooser_names; }
/// Set the selection of one of the preset lists to the entry matching the
/// supplied name.
/// \param[in] name Name of preset to select. Case-sensitive.
/// \param[in] group Type of preset to change.
/// \param[in] index Preset chooser index to operate on (default is 0)
/// \return Whether or not the preset was actually updated.
///
/// Note: If index is greater than the number of active presets, nothing
/// happens.
/// Note: If name is not found, nothing happens.
bool select_preset_by_name(wxString name, preset_t group, size_t index);
/// Set the selection of one of the preset lists to the entry matching the
/// supplied name.
/// \param[in] name Name of preset to select. Case-sensitive.
/// \param[in] chooser Direct pointer to the appropriate wxBitmapComboBox
/// \return Whether or not the preset was actually updated.
///
/// Note: If name is not found, nothing happens.
bool select_preset_by_name(wxString name, wxBitmapComboBox* chooser);
/// Cycle through active presets and prompt user to save dirty configs, if necessary.
bool prompt_unsaved_changes();
private:
wxSizer* local_sizer {};
void _on_change_combobox(preset_t preset, wxBitmapComboBox* choice);
chooser_name_map __chooser_names;
/// Reference to a Slic3r::Settings object.
Settings& _settings;
/// Reference to owning Plater's print
Print& _print;
/// Reference to owning Application's preset database.
preset_store& _presets;
void _on_select_preset(preset_t preset);
};
}} // Slic3r::GUI
#endif // PRESET_CHOOSER_HPP
<|endoftext|> |
<commit_before>#include "Genes/Mutation_Rate_Gene.h"
#include <string>
#include <memory>
#include <map>
#include "Genes/Gene.h"
#include "Game/Color.h"
#include "Utility/Random.h"
class Board;
std::string Mutation_Rate_Gene::name() const noexcept
{
return "Mutation Rate Gene";
}
int Mutation_Rate_Gene::mutation_count() const noexcept
{
return mutated_components_per_mutation;
}
void Mutation_Rate_Gene::gene_specific_mutation() noexcept
{
mutated_components_per_mutation += Random::random_laplace(1.0);
mutated_components_per_mutation = std::max(1.0, mutated_components_per_mutation);
}
std::unique_ptr<Gene> Mutation_Rate_Gene::duplicate() const noexcept
{
return std::make_unique<Mutation_Rate_Gene>(*this);
}
double Mutation_Rate_Gene::score_board(const Board&, Color, size_t) const noexcept
{
return 0.0;
}
std::map<std::string, double> Mutation_Rate_Gene::list_properties() const noexcept
{
return {{"Mutation Rate", mutated_components_per_mutation}};
}
void Mutation_Rate_Gene::load_properties(const std::map<std::string, double>& properties)
{
mutated_components_per_mutation = properties.at("Mutation Rate");
}
<commit_msg>Make type conversion explicit<commit_after>#include "Genes/Mutation_Rate_Gene.h"
#include <string>
#include <memory>
#include <map>
#include "Genes/Gene.h"
#include "Game/Color.h"
#include "Utility/Random.h"
class Board;
std::string Mutation_Rate_Gene::name() const noexcept
{
return "Mutation Rate Gene";
}
int Mutation_Rate_Gene::mutation_count() const noexcept
{
return int(mutated_components_per_mutation);
}
void Mutation_Rate_Gene::gene_specific_mutation() noexcept
{
mutated_components_per_mutation += Random::random_laplace(1.0);
mutated_components_per_mutation = std::max(1.0, mutated_components_per_mutation);
}
std::unique_ptr<Gene> Mutation_Rate_Gene::duplicate() const noexcept
{
return std::make_unique<Mutation_Rate_Gene>(*this);
}
double Mutation_Rate_Gene::score_board(const Board&, Color, size_t) const noexcept
{
return 0.0;
}
std::map<std::string, double> Mutation_Rate_Gene::list_properties() const noexcept
{
return {{"Mutation Rate", mutated_components_per_mutation}};
}
void Mutation_Rate_Gene::load_properties(const std::map<std::string, double>& properties)
{
mutated_components_per_mutation = properties.at("Mutation Rate");
}
<|endoftext|> |
<commit_before>#include "common/network/listen_socket_impl.h"
#include "common/network/utility.h"
#include "test/mocks/network/mocks.h"
#include "test/test_common/environment.h"
#include "test/test_common/network_utility.h"
#include "test/test_common/utility.h"
#include "gtest/gtest.h"
using testing::_;
using testing::Return;
namespace Envoy {
namespace Network {
template <Network::Address::SocketType Type>
class ListenSocketImplTest : public testing::TestWithParam<Address::IpVersion> {
protected:
ListenSocketImplTest() : version_(GetParam()) {}
const Address::IpVersion version_;
template <typename... Args>
std::unique_ptr<ListenSocketImpl> createListenSocketPtr(Args&&... args) {
using NetworkSocketTraitType = NetworkSocketTrait<Type>;
return std::make_unique<NetworkListenSocket<NetworkSocketTraitType>>(
std::forward<Args>(args)...);
}
void testBindSpecificPort() {
// This test has a small but real risk of flaky behavior if another thread or process should
// bind to our assigned port during the interval between closing the fd and re-binding. In an
// attempt to avoid this, we allow for retrying by placing the core of the test in a loop with
// a catch of the SocketBindException, indicating we couldn't bind, at which point we retry.
const int kLoopLimit = 20;
int loop_number = 0;
while (true) {
++loop_number;
auto addr_fd = Network::Test::bindFreeLoopbackPort(version_, Address::SocketType::Stream);
auto addr = addr_fd.first;
EXPECT_LE(0, addr_fd.second);
// Confirm that we got a reasonable address and port.
ASSERT_EQ(Address::Type::Ip, addr->type());
ASSERT_EQ(version_, addr->ip()->version());
ASSERT_LT(0U, addr->ip()->port());
// Release the socket and re-bind it.
EXPECT_EQ(0, close(addr_fd.second));
auto option = std::make_unique<MockSocketOption>();
auto options = std::make_shared<std::vector<Network::Socket::OptionConstSharedPtr>>();
EXPECT_CALL(*option, setOption(_, envoy::api::v2::core::SocketOption::STATE_PREBIND))
.WillOnce(Return(true));
options->emplace_back(std::move(option));
std::unique_ptr<ListenSocketImpl> socket1;
try {
socket1 = createListenSocketPtr(addr, options, true);
} catch (SocketBindException& e) {
if (e.errorNumber() != EADDRINUSE) {
ADD_FAILURE() << "Unexpected failure (" << e.errorNumber()
<< ") to bind a free port: " << e.what();
throw;
} else if (loop_number >= kLoopLimit) {
ADD_FAILURE() << "Too many failures (" << loop_number
<< ") to bind a specific port: " << e.what();
return;
}
continue;
}
// TODO (conqerAtapple): This is unfortunate. We should be able to templatize this
// instead of if block.
if (NetworkSocketTrait<Type>::type == Address::SocketType::Stream) {
EXPECT_EQ(0, listen(socket1->fd(), 0));
}
EXPECT_EQ(addr->ip()->port(), socket1->localAddress()->ip()->port());
EXPECT_EQ(addr->ip()->addressAsString(), socket1->localAddress()->ip()->addressAsString());
EXPECT_EQ(Type, socket1->socketType());
auto option2 = std::make_unique<MockSocketOption>();
auto options2 = std::make_shared<std::vector<Network::Socket::OptionConstSharedPtr>>();
EXPECT_CALL(*option2, setOption(_, envoy::api::v2::core::SocketOption::STATE_PREBIND))
.WillOnce(Return(true));
options2->emplace_back(std::move(option2));
// The address and port are bound already, should throw exception.
EXPECT_THROW(createListenSocketPtr(addr, options2, true), SocketBindException);
// Test the case of a socket with fd and given address and port.
auto socket3 = createListenSocketPtr(dup(socket1->fd()), addr, nullptr);
EXPECT_EQ(addr->asString(), socket3->localAddress()->asString());
// Test successful.
return;
}
}
void testBindPortZero() {
auto loopback = Network::Test::getCanonicalLoopbackAddress(version_);
auto socket = createListenSocketPtr(loopback, nullptr, true);
EXPECT_EQ(Address::Type::Ip, socket->localAddress()->type());
EXPECT_EQ(version_, socket->localAddress()->ip()->version());
EXPECT_EQ(loopback->ip()->addressAsString(), socket->localAddress()->ip()->addressAsString());
EXPECT_GT(socket->localAddress()->ip()->port(), 0U);
EXPECT_EQ(Type, socket->socketType());
}
};
using ListenSocketImplTestTcp = ListenSocketImplTest<Network::Address::SocketType::Stream>;
using ListenSocketImplTestUdp = ListenSocketImplTest<Network::Address::SocketType::Datagram>;
INSTANTIATE_TEST_CASE_P(IpVersions, ListenSocketImplTestTcp,
testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
TestUtility::ipTestParamsToString);
INSTANTIATE_TEST_CASE_P(IpVersions, ListenSocketImplTestUdp,
testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
TestUtility::ipTestParamsToString);
TEST_P(ListenSocketImplTestTcp, BindSpecificPort) { testBindSpecificPort(); }
/*
* A simple implementation to test some of ListenSocketImpl's accessors without requiring
* stack interaction.
*/
class TestListenSocket : public ListenSocketImpl {
public:
TestListenSocket(Network::Address::InstanceConstSharedPtr address)
: ListenSocketImpl(-1, address) {}
};
TEST_P(ListenSocketImplTestTcp, SetLocalAddress) {
std::string address_str = "10.1.2.3";
if (version_ == Network::Address::IpVersion::v6) {
address_str = "1::2";
}
Network::Address::InstanceConstSharedPtr address =
Network::Utility::parseInternetAddress(address_str);
TestListenSocket socket(Network::Utility::getIpv4AnyAddress());
socket.setLocalAddress(address);
EXPECT_EQ(socket.localAddress(), address);
}
TEST_P(ListenSocketImplTestUdp, BindSpecificPort) { testBindSpecificPort(); }
// Validate that we get port allocation when binding to port zero.
TEST_P(ListenSocketImplTestTcp, BindPortZero) { testBindPortZero(); }
TEST_P(ListenSocketImplTestUdp, BindPortZero) { testBindPortZero(); }
} // namespace Network
} // namespace Envoy
<commit_msg>Add socketType to TestListenSocket (#5523)<commit_after>#include "common/network/listen_socket_impl.h"
#include "common/network/utility.h"
#include "test/mocks/network/mocks.h"
#include "test/test_common/environment.h"
#include "test/test_common/network_utility.h"
#include "test/test_common/utility.h"
#include "gtest/gtest.h"
using testing::_;
using testing::Return;
namespace Envoy {
namespace Network {
template <Network::Address::SocketType Type>
class ListenSocketImplTest : public testing::TestWithParam<Address::IpVersion> {
protected:
ListenSocketImplTest() : version_(GetParam()) {}
const Address::IpVersion version_;
template <typename... Args>
std::unique_ptr<ListenSocketImpl> createListenSocketPtr(Args&&... args) {
using NetworkSocketTraitType = NetworkSocketTrait<Type>;
return std::make_unique<NetworkListenSocket<NetworkSocketTraitType>>(
std::forward<Args>(args)...);
}
void testBindSpecificPort() {
// This test has a small but real risk of flaky behavior if another thread or process should
// bind to our assigned port during the interval between closing the fd and re-binding. In an
// attempt to avoid this, we allow for retrying by placing the core of the test in a loop with
// a catch of the SocketBindException, indicating we couldn't bind, at which point we retry.
const int kLoopLimit = 20;
int loop_number = 0;
while (true) {
++loop_number;
auto addr_fd = Network::Test::bindFreeLoopbackPort(version_, Address::SocketType::Stream);
auto addr = addr_fd.first;
EXPECT_LE(0, addr_fd.second);
// Confirm that we got a reasonable address and port.
ASSERT_EQ(Address::Type::Ip, addr->type());
ASSERT_EQ(version_, addr->ip()->version());
ASSERT_LT(0U, addr->ip()->port());
// Release the socket and re-bind it.
EXPECT_EQ(0, close(addr_fd.second));
auto option = std::make_unique<MockSocketOption>();
auto options = std::make_shared<std::vector<Network::Socket::OptionConstSharedPtr>>();
EXPECT_CALL(*option, setOption(_, envoy::api::v2::core::SocketOption::STATE_PREBIND))
.WillOnce(Return(true));
options->emplace_back(std::move(option));
std::unique_ptr<ListenSocketImpl> socket1;
try {
socket1 = createListenSocketPtr(addr, options, true);
} catch (SocketBindException& e) {
if (e.errorNumber() != EADDRINUSE) {
ADD_FAILURE() << "Unexpected failure (" << e.errorNumber()
<< ") to bind a free port: " << e.what();
throw;
} else if (loop_number >= kLoopLimit) {
ADD_FAILURE() << "Too many failures (" << loop_number
<< ") to bind a specific port: " << e.what();
return;
}
continue;
}
// TODO (conqerAtapple): This is unfortunate. We should be able to templatize this
// instead of if block.
if (NetworkSocketTrait<Type>::type == Address::SocketType::Stream) {
EXPECT_EQ(0, listen(socket1->fd(), 0));
}
EXPECT_EQ(addr->ip()->port(), socket1->localAddress()->ip()->port());
EXPECT_EQ(addr->ip()->addressAsString(), socket1->localAddress()->ip()->addressAsString());
EXPECT_EQ(Type, socket1->socketType());
auto option2 = std::make_unique<MockSocketOption>();
auto options2 = std::make_shared<std::vector<Network::Socket::OptionConstSharedPtr>>();
EXPECT_CALL(*option2, setOption(_, envoy::api::v2::core::SocketOption::STATE_PREBIND))
.WillOnce(Return(true));
options2->emplace_back(std::move(option2));
// The address and port are bound already, should throw exception.
EXPECT_THROW(createListenSocketPtr(addr, options2, true), SocketBindException);
// Test the case of a socket with fd and given address and port.
auto socket3 = createListenSocketPtr(dup(socket1->fd()), addr, nullptr);
EXPECT_EQ(addr->asString(), socket3->localAddress()->asString());
// Test successful.
return;
}
}
void testBindPortZero() {
auto loopback = Network::Test::getCanonicalLoopbackAddress(version_);
auto socket = createListenSocketPtr(loopback, nullptr, true);
EXPECT_EQ(Address::Type::Ip, socket->localAddress()->type());
EXPECT_EQ(version_, socket->localAddress()->ip()->version());
EXPECT_EQ(loopback->ip()->addressAsString(), socket->localAddress()->ip()->addressAsString());
EXPECT_GT(socket->localAddress()->ip()->port(), 0U);
EXPECT_EQ(Type, socket->socketType());
}
};
using ListenSocketImplTestTcp = ListenSocketImplTest<Network::Address::SocketType::Stream>;
using ListenSocketImplTestUdp = ListenSocketImplTest<Network::Address::SocketType::Datagram>;
INSTANTIATE_TEST_CASE_P(IpVersions, ListenSocketImplTestTcp,
testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
TestUtility::ipTestParamsToString);
INSTANTIATE_TEST_CASE_P(IpVersions, ListenSocketImplTestUdp,
testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
TestUtility::ipTestParamsToString);
TEST_P(ListenSocketImplTestTcp, BindSpecificPort) { testBindSpecificPort(); }
/*
* A simple implementation to test some of ListenSocketImpl's accessors without requiring
* stack interaction.
*/
class TestListenSocket : public ListenSocketImpl {
public:
TestListenSocket(Address::InstanceConstSharedPtr address) : ListenSocketImpl(-1, address) {}
Address::SocketType socketType() const override { return Address::SocketType::Stream; }
};
TEST_P(ListenSocketImplTestTcp, SetLocalAddress) {
std::string address_str = "10.1.2.3";
if (version_ == Address::IpVersion::v6) {
address_str = "1::2";
}
Address::InstanceConstSharedPtr address = Network::Utility::parseInternetAddress(address_str);
TestListenSocket socket(Utility::getIpv4AnyAddress());
socket.setLocalAddress(address);
EXPECT_EQ(socket.localAddress(), address);
}
TEST_P(ListenSocketImplTestUdp, BindSpecificPort) { testBindSpecificPort(); }
// Validate that we get port allocation when binding to port zero.
TEST_P(ListenSocketImplTestTcp, BindPortZero) { testBindPortZero(); }
TEST_P(ListenSocketImplTestUdp, BindPortZero) { testBindPortZero(); }
} // namespace Network
} // namespace Envoy
<|endoftext|> |
<commit_before>/*
* GAMS - General Algebraic Modeling System C++ API
*
* Copyright (c) 2017-2021 GAMS Software GmbH <support@gams.com>
* Copyright (c) 2017-2021 GAMS Development Corp. <support@gams.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "gamsjobimpl.h"
#include "gmomcc.h"
#include "gamscheckpoint.h"
#include "gamslog.h"
#include "gamsoptions.h"
#include "gamsplatform.h"
#include "gamspath.h"
#include "gamsexceptionexecution.h"
#include <sstream>
#include <fstream>
#include <iostream>
using namespace std;
namespace gams {
GAMSJobImpl::GAMSJobImpl(GAMSWorkspace& workspace,
const std::string& jobName,
const std::string& fileName,
const GAMSCheckpoint* checkpoint)
: mWs(workspace), mJobName(jobName), mFileName(fileName)
{
DEB << "---- Entering GAMSJob constructor ----";
if (checkpoint != nullptr) {
if (!GAMSPath::exists(checkpoint->fileName()) )
throw GAMSException("Checkpoint file " + checkpoint->fileName() + " does not exist");
mCheckpointStart = new GAMSCheckpoint(*checkpoint);
}
}
bool GAMSJobImpl::operator!=(const GAMSJobImpl& other) const
{
return (mWs != other.mWs) || (mJobName != other.mJobName);
}
bool GAMSJobImpl::operator==(const GAMSJobImpl& other) const
{
return !(operator!=(other));
}
GAMSDatabase GAMSJobImpl::outDB()
{
return mOutDb;
}
GAMSJobImpl::~GAMSJobImpl() {
delete mCheckpointStart; // this is intended to only free the wrapper, not the *Impl if used anywhere
}
void GAMSJobImpl::run(GAMSOptions* gamsOptions, GAMSCheckpoint* checkpoint, ostream* output, bool createOutDb,
vector<GAMSDatabase> databases)
{
// TODO(JM) backward replacement of pointer logic with instance of gamsOptions
GAMSOptions tmpOpt = GAMSOptions(mWs, gamsOptions);
GAMSCheckpoint* tmpCP = nullptr;
if (mCheckpointStart)
tmpOpt.setRestart(mCheckpointStart->fileName());
if (checkpoint) {
if (mCheckpointStart != checkpoint) {
tmpCP = new GAMSCheckpoint(mWs, "");
tmpOpt.setSave(tmpCP->fileName());
} else {
tmpOpt.setSave(checkpoint->fileName());
}
}
if (mWs.debug() >= GAMSEnum::DebugLevel::ShowLog) {
tmpOpt.setLogOption(3);
} else {
// can only happen if we are called from GAMSModelInstance
if (tmpOpt.logOption() != 2) {
if (output == nullptr)
tmpOpt.setLogOption(0);
else
tmpOpt.setLogOption(3);
}
}
if (!databases.empty()) {
for (GAMSDatabase db: databases) {
db.doExport("");
if (db.inModelName() != "")
tmpOpt.setDefine(db.inModelName(), db.name());
}
}
GAMSPath jobFileInfo(GAMSPath(mWs.workingDirectory()) / mJobName);
if (createOutDb && tmpOpt.gdx() == "")
tmpOpt.setGdx(mWs.nextDatabaseName());
if (tmpOpt.logFile() == "")
tmpOpt.setLogFile(jobFileInfo.suffix(".log").toStdString());
tmpOpt.setOutput(mJobName + ".lst");
tmpOpt.setCurDir(mWs.workingDirectory());
tmpOpt.setInput(mFileName);
GAMSPath pfFileName = jobFileInfo.suffix(".pf");
try {
tmpOpt.writeOptionFile(pfFileName);
} catch (GAMSException& e) {
throw GAMSException(e.what() + (" for GAMSJob " + mJobName));
}
string gamsExe = mWs.systemDirectory() + "/gams";
gamsExe.append(cExeSuffix);
string args = "dummy pf=" + mJobName + ".pf";
string result;
int exitCode = GAMSPlatform::runProcess(mWs.workingDirectory(), gamsExe, args, result);
if (createOutDb) {
//TODO: should we always delete the outDB before a new run? Affects C#, Pytohn and Java as well
//outdb = nullptr;
GAMSPath gdxPath(tmpOpt.gdx());
if (!gdxPath.is_absolute())
gdxPath = GAMSPath(mWs.workingDirectory()) / gdxPath;
gdxPath.setSuffix(".gdx");
if (gdxPath.exists())
mOutDb = mWs.addDatabaseFromGDXForcedName(gdxPath.toStdString(), gdxPath.suffix("").filename().string(), "");
}
if (output && mWs.debug() >= GAMSEnum::DebugLevel::ShowLog)
MSG << result;
else if (output)
*output << result;
if (exitCode != 0) {
if ((mWs.debug() < GAMSEnum::DebugLevel::KeepFiles) && mWs.usingTmpWorkingDir())
throw GAMSExceptionExecution("GAMS return code not 0 (" + to_string(exitCode) +
"), set GAMSWorkspace.Debug to KeepFiles or higher or define the \
GAMSWorkspace.WorkingDirectory to receive a listing file with more details",
exitCode);
else
throw GAMSExceptionExecution("GAMS return code not 0 (" + to_string(exitCode) + "), check " +
(GAMSPath(mWs.workingDirectory()) / tmpOpt.output()).toStdString() +
" for more details", exitCode);
}
if (tmpCP) {
GAMSPath implFile(checkpoint->fileName());
if (implFile.exists())
implFile.remove();
implFile = tmpCP->fileName();
implFile.rename(checkpoint->fileName());
delete tmpCP; tmpCP=nullptr;
}
if (mWs.debug() < GAMSEnum::DebugLevel::KeepFiles) {
// TODO(RG): this is not good style, but apparently needed
try { pfFileName.remove(); } catch (...) { }
}
}
bool GAMSJobImpl::interrupt()
{
/*qint64*/ int pid = 0 /*mProc.processId()*/; // TODO(RG): we need std process handling here
if(pid == 0)
return false;
return GAMSPlatform::interrupt(pid);
}
}
<commit_msg>build path to gams.exe<commit_after>/*
* GAMS - General Algebraic Modeling System C++ API
*
* Copyright (c) 2017-2021 GAMS Software GmbH <support@gams.com>
* Copyright (c) 2017-2021 GAMS Development Corp. <support@gams.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "gamsjobimpl.h"
#include "gmomcc.h"
#include "gamscheckpoint.h"
#include "gamslog.h"
#include "gamsoptions.h"
#include "gamsplatform.h"
#include "gamspath.h"
#include "gamsexceptionexecution.h"
#include <sstream>
#include <fstream>
#include <iostream>
using namespace std;
namespace gams {
GAMSJobImpl::GAMSJobImpl(GAMSWorkspace& workspace,
const std::string& jobName,
const std::string& fileName,
const GAMSCheckpoint* checkpoint)
: mWs(workspace), mJobName(jobName), mFileName(fileName)
{
DEB << "---- Entering GAMSJob constructor ----";
if (checkpoint != nullptr) {
if (!GAMSPath::exists(checkpoint->fileName()) )
throw GAMSException("Checkpoint file " + checkpoint->fileName() + " does not exist");
mCheckpointStart = new GAMSCheckpoint(*checkpoint);
}
}
bool GAMSJobImpl::operator!=(const GAMSJobImpl& other) const
{
return (mWs != other.mWs) || (mJobName != other.mJobName);
}
bool GAMSJobImpl::operator==(const GAMSJobImpl& other) const
{
return !(operator!=(other));
}
GAMSDatabase GAMSJobImpl::outDB()
{
return mOutDb;
}
GAMSJobImpl::~GAMSJobImpl() {
delete mCheckpointStart; // this is intended to only free the wrapper, not the *Impl if used anywhere
}
void GAMSJobImpl::run(GAMSOptions* gamsOptions, GAMSCheckpoint* checkpoint, ostream* output, bool createOutDb,
vector<GAMSDatabase> databases)
{
// TODO(JM) backward replacement of pointer logic with instance of gamsOptions
GAMSOptions tmpOpt = GAMSOptions(mWs, gamsOptions);
GAMSCheckpoint* tmpCP = nullptr;
if (mCheckpointStart)
tmpOpt.setRestart(mCheckpointStart->fileName());
if (checkpoint) {
if (mCheckpointStart != checkpoint) {
tmpCP = new GAMSCheckpoint(mWs, "");
tmpOpt.setSave(tmpCP->fileName());
} else {
tmpOpt.setSave(checkpoint->fileName());
}
}
if (mWs.debug() >= GAMSEnum::DebugLevel::ShowLog) {
tmpOpt.setLogOption(3);
} else {
// can only happen if we are called from GAMSModelInstance
if (tmpOpt.logOption() != 2) {
if (output == nullptr)
tmpOpt.setLogOption(0);
else
tmpOpt.setLogOption(3);
}
}
if (!databases.empty()) {
for (GAMSDatabase db: databases) {
db.doExport("");
if (db.inModelName() != "")
tmpOpt.setDefine(db.inModelName(), db.name());
}
}
GAMSPath jobFileInfo(GAMSPath(mWs.workingDirectory()) / mJobName);
if (createOutDb && tmpOpt.gdx() == "")
tmpOpt.setGdx(mWs.nextDatabaseName());
if (tmpOpt.logFile() == "")
tmpOpt.setLogFile(jobFileInfo.suffix(".log").toStdString());
tmpOpt.setOutput(mJobName + ".lst");
tmpOpt.setCurDir(mWs.workingDirectory());
tmpOpt.setInput(mFileName);
GAMSPath pfFileName = jobFileInfo.suffix(".pf");
try {
tmpOpt.writeOptionFile(pfFileName);
} catch (GAMSException& e) {
throw GAMSException(e.what() + (" for GAMSJob " + mJobName));
}
auto gamsExe = filesystem::path(mWs.systemDirectory());
gamsExe.append(string("gams") + cExeSuffix);
string args = "dummy pf=" + mJobName + ".pf";
string result;
int exitCode = GAMSPlatform::runProcess(mWs.workingDirectory(), gamsExe.string(), args, result);
if (createOutDb) {
//TODO: should we always delete the outDB before a new run? Affects C#, Pytohn and Java as well
//outdb = nullptr;
GAMSPath gdxPath(tmpOpt.gdx());
if (!gdxPath.is_absolute())
gdxPath = GAMSPath(mWs.workingDirectory()) / gdxPath;
gdxPath.setSuffix(".gdx");
if (gdxPath.exists())
mOutDb = mWs.addDatabaseFromGDXForcedName(gdxPath.toStdString(), gdxPath.suffix("").filename().string(), "");
}
if (output && mWs.debug() >= GAMSEnum::DebugLevel::ShowLog)
MSG << result;
else if (output)
*output << result;
if (exitCode != 0) {
if ((mWs.debug() < GAMSEnum::DebugLevel::KeepFiles) && mWs.usingTmpWorkingDir())
throw GAMSExceptionExecution("GAMS return code not 0 (" + to_string(exitCode) +
"), set GAMSWorkspace.Debug to KeepFiles or higher or define the \
GAMSWorkspace.WorkingDirectory to receive a listing file with more details",
exitCode);
else
throw GAMSExceptionExecution("GAMS return code not 0 (" + to_string(exitCode) + "), check " +
(GAMSPath(mWs.workingDirectory()) / tmpOpt.output()).toStdString() +
" for more details", exitCode);
}
if (tmpCP) {
GAMSPath implFile(checkpoint->fileName());
if (implFile.exists())
implFile.remove();
implFile = tmpCP->fileName();
implFile.rename(checkpoint->fileName());
delete tmpCP; tmpCP=nullptr;
}
if (mWs.debug() < GAMSEnum::DebugLevel::KeepFiles) {
// TODO(RG): this is not good style, but apparently needed
try { pfFileName.remove(); } catch (...) { }
}
}
bool GAMSJobImpl::interrupt()
{
/*qint64*/ int pid = 0 /*mProc.processId()*/; // TODO(RG): we need std process handling here
if(pid == 0)
return false;
return GAMSPlatform::interrupt(pid);
}
}
<|endoftext|> |
<commit_before>/*
*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*is % allowed in string
*/
#include <atomic>
#include <memory>
#include <string>
#include <gflags/gflags.h>
#include <grpc++/grpc++.h>
#include <grpc/support/log.h>
#include "src/cpp/thread_manager/thread_manager.h"
#include "test/cpp/util/test_config.h"
class ThreadManagerTest GRPC_FINAL : public grpc::ThreadManager {
public:
ThreadManagerTest()
: ThreadManager(kMinPollers, kMaxPollers),
num_do_work_(0),
num_poll_for_work_(0),
num_work_found_(0) {}
grpc::ThreadManager::WorkStatus PollForWork(void **tag,
bool *ok) GRPC_OVERRIDE;
void DoWork(void *tag, bool ok) GRPC_OVERRIDE;
void PerformTest();
private:
void SleepForMs(int sleep_time_ms);
static const int kMinPollers = 2;
static const int kMaxPollers = 10;
static const int kPollingTimeoutMsec = 10;
static const int kDoWorkDurationMsec = 1;
// PollForWork will return SHUTDOWN after these many number of invocations
static const int kMaxNumPollForWork = 50;
std::atomic_int num_do_work_; // Number of calls to DoWork
std::atomic_int num_poll_for_work_; // Number of calls to PollForWork
std::atomic_int num_work_found_; // Number of times WORK_FOUND was returned
};
void ThreadManagerTest::SleepForMs(int duration_ms) {
gpr_timespec sleep_time =
gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(duration_ms, GPR_TIMESPAN));
gpr_sleep_until(sleep_time);
}
grpc::ThreadManager::WorkStatus ThreadManagerTest::PollForWork(void **tag,
bool *ok) {
int call_num = num_poll_for_work_.fetch_add(1);
if (call_num >= kMaxNumPollForWork) {
Shutdown();
return SHUTDOWN;
}
// Simulate "polling for work" by sleeping for sometime
SleepForMs(kPollingTimeoutMsec);
*tag = nullptr;
*ok = true;
// Return timeout roughly 1 out of every 3 calls
if (call_num % 3 == 0) {
return TIMEOUT;
} else {
num_work_found_++;
return WORK_FOUND;
}
}
void ThreadManagerTest::DoWork(void *tag, bool ok) {
num_do_work_++;
SleepForMs(kDoWorkDurationMsec); // Simulate doing work by sleeping
}
void ThreadManagerTest::PerformTest() {
// Initialize() starts the ThreadManager
ThreadManager::Initialize();
// Wait for all the threads to gracefully terminate
ThreadManager::Wait();
// The number of times DoWork() was called is equal to the number of times
// WORK_FOUND was returned
gpr_log(GPR_DEBUG, "DoWork() called %d times", num_do_work_.load());
GPR_ASSERT(num_do_work_ == num_work_found_);
}
int main(int argc, char **argv) {
std::srand(std::time(NULL));
grpc::testing::InitTest(&argc, &argv, true);
ThreadManagerTest test_rpc_manager;
test_rpc_manager.PerformTest();
return 0;
}
<commit_msg>Change std::atomic_int to gpr_atm since gcc4.4 is complaining<commit_after>/*
*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*is % allowed in string
*/
#include <memory>
#include <string>
#include <gflags/gflags.h>
#include <grpc++/grpc++.h>
#include <grpc/support/log.h>
#include <grpc/support/port_platform.h>
#include "src/cpp/thread_manager/thread_manager.h"
#include "test/cpp/util/test_config.h"
class ThreadManagerTest GRPC_FINAL : public grpc::ThreadManager {
public:
ThreadManagerTest()
: ThreadManager(kMinPollers, kMaxPollers),
num_do_work_(0),
num_poll_for_work_(0),
num_work_found_(0) {}
grpc::ThreadManager::WorkStatus PollForWork(void **tag,
bool *ok) GRPC_OVERRIDE;
void DoWork(void *tag, bool ok) GRPC_OVERRIDE;
void PerformTest();
private:
void SleepForMs(int sleep_time_ms);
static const int kMinPollers = 2;
static const int kMaxPollers = 10;
static const int kPollingTimeoutMsec = 10;
static const int kDoWorkDurationMsec = 1;
// PollForWork will return SHUTDOWN after these many number of invocations
static const int kMaxNumPollForWork = 50;
gpr_atm num_do_work_; // Number of calls to DoWork
gpr_atm num_poll_for_work_; // Number of calls to PollForWork
gpr_atm num_work_found_; // Number of times WORK_FOUND was returned
};
void ThreadManagerTest::SleepForMs(int duration_ms) {
gpr_timespec sleep_time =
gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(duration_ms, GPR_TIMESPAN));
gpr_sleep_until(sleep_time);
}
grpc::ThreadManager::WorkStatus ThreadManagerTest::PollForWork(void **tag,
bool *ok) {
int call_num = gpr_atm_no_barrier_fetch_add(&num_poll_for_work_, 1);
if (call_num >= kMaxNumPollForWork) {
Shutdown();
return SHUTDOWN;
}
// Simulate "polling for work" by sleeping for sometime
SleepForMs(kPollingTimeoutMsec);
*tag = nullptr;
*ok = true;
// Return timeout roughly 1 out of every 3 calls
if (call_num % 3 == 0) {
return TIMEOUT;
} else {
gpr_atm_no_barrier_fetch_add(&num_work_found_, 1);
return WORK_FOUND;
}
}
void ThreadManagerTest::DoWork(void *tag, bool ok) {
gpr_atm_no_barrier_fetch_add(&num_do_work_, 1);
SleepForMs(kDoWorkDurationMsec); // Simulate doing work by sleeping
}
void ThreadManagerTest::PerformTest() {
// Initialize() starts the ThreadManager
Initialize();
// Wait for all the threads to gracefully terminate
Wait();
// The number of times DoWork() was called is equal to the number of times
// WORK_FOUND was returned
gpr_log(GPR_DEBUG, "DoWork() called %ld times",
gpr_atm_no_barrier_load(&num_do_work_));
GPR_ASSERT(gpr_atm_no_barrier_load(&num_do_work_) ==
gpr_atm_no_barrier_load(&num_work_found_));
}
int main(int argc, char **argv) {
std::srand(std::time(NULL));
grpc::testing::InitTest(&argc, &argv, true);
ThreadManagerTest test_rpc_manager;
test_rpc_manager.PerformTest();
return 0;
}
<|endoftext|> |
<commit_before>#include "graph_widget.h"
#include <cassert>
#include <QHBoxLayout>
#include "edge.h"
GraphWidget::GraphWidget(QWidget* parent) : QWidget(parent) {
m_scene = new QGraphicsScene(this);
m_view = new QGraphicsView(m_scene, this);
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(m_view);
}
void GraphWidget::clear() {
m_scene->clear();
m_nodes.clear();
}
Node& GraphWidget::node(unsigned index) {
assert(index < (unsigned)m_nodes.size());
return *m_nodes[index];
}
unsigned GraphWidget::nodeCount() const {
return m_nodes.size();
}
Node& GraphWidget::addNode(const QString& name, const QPointF& position,
const std::initializer_list<std::pair<QString, Port::Type>>& ports) {
Node* n = new Node(name, position, ports);
m_nodes.push_back(n);
m_scene->addItem(n);
return *n;
}
void GraphWidget::removeNode(Node& n) {
for(auto i = m_nodes.begin(); i != m_nodes.end(); ++i)
if(*i == &n) {
m_scene->removeItem(*i);
m_nodes.erase(i);
}
}
void GraphWidget::connect(Port& p1, Port& p2) {
if((p1.portType() & Port::kOutput) && (p2.portType() & Port::kInput)) {
Edge* e = new Edge(p1, p2);
m_edges.push_back(e);
m_scene->addItem(e);
}
}
<commit_msg>Use OpenGL to draw the graph<commit_after>#include "graph_widget.h"
#include <cassert>
#include <QHBoxLayout>
#include <QGLWidget>
#include "edge.h"
GraphWidget::GraphWidget(QWidget* parent) : QWidget(parent) {
m_scene = new QGraphicsScene(this);
m_view = new QGraphicsView(m_scene, this);
m_view->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
m_view->setViewport(new QGLWidget());
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(m_view);
}
void GraphWidget::clear() {
m_scene->clear();
m_nodes.clear();
}
Node& GraphWidget::node(unsigned index) {
assert(index < (unsigned)m_nodes.size());
return *m_nodes[index];
}
unsigned GraphWidget::nodeCount() const {
return m_nodes.size();
}
Node& GraphWidget::addNode(const QString& name, const QPointF& position,
const std::initializer_list<std::pair<QString, Port::Type>>& ports) {
Node* n = new Node(name, position, ports);
m_nodes.push_back(n);
m_scene->addItem(n);
return *n;
}
void GraphWidget::removeNode(Node& n) {
for(auto i = m_nodes.begin(); i != m_nodes.end(); ++i)
if(*i == &n) {
m_scene->removeItem(*i);
m_nodes.erase(i);
}
}
void GraphWidget::connect(Port& p1, Port& p2) {
if((p1.portType() & Port::kOutput) && (p2.portType() & Port::kInput)) {
Edge* e = new Edge(p1, p2);
m_edges.push_back(e);
m_scene->addItem(e);
}
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#define BOOST_TEST_MODULE SecurityTest
#include <boost/test/unit_test.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <thrift/transport/TSSLServerSocket.h>
#include <thrift/transport/TSSLSocket.h>
#include <thrift/transport/TTransport.h>
#include "TestPortFixture.h"
#include <vector>
#ifdef linux
#include <signal.h>
#endif
using apache::thrift::transport::TSSLServerSocket;
using apache::thrift::transport::TServerTransport;
using apache::thrift::transport::TSSLSocket;
using apache::thrift::transport::TSSLSocketFactory;
using apache::thrift::transport::TTransport;
using apache::thrift::transport::TTransportException;
using apache::thrift::transport::TTransportFactory;
boost::filesystem::path keyDir;
boost::filesystem::path certFile(const std::string& filename)
{
return keyDir / filename;
}
boost::mutex gMutex;
struct GlobalFixture
{
GlobalFixture()
{
using namespace boost::unit_test::framework;
for (int i = 0; i < master_test_suite().argc; ++i)
{
BOOST_TEST_MESSAGE(boost::format("argv[%1%] = \"%2%\"") % i % master_test_suite().argv[i]);
}
#ifdef linux
// OpenSSL calls send() without MSG_NOSIGPIPE so writing to a socket that has
// disconnected can cause a SIGPIPE signal...
signal(SIGPIPE, SIG_IGN);
#endif
TSSLSocketFactory::setManualOpenSSLInitialization(true);
apache::thrift::transport::initializeOpenSSL();
keyDir = boost::filesystem::current_path().parent_path().parent_path().parent_path() / "test" / "keys";
if (!boost::filesystem::exists(certFile("server.crt")))
{
keyDir = boost::filesystem::path(master_test_suite().argv[master_test_suite().argc - 1]);
if (!boost::filesystem::exists(certFile("server.crt")))
{
throw std::invalid_argument("The last argument to this test must be the directory containing the test certificate(s).");
}
}
}
virtual ~GlobalFixture()
{
apache::thrift::transport::cleanupOpenSSL();
#ifdef linux
signal(SIGPIPE, SIG_DFL);
#endif
}
};
#if (BOOST_VERSION >= 105900)
BOOST_GLOBAL_FIXTURE(GlobalFixture);
#else
BOOST_GLOBAL_FIXTURE(GlobalFixture)
#endif
struct SecurityFixture : public TestPortFixture
{
void server(apache::thrift::transport::SSLProtocol protocol)
{
try
{
boost::mutex::scoped_lock lock(mMutex);
boost::shared_ptr<TSSLSocketFactory> pServerSocketFactory;
boost::shared_ptr<TSSLServerSocket> pServerSocket;
pServerSocketFactory.reset(new TSSLSocketFactory(static_cast<apache::thrift::transport::SSLProtocol>(protocol)));
pServerSocketFactory->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
pServerSocketFactory->loadCertificate(certFile("server.crt").string().c_str());
pServerSocketFactory->loadPrivateKey(certFile("server.key").string().c_str());
pServerSocketFactory->server(true);
pServerSocket.reset(new TSSLServerSocket("localhost", m_serverPort, pServerSocketFactory));
boost::shared_ptr<TTransport> connectedClient;
try
{
pServerSocket->listen();
mCVar.notify_one();
lock.unlock();
connectedClient = pServerSocket->accept();
uint8_t buf[2];
buf[0] = 'O';
buf[1] = 'K';
connectedClient->write(&buf[0], 2);
connectedClient->flush();
}
catch (apache::thrift::transport::TTransportException& ex)
{
boost::mutex::scoped_lock lock(gMutex);
BOOST_TEST_MESSAGE(boost::format("SRV %1% Exception: %2%") % boost::this_thread::get_id() % ex.what());
}
if (connectedClient)
{
connectedClient->close();
connectedClient.reset();
}
pServerSocket->close();
pServerSocket.reset();
}
catch (std::exception& ex)
{
BOOST_FAIL(boost::format("%1%: %2%") % typeid(ex).name() % ex.what());
}
}
void client(apache::thrift::transport::SSLProtocol protocol)
{
try
{
boost::shared_ptr<TSSLSocketFactory> pClientSocketFactory;
boost::shared_ptr<TSSLSocket> pClientSocket;
try
{
pClientSocketFactory.reset(new TSSLSocketFactory(static_cast<apache::thrift::transport::SSLProtocol>(protocol)));
pClientSocketFactory->authenticate(true);
pClientSocketFactory->loadCertificate(certFile("client.crt").string().c_str());
pClientSocketFactory->loadPrivateKey(certFile("client.key").string().c_str());
pClientSocketFactory->loadTrustedCertificates(certFile("CA.pem").string().c_str());
pClientSocket = pClientSocketFactory->createSocket("localhost", m_serverPort);
pClientSocket->open();
uint8_t buf[3];
buf[0] = 0;
buf[1] = 0;
BOOST_CHECK_EQUAL(2, pClientSocket->read(&buf[0], 2));
BOOST_CHECK_EQUAL(0, memcmp(&buf[0], "OK", 2));
mConnected = true;
}
catch (apache::thrift::transport::TTransportException& ex)
{
boost::mutex::scoped_lock lock(gMutex);
BOOST_TEST_MESSAGE(boost::format("CLI %1% Exception: %2%") % boost::this_thread::get_id() % ex.what());
}
if (pClientSocket)
{
pClientSocket->close();
pClientSocket.reset();
}
}
catch (std::exception& ex)
{
BOOST_FAIL(boost::format("%1%: %2%") % typeid(ex).name() % ex.what());
}
}
static const char *protocol2str(size_t protocol)
{
static const char *strings[apache::thrift::transport::LATEST + 1] =
{
"SSLTLS",
"SSLv2",
"SSLv3",
"TLSv1_0",
"TLSv1_1",
"TLSv1_2"
};
return strings[protocol];
}
boost::mutex mMutex;
boost::condition_variable mCVar;
bool mConnected;
};
BOOST_FIXTURE_TEST_SUITE(BOOST_TEST_MODULE, SecurityFixture)
BOOST_AUTO_TEST_CASE(ssl_security_matrix)
{
try
{
// matrix of connection success between client and server with different SSLProtocol selections
bool matrix[apache::thrift::transport::LATEST + 1][apache::thrift::transport::LATEST + 1] =
{
// server = SSLTLS SSLv2 SSLv3 TLSv1_0 TLSv1_1 TLSv1_2
// client
/* SSLTLS */ { true, false, false, true, true, true },
/* SSLv2 */ { false, false, false, false, false, false },
/* SSLv3 */ { false, false, true, false, false, false },
/* TLSv1_0 */ { true, false, false, true, false, false },
/* TLSv1_1 */ { true, false, false, false, true, false },
/* TLSv1_2 */ { true, false, false, false, false, true }
};
for (size_t si = 0; si <= apache::thrift::transport::LATEST; ++si)
{
for (size_t ci = 0; ci <= apache::thrift::transport::LATEST; ++ci)
{
if (si == 1 || ci == 1)
{
// Skip all SSLv2 cases - protocol not supported
continue;
}
boost::mutex::scoped_lock lock(mMutex);
BOOST_TEST_MESSAGE(boost::format("TEST: Server = %1%, Client = %2%")
% protocol2str(si) % protocol2str(ci));
mConnected = false;
boost::thread_group threads;
threads.create_thread(boost::bind(&SecurityFixture::server, this, static_cast<apache::thrift::transport::SSLProtocol>(si)));
mCVar.wait(lock); // wait for listen() to succeed
lock.unlock();
threads.create_thread(boost::bind(&SecurityFixture::client, this, static_cast<apache::thrift::transport::SSLProtocol>(ci)));
threads.join_all();
BOOST_CHECK_MESSAGE(mConnected == matrix[ci][si],
boost::format(" Server = %1%, Client = %2% expected mConnected == %3% but was %4%")
% protocol2str(si) % protocol2str(ci) % matrix[ci][si] % mConnected);
}
}
}
catch (std::exception& ex)
{
BOOST_FAIL(boost::format("%1%: %2%") % typeid(ex).name() % ex.what());
}
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>THRIFT-3608 lib/cpp/test/SecurityTest is flaky in jenkins Thrift-precommit build. Client: Test (C++) Patch: John Sirois<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#define BOOST_TEST_MODULE SecurityTest
#include <boost/test/unit_test.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <thrift/transport/TSSLServerSocket.h>
#include <thrift/transport/TSSLSocket.h>
#include <thrift/transport/TTransport.h>
#include "TestPortFixture.h"
#include <vector>
#ifdef __linux__
#include <signal.h>
#endif
using apache::thrift::transport::TSSLServerSocket;
using apache::thrift::transport::TServerTransport;
using apache::thrift::transport::TSSLSocket;
using apache::thrift::transport::TSSLSocketFactory;
using apache::thrift::transport::TTransport;
using apache::thrift::transport::TTransportException;
using apache::thrift::transport::TTransportFactory;
boost::filesystem::path keyDir;
boost::filesystem::path certFile(const std::string& filename)
{
return keyDir / filename;
}
boost::mutex gMutex;
struct GlobalFixture
{
GlobalFixture()
{
using namespace boost::unit_test::framework;
for (int i = 0; i < master_test_suite().argc; ++i)
{
BOOST_TEST_MESSAGE(boost::format("argv[%1%] = \"%2%\"") % i % master_test_suite().argv[i]);
}
#ifdef __linux__
// OpenSSL calls send() without MSG_NOSIGPIPE so writing to a socket that has
// disconnected can cause a SIGPIPE signal...
signal(SIGPIPE, SIG_IGN);
#endif
TSSLSocketFactory::setManualOpenSSLInitialization(true);
apache::thrift::transport::initializeOpenSSL();
keyDir = boost::filesystem::current_path().parent_path().parent_path().parent_path() / "test" / "keys";
if (!boost::filesystem::exists(certFile("server.crt")))
{
keyDir = boost::filesystem::path(master_test_suite().argv[master_test_suite().argc - 1]);
if (!boost::filesystem::exists(certFile("server.crt")))
{
throw std::invalid_argument("The last argument to this test must be the directory containing the test certificate(s).");
}
}
}
virtual ~GlobalFixture()
{
apache::thrift::transport::cleanupOpenSSL();
#ifdef __linux__
signal(SIGPIPE, SIG_DFL);
#endif
}
};
#if (BOOST_VERSION >= 105900)
BOOST_GLOBAL_FIXTURE(GlobalFixture);
#else
BOOST_GLOBAL_FIXTURE(GlobalFixture)
#endif
struct SecurityFixture : public TestPortFixture
{
void server(apache::thrift::transport::SSLProtocol protocol)
{
try
{
boost::mutex::scoped_lock lock(mMutex);
boost::shared_ptr<TSSLSocketFactory> pServerSocketFactory;
boost::shared_ptr<TSSLServerSocket> pServerSocket;
pServerSocketFactory.reset(new TSSLSocketFactory(static_cast<apache::thrift::transport::SSLProtocol>(protocol)));
pServerSocketFactory->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
pServerSocketFactory->loadCertificate(certFile("server.crt").string().c_str());
pServerSocketFactory->loadPrivateKey(certFile("server.key").string().c_str());
pServerSocketFactory->server(true);
pServerSocket.reset(new TSSLServerSocket("localhost", m_serverPort, pServerSocketFactory));
boost::shared_ptr<TTransport> connectedClient;
try
{
pServerSocket->listen();
mCVar.notify_one();
lock.unlock();
connectedClient = pServerSocket->accept();
uint8_t buf[2];
buf[0] = 'O';
buf[1] = 'K';
connectedClient->write(&buf[0], 2);
connectedClient->flush();
}
catch (apache::thrift::transport::TTransportException& ex)
{
boost::mutex::scoped_lock lock(gMutex);
BOOST_TEST_MESSAGE(boost::format("SRV %1% Exception: %2%") % boost::this_thread::get_id() % ex.what());
}
if (connectedClient)
{
connectedClient->close();
connectedClient.reset();
}
pServerSocket->close();
pServerSocket.reset();
}
catch (std::exception& ex)
{
BOOST_FAIL(boost::format("%1%: %2%") % typeid(ex).name() % ex.what());
}
}
void client(apache::thrift::transport::SSLProtocol protocol)
{
try
{
boost::shared_ptr<TSSLSocketFactory> pClientSocketFactory;
boost::shared_ptr<TSSLSocket> pClientSocket;
try
{
pClientSocketFactory.reset(new TSSLSocketFactory(static_cast<apache::thrift::transport::SSLProtocol>(protocol)));
pClientSocketFactory->authenticate(true);
pClientSocketFactory->loadCertificate(certFile("client.crt").string().c_str());
pClientSocketFactory->loadPrivateKey(certFile("client.key").string().c_str());
pClientSocketFactory->loadTrustedCertificates(certFile("CA.pem").string().c_str());
pClientSocket = pClientSocketFactory->createSocket("localhost", m_serverPort);
pClientSocket->open();
uint8_t buf[3];
buf[0] = 0;
buf[1] = 0;
BOOST_CHECK_EQUAL(2, pClientSocket->read(&buf[0], 2));
BOOST_CHECK_EQUAL(0, memcmp(&buf[0], "OK", 2));
mConnected = true;
}
catch (apache::thrift::transport::TTransportException& ex)
{
boost::mutex::scoped_lock lock(gMutex);
BOOST_TEST_MESSAGE(boost::format("CLI %1% Exception: %2%") % boost::this_thread::get_id() % ex.what());
}
if (pClientSocket)
{
pClientSocket->close();
pClientSocket.reset();
}
}
catch (std::exception& ex)
{
BOOST_FAIL(boost::format("%1%: %2%") % typeid(ex).name() % ex.what());
}
}
static const char *protocol2str(size_t protocol)
{
static const char *strings[apache::thrift::transport::LATEST + 1] =
{
"SSLTLS",
"SSLv2",
"SSLv3",
"TLSv1_0",
"TLSv1_1",
"TLSv1_2"
};
return strings[protocol];
}
boost::mutex mMutex;
boost::condition_variable mCVar;
bool mConnected;
};
BOOST_FIXTURE_TEST_SUITE(BOOST_TEST_MODULE, SecurityFixture)
BOOST_AUTO_TEST_CASE(ssl_security_matrix)
{
try
{
// matrix of connection success between client and server with different SSLProtocol selections
bool matrix[apache::thrift::transport::LATEST + 1][apache::thrift::transport::LATEST + 1] =
{
// server = SSLTLS SSLv2 SSLv3 TLSv1_0 TLSv1_1 TLSv1_2
// client
/* SSLTLS */ { true, false, false, true, true, true },
/* SSLv2 */ { false, false, false, false, false, false },
/* SSLv3 */ { false, false, true, false, false, false },
/* TLSv1_0 */ { true, false, false, true, false, false },
/* TLSv1_1 */ { true, false, false, false, true, false },
/* TLSv1_2 */ { true, false, false, false, false, true }
};
for (size_t si = 0; si <= apache::thrift::transport::LATEST; ++si)
{
for (size_t ci = 0; ci <= apache::thrift::transport::LATEST; ++ci)
{
if (si == 1 || ci == 1)
{
// Skip all SSLv2 cases - protocol not supported
continue;
}
boost::mutex::scoped_lock lock(mMutex);
BOOST_TEST_MESSAGE(boost::format("TEST: Server = %1%, Client = %2%")
% protocol2str(si) % protocol2str(ci));
mConnected = false;
boost::thread_group threads;
threads.create_thread(boost::bind(&SecurityFixture::server, this, static_cast<apache::thrift::transport::SSLProtocol>(si)));
mCVar.wait(lock); // wait for listen() to succeed
lock.unlock();
threads.create_thread(boost::bind(&SecurityFixture::client, this, static_cast<apache::thrift::transport::SSLProtocol>(ci)));
threads.join_all();
BOOST_CHECK_MESSAGE(mConnected == matrix[ci][si],
boost::format(" Server = %1%, Client = %2% expected mConnected == %3% but was %4%")
% protocol2str(si) % protocol2str(ci) % matrix[ci][si] % mConnected);
}
}
}
catch (std::exception& ex)
{
BOOST_FAIL(boost::format("%1%: %2%") % typeid(ex).name() % ex.what());
}
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/***************************************************************************
* algo/test_stable_ksort.cpp
*
* Part of the STXXL. See http://stxxl.sourceforge.net
*
* Copyright (C) 2003 Roman Dementiev <dementiev@mpi-sb.mpg.de>
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
**************************************************************************/
//! \example algo/test_stable_ksort.cpp
//! This is an example of how to use \c stxxl::ksort() algorithm
#include <stxxl/mng>
#include <stxxl/stable_ksort>
#include <stxxl/ksort>
#include <stxxl/vector>
struct my_type
{
typedef unsigned long key_type;
key_type _key;
char _data[128 - sizeof(key_type)];
key_type key() const
{
return _key;
}
my_type() { }
my_type(key_type __key) : _key(__key) { }
static my_type min_value()
{
return my_type(0);
}
static my_type max_value()
{
return my_type(0xffffffff);
}
};
bool operator < (const my_type & a, const my_type & b)
{
return a.key() < b.key();
}
int main()
{
unsigned memory_to_use = 32 * 1024 * 1024;
typedef stxxl::vector<my_type> vector_type;
const stxxl::int64 n_records = 2 * 32 * stxxl::int64(1024 * 1024) / sizeof(my_type);
vector_type v(n_records);
stxxl::random_number32 rnd;
STXXL_MSG("Filling vector... " << rnd() << " " << rnd() << " " << rnd());
for (vector_type::size_type i = 0; i < v.size(); i++)
v[i]._key = rnd();
STXXL_MSG("Checking order...");
STXXL_MSG(((stxxl::is_sorted(v.begin(), v.end())) ? "OK" : "WRONG"));
STXXL_MSG("Sorting...");
stxxl::stable_ksort(v.begin(), v.end(), memory_to_use);
STXXL_MSG("Checking order...");
STXXL_MSG(((stxxl::is_sorted(v.begin(), v.end())) ? "OK" : "WRONG"));
return 0;
}
<commit_msg>changed the key_type to 32-bit unsigned on all platforms (32 and 64-bit)<commit_after>/***************************************************************************
* algo/test_stable_ksort.cpp
*
* Part of the STXXL. See http://stxxl.sourceforge.net
*
* Copyright (C) 2003 Roman Dementiev <dementiev@mpi-sb.mpg.de>
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
**************************************************************************/
//! \example algo/test_stable_ksort.cpp
//! This is an example of how to use \c stxxl::ksort() algorithm
#include <stxxl/mng>
#include <stxxl/stable_ksort>
#include <stxxl/ksort>
#include <stxxl/vector>
struct my_type
{
typedef unsigned key_type;
key_type _key;
char _data[128 - sizeof(key_type)];
key_type key() const
{
return _key;
}
my_type() { }
my_type(key_type __key) : _key(__key) { }
static my_type min_value()
{
return my_type(0);
}
static my_type max_value()
{
return my_type(0xffffffff);
}
};
bool operator < (const my_type & a, const my_type & b)
{
return a.key() < b.key();
}
int main()
{
unsigned memory_to_use = 32 * 1024 * 1024;
typedef stxxl::vector<my_type> vector_type;
const stxxl::int64 n_records = 2 * 32 * stxxl::int64(1024 * 1024) / sizeof(my_type);
vector_type v(n_records);
stxxl::random_number32 rnd;
STXXL_MSG("Filling vector... " << rnd() << " " << rnd() << " " << rnd());
for (vector_type::size_type i = 0; i < v.size(); i++)
v[i]._key = (rnd()/2)*2;
STXXL_MSG("Checking order...");
STXXL_MSG(((stxxl::is_sorted(v.begin(), v.end())) ? "OK" : "WRONG"));
STXXL_MSG("Sorting...");
stxxl::stable_ksort(v.begin(), v.end(), memory_to_use);
STXXL_MSG("Checking order...");
STXXL_MSG(((stxxl::is_sorted(v.begin(), v.end())) ? "OK" : "WRONG"));
return 0;
}
<|endoftext|> |
<commit_before>#include <htmlrenderer.h>
#include <xmlpullparser.h>
#include <utils.h>
#include <sstream>
#include <iostream>
#include <stdexcept>
#include <logger.h>
using namespace newsbeuter;
htmlrenderer::htmlrenderer(unsigned int width) : w(width) { }
void htmlrenderer::render(const std::string& source, std::vector<std::string>& lines, std::vector<std::string>& links) {
std::istringstream input(source);
render(input, lines, links);
}
void htmlrenderer::add_link(std::vector<std::string>& links, const std::string& link) {
bool found = false;
for (std::vector<std::string>::iterator it=links.begin();it!=links.end();++it) {
if (*it == link)
found = true;
}
if (!found)
links.push_back(link);
}
void htmlrenderer::render(std::istream& input, std::vector<std::string>& lines, std::vector<std::string>& links) {
unsigned int link_count = 0;
std::string curline;
int indent_level = 0;
bool inside_list = false, inside_li = false, is_ol = false, inside_pre = false;
unsigned int ol_count = 1;
xmlpullparser xpp;
xpp.setInput(input);
for (xmlpullparser::event e = xpp.next(); e != xmlpullparser::END_DOCUMENT; e = xpp.next()) {
switch (e) {
case xmlpullparser::START_TAG:
GetLogger().log(LOG_DEBUG,"htmlrenderer::render: found start tag %s",xpp.getText().c_str());
if (xpp.getText() == "a") {
std::string link;
try {
link = xpp.getAttributeValue("href");
} catch (const std::invalid_argument& ) {
GetLogger().log(LOG_WARN,"htmlrenderer::render: found a tag with no href attribute");
link = "";
}
if (link.length() > 0) {
add_link(links,link);
std::ostringstream ref;
ref << "[" << links.size()-1 << "]";
link_count++;
curline.append(ref.str());
}
} else if (xpp.getText() == "br") {
if (curline.length() > 0)
lines.push_back(curline);
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "pre") {
inside_pre = true;
if (curline.length() > 0)
lines.push_back(curline);
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "img") {
std::string imgurl;
try {
imgurl = xpp.getAttributeValue("src");
} catch (const std::invalid_argument& ) {
GetLogger().log(LOG_WARN,"htmlrenderer::render: found img tag with no src attribute");
imgurl = "";
}
if (imgurl.length() > 0) {
add_link(links,imgurl);
std::ostringstream ref;
ref << "[" << links.size()-1 << "]";
link_count++;
curline.append(ref.str());
}
} else if (xpp.getText() == "blockquote") {
++indent_level;
if (curline.length() > 0)
lines.push_back(curline);
lines.push_back(std::string(""));
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "p") {
if (curline.length() > 0)
lines.push_back(curline);
if (lines.size() > 0 && lines[lines.size()-1].length() > static_cast<unsigned int>(indent_level*2))
lines.push_back(std::string(""));
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "ol") {
inside_list = true;
is_ol = true;
ol_count = 1;
if (curline.length() > 0)
lines.push_back(curline);
lines.push_back(std::string(""));
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "ul") {
inside_list = true;
is_ol = false;
if (curline.length() > 0)
lines.push_back(curline);
lines.push_back(std::string(""));
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "li") {
if (inside_li) {
indent_level-=2;
if (curline.length() > 0)
lines.push_back(curline);
prepare_newline(curline, indent_level);
}
inside_li = true;
if (curline.length() > 0)
lines.push_back(curline);
prepare_newline(curline, indent_level);
indent_level+=2;
if (is_ol) {
std::ostringstream num;
num << ol_count;
if (ol_count < 10)
curline.append(" ");
curline.append(num.str());
curline.append(". ");
++ol_count;
} else {
curline.append(" * ");
}
}
break;
case xmlpullparser::END_TAG:
GetLogger().log(LOG_DEBUG, "htmlrenderer::render: found end tag %s",xpp.getText().c_str());
if (xpp.getText() == "blockquote") {
--indent_level;
if (indent_level < 0)
indent_level = 0;
if (curline.length() > 0)
lines.push_back(curline);
lines.push_back(std::string(""));
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "ol" || xpp.getText() == "ul") {
inside_list = false;
if (inside_li) {
indent_level-=2;
if (curline.length() > 0)
lines.push_back(curline);
prepare_newline(curline, indent_level);
}
if (curline.length() > 0)
lines.push_back(curline);
lines.push_back(std::string(""));
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "li") {
indent_level-=2;
inside_li = false;
if (curline.length() > 0)
lines.push_back(curline);
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "p") {
if (curline.length() > 0)
lines.push_back(curline);
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "pre") {
if (curline.length() > 0)
lines.push_back(curline);
prepare_newline(curline, indent_level);
inside_pre = false;
}
break;
case xmlpullparser::TEXT:
{
GetLogger().log(LOG_DEBUG,"htmlrenderer::render: found text `%s'",xpp.getText().c_str());
if (inside_pre) {
std::vector<std::string> words = utils::tokenize_nl(xpp.getText());
for (std::vector<std::string>::iterator it=words.begin();it!=words.end();++it) {
if (*it == "\n") {
lines.push_back(curline);
prepare_newline(curline, indent_level);
} else {
curline.append(*it);
}
}
} else {
std::vector<std::string> words = utils::tokenize_spaced(xpp.getText());
unsigned int i=0;
bool new_line = false;
for (std::vector<std::string>::iterator it=words.begin();it!=words.end();++it,++i) {
if ((curline.length() + it->length()) >= w) {
if (curline.length() > 0)
lines.push_back(curline);
prepare_newline(curline, indent_level);
new_line = true;
}
if (new_line) {
if (*it != " ")
curline.append(*it);
new_line = false;
} else {
curline.append(*it);
}
}
}
}
break;
default:
/* do nothing */
break;
}
}
if (curline.length() > 0)
lines.push_back(curline);
if (links.size() > 0) {
lines.push_back(std::string(""));
lines.push_back(std::string("Links: "));
for (unsigned int i=0;i<links.size();++i) {
std::ostringstream line;
line << "[" << i << "]: " << links[i];
lines.push_back(line.str());
}
}
}
void htmlrenderer::prepare_newline(std::string& line, int indent_level) {
line = "";
for (int i=0;i<indent_level;++i) {
line.append(" ");
}
}
<commit_msg>Andreas Krennmair: fixed bug with link numbering.<commit_after>#include <htmlrenderer.h>
#include <xmlpullparser.h>
#include <utils.h>
#include <sstream>
#include <iostream>
#include <stdexcept>
#include <logger.h>
using namespace newsbeuter;
htmlrenderer::htmlrenderer(unsigned int width) : w(width) { }
void htmlrenderer::render(const std::string& source, std::vector<std::string>& lines, std::vector<std::string>& links) {
std::istringstream input(source);
render(input, lines, links);
}
void htmlrenderer::add_link(std::vector<std::string>& links, const std::string& link) {
bool found = false;
for (std::vector<std::string>::iterator it=links.begin();it!=links.end();++it) {
if (*it == link)
found = true;
}
if (!found)
links.push_back(link);
}
void htmlrenderer::render(std::istream& input, std::vector<std::string>& lines, std::vector<std::string>& links) {
unsigned int link_count = 0;
std::string curline;
int indent_level = 0;
bool inside_list = false, inside_li = false, is_ol = false, inside_pre = false;
unsigned int ol_count = 1;
xmlpullparser xpp;
xpp.setInput(input);
for (xmlpullparser::event e = xpp.next(); e != xmlpullparser::END_DOCUMENT; e = xpp.next()) {
switch (e) {
case xmlpullparser::START_TAG:
GetLogger().log(LOG_DEBUG,"htmlrenderer::render: found start tag %s",xpp.getText().c_str());
if (xpp.getText() == "a") {
std::string link;
try {
link = xpp.getAttributeValue("href");
} catch (const std::invalid_argument& ) {
GetLogger().log(LOG_WARN,"htmlrenderer::render: found a tag with no href attribute");
link = "";
}
if (link.length() > 0) {
add_link(links,link);
std::ostringstream ref;
ref << "[" << link_count << "]";
link_count++;
curline.append(ref.str());
}
} else if (xpp.getText() == "br") {
if (curline.length() > 0)
lines.push_back(curline);
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "pre") {
inside_pre = true;
if (curline.length() > 0)
lines.push_back(curline);
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "img") {
std::string imgurl;
try {
imgurl = xpp.getAttributeValue("src");
} catch (const std::invalid_argument& ) {
GetLogger().log(LOG_WARN,"htmlrenderer::render: found img tag with no src attribute");
imgurl = "";
}
if (imgurl.length() > 0) {
add_link(links,imgurl);
std::ostringstream ref;
ref << "[" << link_count << "]";
link_count++;
curline.append(ref.str());
}
} else if (xpp.getText() == "blockquote") {
++indent_level;
if (curline.length() > 0)
lines.push_back(curline);
lines.push_back(std::string(""));
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "p") {
if (curline.length() > 0)
lines.push_back(curline);
if (lines.size() > 0 && lines[lines.size()-1].length() > static_cast<unsigned int>(indent_level*2))
lines.push_back(std::string(""));
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "ol") {
inside_list = true;
is_ol = true;
ol_count = 1;
if (curline.length() > 0)
lines.push_back(curline);
lines.push_back(std::string(""));
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "ul") {
inside_list = true;
is_ol = false;
if (curline.length() > 0)
lines.push_back(curline);
lines.push_back(std::string(""));
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "li") {
if (inside_li) {
indent_level-=2;
if (curline.length() > 0)
lines.push_back(curline);
prepare_newline(curline, indent_level);
}
inside_li = true;
if (curline.length() > 0)
lines.push_back(curline);
prepare_newline(curline, indent_level);
indent_level+=2;
if (is_ol) {
std::ostringstream num;
num << ol_count;
if (ol_count < 10)
curline.append(" ");
curline.append(num.str());
curline.append(". ");
++ol_count;
} else {
curline.append(" * ");
}
}
break;
case xmlpullparser::END_TAG:
GetLogger().log(LOG_DEBUG, "htmlrenderer::render: found end tag %s",xpp.getText().c_str());
if (xpp.getText() == "blockquote") {
--indent_level;
if (indent_level < 0)
indent_level = 0;
if (curline.length() > 0)
lines.push_back(curline);
lines.push_back(std::string(""));
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "ol" || xpp.getText() == "ul") {
inside_list = false;
if (inside_li) {
indent_level-=2;
if (curline.length() > 0)
lines.push_back(curline);
prepare_newline(curline, indent_level);
}
if (curline.length() > 0)
lines.push_back(curline);
lines.push_back(std::string(""));
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "li") {
indent_level-=2;
inside_li = false;
if (curline.length() > 0)
lines.push_back(curline);
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "p") {
if (curline.length() > 0)
lines.push_back(curline);
prepare_newline(curline, indent_level);
} else if (xpp.getText() == "pre") {
if (curline.length() > 0)
lines.push_back(curline);
prepare_newline(curline, indent_level);
inside_pre = false;
}
break;
case xmlpullparser::TEXT:
{
GetLogger().log(LOG_DEBUG,"htmlrenderer::render: found text `%s'",xpp.getText().c_str());
if (inside_pre) {
std::vector<std::string> words = utils::tokenize_nl(xpp.getText());
for (std::vector<std::string>::iterator it=words.begin();it!=words.end();++it) {
if (*it == "\n") {
lines.push_back(curline);
prepare_newline(curline, indent_level);
} else {
curline.append(*it);
}
}
} else {
std::vector<std::string> words = utils::tokenize_spaced(xpp.getText());
unsigned int i=0;
bool new_line = false;
for (std::vector<std::string>::iterator it=words.begin();it!=words.end();++it,++i) {
if ((curline.length() + it->length()) >= w) {
if (curline.length() > 0)
lines.push_back(curline);
prepare_newline(curline, indent_level);
new_line = true;
}
if (new_line) {
if (*it != " ")
curline.append(*it);
new_line = false;
} else {
curline.append(*it);
}
}
}
}
break;
default:
/* do nothing */
break;
}
}
if (curline.length() > 0)
lines.push_back(curline);
if (links.size() > 0) {
lines.push_back(std::string(""));
lines.push_back(std::string("Links: "));
for (unsigned int i=0;i<links.size();++i) {
std::ostringstream line;
line << "[" << i << "]: " << links[i];
lines.push_back(line.str());
}
}
}
void htmlrenderer::prepare_newline(std::string& line, int indent_level) {
line = "";
for (int i=0;i<indent_level;++i) {
line.append(" ");
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "profilemanager.h"
#include "profile.h"
#include "profileconfigwidget.h"
#include "profileinformation.h"
#include "profilemanagerconfigwidget.h"
#include "project.h"
#include <coreplugin/icore.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/persistentsettings.h>
#include <utils/environment.h>
#include <QCoreApplication>
#include <QDir>
#include <QSettings>
#include <QFormLayout>
#include <QLabel>
#include <QMainWindow>
static const char PROFILE_DATA_KEY[] = "Profile.";
static const char PROFILE_COUNT_KEY[] = "Profile.Count";
static const char PROFILE_FILE_VERSION_KEY[] = "Version";
static const char PROFILE_DEFAULT_KEY[] = "Profile.Default";
static const char PROFILE_FILENAME[] = "/qtcreator/profiles.xml";
using Utils::PersistentSettingsWriter;
using Utils::PersistentSettingsReader;
static QString settingsFileName()
{
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
QFileInfo settingsLocation(pm->settings()->fileName());
return settingsLocation.absolutePath() + QLatin1String(PROFILE_FILENAME);
}
namespace ProjectExplorer {
ProfileManager *ProfileManager::m_instance = 0;
namespace Internal {
// --------------------------------------------------------------------------
// ProfileManagerPrivate:
// --------------------------------------------------------------------------
class ProfileManagerPrivate
{
public:
ProfileManagerPrivate();
~ProfileManagerPrivate();
QList<Task> validateProfile(Profile *p) const;
Profile *m_defaultProfile;
bool m_initialized;
QList<ProfileInformation *> m_informationList;
QList<Profile *> m_profileList;
};
ProfileManagerPrivate::ProfileManagerPrivate()
: m_defaultProfile(0), m_initialized(false)
{ }
ProfileManagerPrivate::~ProfileManagerPrivate()
{
}
QList<Task> ProfileManagerPrivate::validateProfile(Profile *p) const
{
Q_ASSERT(p);
QList<Task> result;
bool hasError = false;
foreach (ProfileInformation *pi, m_informationList) {
QList<Task> tmp = pi->validate(p);
foreach (const Task &t, tmp)
if (t.type == Task::Error)
hasError = true;
result << tmp;
}
p->setValid(!hasError);
return result;
}
} // namespace Internal
// --------------------------------------------------------------------------
// ProfileManager:
// --------------------------------------------------------------------------
ProfileManager *ProfileManager::instance()
{
return m_instance;
}
ProfileManager::ProfileManager(QObject *parent) :
QObject(parent),
d(new Internal::ProfileManagerPrivate())
{
Q_ASSERT(!m_instance);
m_instance = this;
connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()),
this, SLOT(saveProfiles()));
connect(this, SIGNAL(profileAdded(ProjectExplorer::Profile*)),
this, SIGNAL(profilesChanged()));
connect(this, SIGNAL(profileRemoved(ProjectExplorer::Profile*)),
this, SIGNAL(profilesChanged()));
connect(this, SIGNAL(profileUpdated(ProjectExplorer::Profile*)),
this, SIGNAL(profilesChanged()));
}
void ProfileManager::restoreProfiles()
{
QList<Profile *> stsToRegister;
QList<Profile *> stsToCheck;
// read all profiles from SDK
QFileInfo systemSettingsFile(Core::ICore::settings(QSettings::SystemScope)->fileName());
ProfileList system = restoreProfiles(systemSettingsFile.absolutePath() + QLatin1String(PROFILE_FILENAME));
QList<Profile *> readSts = system.profiles;
// make sure we mark these as autodetected!
foreach (Profile *p, readSts)
p->setAutoDetected(true);
stsToRegister = readSts; // SDK profiles are always considered to be up-to-date, so no need to
// recheck them.
// read all profile chains from user file
ProfileList userProfiles = restoreProfiles(settingsFileName());
readSts = userProfiles.profiles;
foreach (Profile *p, readSts) {
if (p->isAutoDetected())
stsToCheck.append(p);
else
stsToRegister.append(p);
}
readSts.clear();
// Then auto create profiles:
QList<Profile *> detectedSts;
// Find/update autodetected profiles:
Profile *toStore = 0;
foreach (Profile *currentDetected, detectedSts) {
toStore = currentDetected;
// Check whether we had this profile stored and prefer the old one with the old id:
for (int i = 0; i < stsToCheck.count(); ++i) {
if (*(stsToCheck.at(i)) == *currentDetected) {
toStore = stsToCheck.at(i);
stsToCheck.removeAt(i);
delete currentDetected;
break;
}
}
addProfile(toStore);
}
// Delete all loaded autodetected profiles that were not rediscovered:
qDeleteAll(stsToCheck);
// Store manual profiles
foreach (Profile *p, stsToRegister)
addProfile(p);
if (profiles().isEmpty()) {
Profile *defaultProfile = new Profile; // One profile using default values
defaultProfile->setDisplayName(tr("Desktop"));
defaultProfile->setAutoDetected(false);
defaultProfile->setIconPath(QLatin1String(":///DESKTOP///"));
addProfile(defaultProfile);
}
Profile *p = find(userProfiles.defaultProfile);
if (p)
setDefaultProfile(p);
}
ProfileManager::~ProfileManager()
{
// Clean out profile information to avoid calling them during deregistration:
qDeleteAll(d->m_informationList);
qDeleteAll(d->m_profileList);
delete d;
m_instance = 0;
}
void ProfileManager::saveProfiles()
{
if (!d->m_initialized) // ignore save requests while we are not initialized.
return;
PersistentSettingsWriter writer;
writer.saveValue(QLatin1String(PROFILE_FILE_VERSION_KEY), 1);
int count = 0;
foreach (Profile *p, profiles()) {
QVariantMap tmp = p->toMap();
if (tmp.isEmpty())
continue;
writer.saveValue(QString::fromLatin1(PROFILE_DATA_KEY) + QString::number(count), tmp);
++count;
}
writer.saveValue(QLatin1String(PROFILE_COUNT_KEY), count);
writer.saveValue(QLatin1String(PROFILE_DEFAULT_KEY),
d->m_defaultProfile ? QString::fromLatin1(d->m_defaultProfile->id().name()) : QString());
writer.save(settingsFileName(), QLatin1String("QtCreatorProfiles"), Core::ICore::mainWindow());
}
bool greaterPriority(ProfileInformation *a, ProfileInformation *b)
{
return a->priority() > b->priority();
}
void ProfileManager::registerProfileInformation(ProfileInformation *pi)
{
QList<ProfileInformation *>::iterator it
= qLowerBound(d->m_informationList.begin(), d->m_informationList.end(), pi, greaterPriority);
d->m_informationList.insert(it, pi);
connect(pi, SIGNAL(validationNeeded()), this, SLOT(validateProfiles()));
if (!d->m_initialized)
return;
foreach (Profile *p, profiles()) {
if (!p->hasValue(pi->dataId()))
p->setValue(pi->dataId(), pi->defaultValue(p));
}
return;
}
void ProfileManager::deregisterProfileInformation(ProfileInformation *pi)
{
Q_ASSERT(d->m_informationList.contains(pi));
d->m_informationList.removeAll(pi);
delete pi;
}
ProfileManager::ProfileList ProfileManager::restoreProfiles(const QString &fileName)
{
ProfileList result;
PersistentSettingsReader reader;
if (!reader.load(fileName))
return result;
QVariantMap data = reader.restoreValues();
// Check version:
int version = data.value(QLatin1String(PROFILE_FILE_VERSION_KEY), 0).toInt();
if (version < 1)
return result;
const int count = data.value(QLatin1String(PROFILE_COUNT_KEY), 0).toInt();
for (int i = 0; i < count; ++i) {
const QString key = QString::fromLatin1(PROFILE_DATA_KEY) + QString::number(i);
if (!data.contains(key))
break;
const QVariantMap stMap = data.value(key).toMap();
Profile *p = new Profile;
if (p->fromMap(stMap)) {
result.profiles.append(p);
} else {
delete p;
qWarning("Warning: Unable to restore profiles stored in %s at position %d.",
qPrintable(QDir::toNativeSeparators(fileName)), i);
}
}
const QString defaultId = data.value(QLatin1String(PROFILE_DEFAULT_KEY)).toString();
if (defaultId.isEmpty())
return result;
const Core::Id id = Core::Id(defaultId);
foreach (Profile *i, result.profiles) {
if (i->id() == id) {
result.defaultProfile = id;
break;
}
}
return result;
}
QList<Profile *> ProfileManager::profiles(const ProfileMatcher *m) const
{
if (!d->m_initialized) {
d->m_initialized = true;
const_cast<ProfileManager *>(this)->restoreProfiles();
}
QList<Profile *> result;
foreach (Profile *p, d->m_profileList) {
if (!m || m->matches(p))
result.append(p);
}
return result;
}
Profile *ProfileManager::find(const Core::Id &id) const
{
if (!id.isValid())
return 0;
foreach (Profile *p, profiles()) {
if (p->id() == id)
return p;
}
return 0;
}
Profile *ProfileManager::find(const ProfileMatcher *m) const
{
QList<Profile *> matched = profiles(m);
return matched.isEmpty() ? 0 : matched.first();
}
Profile *ProfileManager::defaultProfile()
{
if (!d->m_initialized) {
d->m_initialized = true;
restoreProfiles();
}
return d->m_defaultProfile;
}
QList<ProfileInformation *> ProfileManager::profileInformation() const
{
return d->m_informationList;
}
ProfileConfigWidget *ProfileManager::createConfigWidget(Profile *p) const
{
if (!p)
return 0;
Internal::ProfileManagerConfigWidget *result = new Internal::ProfileManagerConfigWidget(p);
foreach (ProfileInformation *pi, d->m_informationList)
result->addConfigWidget(pi->createConfigWidget(p));
return result;
}
void ProfileManager::notifyAboutUpdate(ProjectExplorer::Profile *p)
{
if (!p || !profiles().contains(p))
return;
d->validateProfile(p);
emit profileUpdated(p);
}
bool ProfileManager::registerProfile(ProjectExplorer::Profile *p)
{
if (!p)
return true;
foreach (Profile *current, profiles()) {
if (p == current)
return false;
}
// make sure we have all the information in our profiles:
foreach (ProfileInformation *pi, d->m_informationList) {
if (!p->hasValue(pi->dataId()))
p->setValue(pi->dataId(), pi->defaultValue(p));
}
addProfile(p);
emit profileAdded(p);
return true;
}
void ProfileManager::deregisterProfile(Profile *p)
{
if (!p || !profiles().contains(p))
return;
d->m_profileList.removeOne(p);
if (d->m_defaultProfile == p) {
QList<Profile *> stList = profiles();
Profile *newDefault = 0;
foreach (Profile *cur, stList) {
if (cur->isValid()) {
newDefault = cur;
break;
}
}
setDefaultProfile(newDefault);
}
emit profileRemoved(p);
delete p;
}
QList<Task> ProfileManager::validateProfile(Profile *p)
{
QList<Task> result = d->validateProfile(p);
qSort(result);
return result;
}
void ProfileManager::setDefaultProfile(Profile *p)
{
if (d->m_defaultProfile == p)
return;
if (p && !profiles().contains(p))
return;
d->m_defaultProfile = p;
emit defaultProfileChanged();
}
void ProfileManager::validateProfiles()
{
foreach (Profile *p, profiles())
d->validateProfile(p);
}
void ProfileManager::addProfile(Profile *p)
{
if (!p)
return;
d->validateProfile(p);
d->m_profileList.append(p);
if (!d->m_defaultProfile ||
(!d->m_defaultProfile->isValid() && p->isValid()))
setDefaultProfile(p);
}
void ProfileInformation::addToEnvironment(const Profile *p, Utils::Environment &env) const
{
Q_UNUSED(p);
Q_UNUSED(env);
}
} // namespace ProjectExplorer
<commit_msg>profiles: some variable renaming (st->profile)<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "profilemanager.h"
#include "profile.h"
#include "profileconfigwidget.h"
#include "profileinformation.h"
#include "profilemanagerconfigwidget.h"
#include "project.h"
#include <coreplugin/icore.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/persistentsettings.h>
#include <utils/environment.h>
#include <QCoreApplication>
#include <QDir>
#include <QSettings>
#include <QFormLayout>
#include <QLabel>
#include <QMainWindow>
static const char PROFILE_DATA_KEY[] = "Profile.";
static const char PROFILE_COUNT_KEY[] = "Profile.Count";
static const char PROFILE_FILE_VERSION_KEY[] = "Version";
static const char PROFILE_DEFAULT_KEY[] = "Profile.Default";
static const char PROFILE_FILENAME[] = "/qtcreator/profiles.xml";
using Utils::PersistentSettingsWriter;
using Utils::PersistentSettingsReader;
static QString settingsFileName()
{
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
QFileInfo settingsLocation(pm->settings()->fileName());
return settingsLocation.absolutePath() + QLatin1String(PROFILE_FILENAME);
}
namespace ProjectExplorer {
ProfileManager *ProfileManager::m_instance = 0;
namespace Internal {
// --------------------------------------------------------------------------
// ProfileManagerPrivate:
// --------------------------------------------------------------------------
class ProfileManagerPrivate
{
public:
ProfileManagerPrivate();
~ProfileManagerPrivate();
QList<Task> validateProfile(Profile *p) const;
Profile *m_defaultProfile;
bool m_initialized;
QList<ProfileInformation *> m_informationList;
QList<Profile *> m_profileList;
};
ProfileManagerPrivate::ProfileManagerPrivate()
: m_defaultProfile(0), m_initialized(false)
{ }
ProfileManagerPrivate::~ProfileManagerPrivate()
{
}
QList<Task> ProfileManagerPrivate::validateProfile(Profile *p) const
{
Q_ASSERT(p);
QList<Task> result;
bool hasError = false;
foreach (ProfileInformation *pi, m_informationList) {
QList<Task> tmp = pi->validate(p);
foreach (const Task &t, tmp)
if (t.type == Task::Error)
hasError = true;
result << tmp;
}
p->setValid(!hasError);
return result;
}
} // namespace Internal
// --------------------------------------------------------------------------
// ProfileManager:
// --------------------------------------------------------------------------
ProfileManager *ProfileManager::instance()
{
return m_instance;
}
ProfileManager::ProfileManager(QObject *parent) :
QObject(parent),
d(new Internal::ProfileManagerPrivate())
{
Q_ASSERT(!m_instance);
m_instance = this;
connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()),
this, SLOT(saveProfiles()));
connect(this, SIGNAL(profileAdded(ProjectExplorer::Profile*)),
this, SIGNAL(profilesChanged()));
connect(this, SIGNAL(profileRemoved(ProjectExplorer::Profile*)),
this, SIGNAL(profilesChanged()));
connect(this, SIGNAL(profileUpdated(ProjectExplorer::Profile*)),
this, SIGNAL(profilesChanged()));
}
void ProfileManager::restoreProfiles()
{
QList<Profile *> profilesToRegister;
QList<Profile *> profilesToCheck;
// read all profiles from SDK
QFileInfo systemSettingsFile(Core::ICore::settings(QSettings::SystemScope)->fileName());
ProfileList system = restoreProfiles(systemSettingsFile.absolutePath() + QLatin1String(PROFILE_FILENAME));
QList<Profile *> readProfiles = system.profiles;
// make sure we mark these as autodetected!
foreach (Profile *p, readProfiles)
p->setAutoDetected(true);
profilesToRegister = readProfiles; // SDK profiles are always considered to be up-to-date, so no need to
// recheck them.
// read all profile chains from user file
ProfileList userProfiles = restoreProfiles(settingsFileName());
readProfiles = userProfiles.profiles;
foreach (Profile *p, readProfiles) {
if (p->isAutoDetected())
profilesToCheck.append(p);
else
profilesToRegister.append(p);
}
readProfiles.clear();
// Then auto create profiles:
QList<Profile *> detectedProfiles;
// Find/update autodetected profiles:
Profile *toStore = 0;
foreach (Profile *currentDetected, detectedProfiles) {
toStore = currentDetected;
// Check whether we had this profile stored and prefer the old one with the old id:
for (int i = 0; i < profilesToCheck.count(); ++i) {
if (*(profilesToCheck.at(i)) == *currentDetected) {
toStore = profilesToCheck.at(i);
profilesToCheck.removeAt(i);
delete currentDetected;
break;
}
}
addProfile(toStore);
}
// Delete all loaded autodetected profiles that were not rediscovered:
qDeleteAll(profilesToCheck);
// Store manual profiles
foreach (Profile *p, profilesToRegister)
addProfile(p);
if (profiles().isEmpty()) {
Profile *defaultProfile = new Profile; // One profile using default values
defaultProfile->setDisplayName(tr("Desktop"));
defaultProfile->setAutoDetected(false);
defaultProfile->setIconPath(QLatin1String(":///DESKTOP///"));
addProfile(defaultProfile);
}
Profile *p = find(userProfiles.defaultProfile);
if (p)
setDefaultProfile(p);
}
ProfileManager::~ProfileManager()
{
// Clean out profile information to avoid calling them during deregistration:
qDeleteAll(d->m_informationList);
qDeleteAll(d->m_profileList);
delete d;
m_instance = 0;
}
void ProfileManager::saveProfiles()
{
if (!d->m_initialized) // ignore save requests while we are not initialized.
return;
PersistentSettingsWriter writer;
writer.saveValue(QLatin1String(PROFILE_FILE_VERSION_KEY), 1);
int count = 0;
foreach (Profile *p, profiles()) {
QVariantMap tmp = p->toMap();
if (tmp.isEmpty())
continue;
writer.saveValue(QString::fromLatin1(PROFILE_DATA_KEY) + QString::number(count), tmp);
++count;
}
writer.saveValue(QLatin1String(PROFILE_COUNT_KEY), count);
writer.saveValue(QLatin1String(PROFILE_DEFAULT_KEY),
d->m_defaultProfile ? QString::fromLatin1(d->m_defaultProfile->id().name()) : QString());
writer.save(settingsFileName(), QLatin1String("QtCreatorProfiles"), Core::ICore::mainWindow());
}
bool greaterPriority(ProfileInformation *a, ProfileInformation *b)
{
return a->priority() > b->priority();
}
void ProfileManager::registerProfileInformation(ProfileInformation *pi)
{
QList<ProfileInformation *>::iterator it
= qLowerBound(d->m_informationList.begin(), d->m_informationList.end(), pi, greaterPriority);
d->m_informationList.insert(it, pi);
connect(pi, SIGNAL(validationNeeded()), this, SLOT(validateProfiles()));
if (!d->m_initialized)
return;
foreach (Profile *p, profiles()) {
if (!p->hasValue(pi->dataId()))
p->setValue(pi->dataId(), pi->defaultValue(p));
}
return;
}
void ProfileManager::deregisterProfileInformation(ProfileInformation *pi)
{
Q_ASSERT(d->m_informationList.contains(pi));
d->m_informationList.removeAll(pi);
delete pi;
}
ProfileManager::ProfileList ProfileManager::restoreProfiles(const QString &fileName)
{
ProfileList result;
PersistentSettingsReader reader;
if (!reader.load(fileName))
return result;
QVariantMap data = reader.restoreValues();
// Check version:
int version = data.value(QLatin1String(PROFILE_FILE_VERSION_KEY), 0).toInt();
if (version < 1)
return result;
const int count = data.value(QLatin1String(PROFILE_COUNT_KEY), 0).toInt();
for (int i = 0; i < count; ++i) {
const QString key = QString::fromLatin1(PROFILE_DATA_KEY) + QString::number(i);
if (!data.contains(key))
break;
const QVariantMap stMap = data.value(key).toMap();
Profile *p = new Profile;
if (p->fromMap(stMap)) {
result.profiles.append(p);
} else {
delete p;
qWarning("Warning: Unable to restore profiles stored in %s at position %d.",
qPrintable(QDir::toNativeSeparators(fileName)), i);
}
}
const QString defaultId = data.value(QLatin1String(PROFILE_DEFAULT_KEY)).toString();
if (defaultId.isEmpty())
return result;
const Core::Id id = Core::Id(defaultId);
foreach (Profile *i, result.profiles) {
if (i->id() == id) {
result.defaultProfile = id;
break;
}
}
return result;
}
QList<Profile *> ProfileManager::profiles(const ProfileMatcher *m) const
{
if (!d->m_initialized) {
d->m_initialized = true;
const_cast<ProfileManager *>(this)->restoreProfiles();
}
QList<Profile *> result;
foreach (Profile *p, d->m_profileList) {
if (!m || m->matches(p))
result.append(p);
}
return result;
}
Profile *ProfileManager::find(const Core::Id &id) const
{
if (!id.isValid())
return 0;
foreach (Profile *p, profiles()) {
if (p->id() == id)
return p;
}
return 0;
}
Profile *ProfileManager::find(const ProfileMatcher *m) const
{
QList<Profile *> matched = profiles(m);
return matched.isEmpty() ? 0 : matched.first();
}
Profile *ProfileManager::defaultProfile()
{
if (!d->m_initialized) {
d->m_initialized = true;
restoreProfiles();
}
return d->m_defaultProfile;
}
QList<ProfileInformation *> ProfileManager::profileInformation() const
{
return d->m_informationList;
}
ProfileConfigWidget *ProfileManager::createConfigWidget(Profile *p) const
{
if (!p)
return 0;
Internal::ProfileManagerConfigWidget *result = new Internal::ProfileManagerConfigWidget(p);
foreach (ProfileInformation *pi, d->m_informationList)
result->addConfigWidget(pi->createConfigWidget(p));
return result;
}
void ProfileManager::notifyAboutUpdate(ProjectExplorer::Profile *p)
{
if (!p || !profiles().contains(p))
return;
d->validateProfile(p);
emit profileUpdated(p);
}
bool ProfileManager::registerProfile(ProjectExplorer::Profile *p)
{
if (!p)
return true;
foreach (Profile *current, profiles()) {
if (p == current)
return false;
}
// make sure we have all the information in our profiles:
foreach (ProfileInformation *pi, d->m_informationList) {
if (!p->hasValue(pi->dataId()))
p->setValue(pi->dataId(), pi->defaultValue(p));
}
addProfile(p);
emit profileAdded(p);
return true;
}
void ProfileManager::deregisterProfile(Profile *p)
{
if (!p || !profiles().contains(p))
return;
d->m_profileList.removeOne(p);
if (d->m_defaultProfile == p) {
QList<Profile *> stList = profiles();
Profile *newDefault = 0;
foreach (Profile *cur, stList) {
if (cur->isValid()) {
newDefault = cur;
break;
}
}
setDefaultProfile(newDefault);
}
emit profileRemoved(p);
delete p;
}
QList<Task> ProfileManager::validateProfile(Profile *p)
{
QList<Task> result = d->validateProfile(p);
qSort(result);
return result;
}
void ProfileManager::setDefaultProfile(Profile *p)
{
if (d->m_defaultProfile == p)
return;
if (p && !profiles().contains(p))
return;
d->m_defaultProfile = p;
emit defaultProfileChanged();
}
void ProfileManager::validateProfiles()
{
foreach (Profile *p, profiles())
d->validateProfile(p);
}
void ProfileManager::addProfile(Profile *p)
{
if (!p)
return;
d->validateProfile(p);
d->m_profileList.append(p);
if (!d->m_defaultProfile ||
(!d->m_defaultProfile->isValid() && p->isValid()))
setDefaultProfile(p);
}
void ProfileInformation::addToEnvironment(const Profile *p, Utils::Environment &env) const
{
Q_UNUSED(p);
Q_UNUSED(env);
}
} // namespace ProjectExplorer
<|endoftext|> |
<commit_before>#include "hook_manager.hh"
#include "containers.hh"
#include "context.hh"
#include "buffer_utils.hh"
#include "display_buffer.hh"
#include "face_registry.hh"
#include "regex.hh"
#include <chrono>
namespace Kakoune
{
void HookManager::add_hook(StringView hook_name, String group, HookFunc hook)
{
auto& hooks = m_hook[hook_name];
hooks.append({std::move(group), std::move(hook)});
}
void HookManager::remove_hooks(StringView group)
{
if (group.empty())
throw runtime_error("invalid id");
for (auto& hooks : m_hook)
hooks.value.remove_all(group);
}
CandidateList HookManager::complete_hook_group(StringView prefix, ByteCount pos_in_token)
{
CandidateList res;
for (auto& list : m_hook)
{
auto container = list.value | transform(decltype(list.value)::get_id);
for (auto& c : complete(prefix, pos_in_token, container))
{
if (!contains(res, c))
res.push_back(c);
}
}
return res;
}
void HookManager::run_hook(StringView hook_name,
StringView param, Context& context) const
{
if (m_parent)
m_parent->run_hook(hook_name, param, context);
auto hook_list_it = m_hook.find(hook_name);
if (hook_list_it == m_hook.end())
return;
if (contains(m_running_hooks, std::make_pair(hook_name, param)))
{
auto error = format("recursive call of hook {}/{}, aborting", hook_name, param);
write_to_debug_buffer(error);
throw runtime_error(std::move(error));
}
m_running_hooks.emplace_back(hook_name, param);
auto pop_running_hook = on_scope_end([this]{ m_running_hooks.pop_back(); });
using Clock = std::chrono::steady_clock;
using TimePoint = Clock::time_point;
const DebugFlags debug_flags = context.options()["debug"].get<DebugFlags>();
const bool profile = debug_flags & DebugFlags::Profile;
auto start_time = profile ? Clock::now() : TimePoint{};
auto& disabled_hooks = context.options()["disabled_hooks"].get<Regex>();
bool hook_error = false;
for (auto& hook : hook_list_it->value)
{
if (not hook.key.empty() and not disabled_hooks.empty() and
regex_match(hook.key.begin(), hook.key.end(), disabled_hooks))
continue;
try
{
if (debug_flags & DebugFlags::Hooks)
write_to_debug_buffer(format("hook {}/{}", hook_name, hook.key));
hook.value(param, context);
}
catch (runtime_error& err)
{
hook_error = true;
write_to_debug_buffer(format("error running hook {}({})/{}: {}",
hook_name, param, hook.key, err.what()));
}
}
if (hook_error)
context.print_status({
format("Error running hooks for '{}' '{}', see *debug* buffer",
hook_name, param), get_face("Error") });
if (profile)
{
auto end_time = Clock::now();
auto full = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
write_to_debug_buffer(format("hook '{}({})' took {} ms", hook_name, param, (size_t)full.count()));
}
}
}
<commit_msg>Do not throw when recursive hook calls are detected<commit_after>#include "hook_manager.hh"
#include "containers.hh"
#include "context.hh"
#include "buffer_utils.hh"
#include "display_buffer.hh"
#include "face_registry.hh"
#include "regex.hh"
#include <chrono>
namespace Kakoune
{
void HookManager::add_hook(StringView hook_name, String group, HookFunc hook)
{
auto& hooks = m_hook[hook_name];
hooks.append({std::move(group), std::move(hook)});
}
void HookManager::remove_hooks(StringView group)
{
if (group.empty())
throw runtime_error("invalid id");
for (auto& hooks : m_hook)
hooks.value.remove_all(group);
}
CandidateList HookManager::complete_hook_group(StringView prefix, ByteCount pos_in_token)
{
CandidateList res;
for (auto& list : m_hook)
{
auto container = list.value | transform(decltype(list.value)::get_id);
for (auto& c : complete(prefix, pos_in_token, container))
{
if (!contains(res, c))
res.push_back(c);
}
}
return res;
}
void HookManager::run_hook(StringView hook_name,
StringView param, Context& context) const
{
if (m_parent)
m_parent->run_hook(hook_name, param, context);
auto hook_list_it = m_hook.find(hook_name);
if (hook_list_it == m_hook.end())
return;
if (contains(m_running_hooks, std::make_pair(hook_name, param)))
{
auto error = format("recursive call of hook {}/{}, not executing", hook_name, param);
write_to_debug_buffer(error);
return;
}
m_running_hooks.emplace_back(hook_name, param);
auto pop_running_hook = on_scope_end([this]{ m_running_hooks.pop_back(); });
using Clock = std::chrono::steady_clock;
using TimePoint = Clock::time_point;
const DebugFlags debug_flags = context.options()["debug"].get<DebugFlags>();
const bool profile = debug_flags & DebugFlags::Profile;
auto start_time = profile ? Clock::now() : TimePoint{};
auto& disabled_hooks = context.options()["disabled_hooks"].get<Regex>();
bool hook_error = false;
for (auto& hook : hook_list_it->value)
{
if (not hook.key.empty() and not disabled_hooks.empty() and
regex_match(hook.key.begin(), hook.key.end(), disabled_hooks))
continue;
try
{
if (debug_flags & DebugFlags::Hooks)
write_to_debug_buffer(format("hook {}/{}", hook_name, hook.key));
hook.value(param, context);
}
catch (runtime_error& err)
{
hook_error = true;
write_to_debug_buffer(format("error running hook {}({})/{}: {}",
hook_name, param, hook.key, err.what()));
}
}
if (hook_error)
context.print_status({
format("Error running hooks for '{}' '{}', see *debug* buffer",
hook_name, param), get_face("Error") });
if (profile)
{
auto end_time = Clock::now();
auto full = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
write_to_debug_buffer(format("hook '{}({})' took {} ms", hook_name, param, (size_t)full.count()));
}
}
}
<|endoftext|> |
<commit_before><?hh
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
namespace pocketmine\level\format\anvil;
use pocketmine\level\Level;
use pocketmine\nbt\NBT;
use pocketmine\scheduler\AsyncTask;
use pocketmine\Server;
use pocketmine\tile\Spawnable;
class ChunkRequestTask extends AsyncTask{
protected $levelId;
protected $chunk;
protected $chunkX;
protected $chunkZ;
protected $tiles;
public function __construct(Level $level, Chunk $chunk){
$this->levelId = $level->getId();
$this->chunk = $chunk->toFastBinary();
$this->chunkX = $chunk->getX();
$this->chunkZ = $chunk->getZ();
$tiles = "";
$nbt = new NBT(NBT::LITTLE_ENDIAN);
foreach($chunk->getTiles() as $tile){
if($tile instanceof Spawnable){
$nbt->setData($tile->getSpawnCompound());
$tiles .= $nbt->write();
}
}
$this->tiles = $tiles;
}
public function onRun(){
$chunk = Chunk::fromFastBinary($this->chunk);
$ids = $chunk->getBlockIdArray();
$meta = $chunk->getBlockDataArray();
$blockLight = $chunk->getBlockLightArray();
$skyLight = $chunk->getBlockSkyLightArray();
$orderedIds = "";
$orderedData = "";
$orderedSkyLight = "";
$orderedLight = "";
for($x = 0; $x < 16; ++$x){
for($z = 0; $z < 16; ++$z){
$orderedIds .= $this->getColumn($ids, $x, $z);
$orderedData .= $this->getHalfColumn($meta, $x, $z);
$orderedSkyLight .= $this->getHalfColumn($skyLight, $x, $z);
$orderedLight .= $this->getHalfColumn($blockLight, $x, $z);
}
}
$heightmap = pack("C*", ...$chunk->getHeightMapArray());
$biomeColors = pack("N*", ...$chunk->getBiomeColorArray());
$ordered = $orderedIds . $orderedData . $orderedSkyLight . $orderedLight . $heightmap . $biomeColors . $this->tiles;
$this->setResult($ordered, false);
}
public function getColumn($data, $x, $z){
$column = "";
$i = ($z << 4) + $x;
for($y = 0; $y < 128; ++$y){
$column .= $data{($y << 8) + $i};
}
return $column;
}
public function getHalfColumn($data, $x, $z){
$column = "";
$i = ($z << 3) + ($x >> 1);
if(($x & 1) === 0){
for($y = 0; $y < 128; $y += 2){
$column .= ($data{($y << 7) + $i} & "\x0f") | chr((ord($data{(($y + 1) << 7) + $i}) & 0x0f) << 4);
}
}else{
for($y = 0; $y < 128; $y += 2){
$column .= chr((ord($data{($y << 7) + $i}) & 0xf0) >> 4) | ($data{(($y + 1) << 7) + $i} & "\xf0");
}
}
return $column;
}
public function onCompletion(Server $server){
$level = $server->getLevel($this->levelId);
if($level instanceof Level and $this->hasResult()){
$level->chunkRequestCallback($this->chunkX, $this->chunkZ, $this->getResult());
}
}
}<commit_msg>Delete ChunkRequestTask.hh<commit_after><|endoftext|> |
<commit_before>// Copyright 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: morlovich@google.com (Maksim Orlovich)
#include "net/instaweb/util/public/shared_mem_test_base.h"
#include <cstddef>
#include "net/instaweb/util/public/abstract_mutex.h"
#include "net/instaweb/util/public/abstract_shared_mem.h"
#include "net/instaweb/util/public/function.h"
#include "net/instaweb/util/public/gtest.h"
#include "net/instaweb/util/public/mock_message_handler.h"
#include "net/instaweb/util/public/scoped_ptr.h"
namespace net_instaweb {
namespace {
const char kTestSegment[] = "segment1";
const char kOtherSegment[] = "segment2";
} // namespace
SharedMemTestEnv::~SharedMemTestEnv() {
}
SharedMemTestBase::SharedMemTestBase(SharedMemTestEnv* test_env)
: test_env_(test_env),
shmem_runtime_(test_env->CreateSharedMemRuntime()) {
}
bool SharedMemTestBase::CreateChild(TestMethod method) {
Function* callback = new MemberFunction0<SharedMemTestBase>(method, this);
return test_env_->CreateChild(callback);
}
void SharedMemTestBase::TestReadWrite(bool reattach) {
scoped_ptr<AbstractSharedMemSegment> seg(CreateDefault());
ASSERT_TRUE(seg.get() != NULL);
ASSERT_TRUE(CreateChild(&SharedMemTestBase::TestReadWriteChild));
if (reattach) {
seg.reset(AttachDefault());
}
// Wait for kid to write out stuff
while (*seg->Base() != '1') {
test_env_->ShortSleep();
}
// Write out stuff.
*seg->Base() = '2';
// Wait for termination.
test_env_->WaitForChildren();
seg.reset(NULL);
DestroyDefault();
EXPECT_EQ(0, handler_.SeriousMessages());
}
void SharedMemTestBase::TestReadWriteChild() {
scoped_ptr<AbstractSharedMemSegment> seg(AttachDefault());
// Write out '1', which the parent will wait for.
*seg->Base() = '1';
// Wait for '2' from parent
while (*seg->Base() != '2') {
test_env_->ShortSleep();
}
}
void SharedMemTestBase::TestLarge() {
scoped_ptr<AbstractSharedMemSegment> seg(
shmem_runtime_->CreateSegment(kTestSegment, kLarge, &handler_));
ASSERT_TRUE(seg.get() != NULL);
// Make sure everything is zeroed
for (int c = 0; c < kLarge; ++c) {
EXPECT_EQ(0, seg->Base()[c]);
}
seg.reset(NULL);
ASSERT_TRUE(CreateChild(&SharedMemTestBase::TestLargeChild));
test_env_->WaitForChildren();
seg.reset(shmem_runtime_->AttachToSegment(kTestSegment, kLarge, &handler_));
for (int i = 0; i < kLarge; i+=4) {
EXPECT_EQ(i, *IntPtr(seg.get(), i));
}
}
void SharedMemTestBase::TestLargeChild() {
scoped_ptr<AbstractSharedMemSegment> seg(
shmem_runtime_->AttachToSegment(kTestSegment, kLarge, &handler_));
for (int i = 0; i < kLarge; i+=4) {
*IntPtr(seg.get(), i) = i;
}
}
// Make sure that 2 segments don't interfere.
void SharedMemTestBase::TestDistinct() {
scoped_ptr<AbstractSharedMemSegment> seg(CreateDefault());
ASSERT_TRUE(seg.get() != NULL);
scoped_ptr<AbstractSharedMemSegment> seg2(
shmem_runtime_->CreateSegment(kOtherSegment, 4, &handler_));
ASSERT_TRUE(seg2.get() != NULL);
ASSERT_TRUE(CreateChild(&SharedMemTestBase::WriteSeg1Child));
ASSERT_TRUE(CreateChild(&SharedMemTestBase::WriteSeg2Child));
test_env_->WaitForChildren();
EXPECT_EQ('1', *seg->Base());
EXPECT_EQ('2', *seg2->Base());
seg.reset(NULL);
seg2.reset(NULL);
DestroyDefault();
shmem_runtime_->DestroySegment(kOtherSegment, &handler_);
EXPECT_EQ(0, handler_.SeriousMessages());
}
// Make sure destruction destroys things properly...
void SharedMemTestBase::TestDestroy() {
scoped_ptr<AbstractSharedMemSegment> seg(CreateDefault());
ASSERT_TRUE(seg.get() != NULL);
ASSERT_TRUE(CreateChild(&SharedMemTestBase::WriteSeg1Child));
test_env_->WaitForChildren();
EXPECT_EQ('1', *seg->Base());
seg.reset(NULL);
DestroyDefault();
// Attach should fail now
seg.reset(AttachDefault());
EXPECT_EQ(NULL, seg.get());
// Newly created one should have zeroed memory
seg.reset(CreateDefault());
EXPECT_EQ('\0', *seg->Base());
DestroyDefault();
}
// Make sure that re-creating a segment without a Destroy is safe and
// produces a distinct segment
void SharedMemTestBase::TestCreateTwice() {
scoped_ptr<AbstractSharedMemSegment> seg(CreateDefault());
ASSERT_TRUE(seg.get() != NULL);
ASSERT_TRUE(CreateChild(&SharedMemTestBase::WriteSeg1Child));
test_env_->WaitForChildren();
EXPECT_EQ('1', *seg->Base());
seg.reset(CreateDefault());
EXPECT_EQ('\0', *seg->Base());
}
// Make sure between two kids see the SHM as well.
void SharedMemTestBase::TestTwoKids() {
scoped_ptr<AbstractSharedMemSegment> seg(CreateDefault());
ASSERT_TRUE(seg.get() != NULL);
seg.reset(NULL);
ASSERT_TRUE(CreateChild(&SharedMemTestBase::TwoKidsChild1));
ASSERT_TRUE(CreateChild(&SharedMemTestBase::TwoKidsChild2));
test_env_->WaitForChildren();
seg.reset(AttachDefault());
EXPECT_EQ('2', *seg->Base());
DestroyDefault();
EXPECT_EQ(0, handler_.SeriousMessages());
}
void SharedMemTestBase::TwoKidsChild1() {
scoped_ptr<AbstractSharedMemSegment> seg(AttachDefault());
ASSERT_TRUE(seg.get() != NULL);
// Write out '1', which the other kid will wait for.
*seg->Base() = '1';
}
void SharedMemTestBase::TwoKidsChild2() {
scoped_ptr<AbstractSharedMemSegment> seg(AttachDefault());
ASSERT_TRUE(seg.get() != NULL);
// Wait for '1'
while (*seg->Base() != '1') {
test_env_->ShortSleep();
}
*seg->Base() = '2';
}
// Test for mutex operation. This attempts to detect lack of mutual exclusion
// by hammering on a shared location (protected by a lock) with non-atomic
// increments. This test does not guarantee that it will detect a failure
// (the schedule might just end up such that things work out), but it's
// been found to be effective in practice.
void SharedMemTestBase::TestMutex() {
size_t mutex_size = shmem_runtime_->SharedMutexSize();
scoped_ptr<AbstractSharedMemSegment> seg(
shmem_runtime_->CreateSegment(kTestSegment, mutex_size + 4, &handler_));
ASSERT_TRUE(seg.get() != NULL);
ASSERT_EQ(mutex_size, seg->SharedMutexSize());
ASSERT_TRUE(seg->InitializeSharedMutex(0, &handler_));
seg.reset(
shmem_runtime_->AttachToSegment(kTestSegment, mutex_size + 4, &handler_));
scoped_ptr<AbstractMutex> mutex(seg->AttachToSharedMutex(0));
mutex->Lock();
ASSERT_TRUE(CreateChild(&SharedMemTestBase::MutexChild));
// Unblock the kid. Before that, it shouldn't have written
EXPECT_EQ(0, *IntPtr(seg.get(), mutex_size));
mutex->Unlock();
mutex->Lock();
EXPECT_TRUE(IncrementStorm(seg.get(), mutex_size));
mutex->Unlock();
test_env_->WaitForChildren();
DestroyDefault();
}
void SharedMemTestBase::MutexChild() {
size_t mutex_size = shmem_runtime_->SharedMutexSize();
scoped_ptr<AbstractSharedMemSegment> seg(
shmem_runtime_->AttachToSegment(kTestSegment, mutex_size + 4, &handler_));
ASSERT_TRUE(seg.get() != NULL);
scoped_ptr<AbstractMutex> mutex(seg->AttachToSharedMutex(0));
mutex->Lock();
if (!IncrementStorm(seg.get(), mutex_size)) {
mutex->Unlock();
test_env_->ChildFailed();
return;
}
mutex->Unlock();
}
// Returns if successful
bool SharedMemTestBase::IncrementStorm(AbstractSharedMemSegment* seg,
size_t mutex_size) {
// We are either the first or second to do the increments.
int init = *IntPtr(seg, mutex_size);
if ((init != 0) && (init != kNumIncrements)) {
return false;
}
for (int i = 0; i < kNumIncrements; ++i) {
++*IntPtr(seg, mutex_size);
if (*IntPtr(seg, mutex_size) != (i + init + 1)) {
return false;
}
++*IntPtr(seg, mutex_size);
if (*IntPtr(seg, mutex_size) != (i + init + 2)) {
return false;
}
--*IntPtr(seg, mutex_size);
if (*IntPtr(seg, mutex_size) != (i + init + 1)) {
return false;
}
}
return true;
}
void SharedMemTestBase::WriteSeg1Child() {
scoped_ptr<AbstractSharedMemSegment> seg(AttachDefault());
ASSERT_TRUE(seg.get() != NULL);
*seg->Base() = '1';
}
void SharedMemTestBase::WriteSeg2Child() {
scoped_ptr<AbstractSharedMemSegment> seg(
shmem_runtime_->AttachToSegment(kOtherSegment, 4, &handler_));
ASSERT_TRUE(seg.get() != NULL);
*seg->Base() = '2';
}
AbstractSharedMemSegment* SharedMemTestBase::CreateDefault() {
return shmem_runtime_->CreateSegment(kTestSegment, 4, &handler_);
}
AbstractSharedMemSegment* SharedMemTestBase::AttachDefault() {
return shmem_runtime_->AttachToSegment(kTestSegment, 4, &handler_);
}
void SharedMemTestBase::DestroyDefault() {
shmem_runtime_->DestroySegment(kTestSegment, &handler_);
}
} // namespace net_instaweb
<commit_msg>Cleanup segments here, to avoid valgrind warnings.<commit_after>// Copyright 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: morlovich@google.com (Maksim Orlovich)
#include "net/instaweb/util/public/shared_mem_test_base.h"
#include <cstddef>
#include "net/instaweb/util/public/abstract_mutex.h"
#include "net/instaweb/util/public/abstract_shared_mem.h"
#include "net/instaweb/util/public/function.h"
#include "net/instaweb/util/public/gtest.h"
#include "net/instaweb/util/public/mock_message_handler.h"
#include "net/instaweb/util/public/scoped_ptr.h"
namespace net_instaweb {
namespace {
const char kTestSegment[] = "segment1";
const char kOtherSegment[] = "segment2";
} // namespace
SharedMemTestEnv::~SharedMemTestEnv() {
}
SharedMemTestBase::SharedMemTestBase(SharedMemTestEnv* test_env)
: test_env_(test_env),
shmem_runtime_(test_env->CreateSharedMemRuntime()) {
}
bool SharedMemTestBase::CreateChild(TestMethod method) {
Function* callback = new MemberFunction0<SharedMemTestBase>(method, this);
return test_env_->CreateChild(callback);
}
void SharedMemTestBase::TestReadWrite(bool reattach) {
scoped_ptr<AbstractSharedMemSegment> seg(CreateDefault());
ASSERT_TRUE(seg.get() != NULL);
ASSERT_TRUE(CreateChild(&SharedMemTestBase::TestReadWriteChild));
if (reattach) {
seg.reset(AttachDefault());
}
// Wait for kid to write out stuff
while (*seg->Base() != '1') {
test_env_->ShortSleep();
}
// Write out stuff.
*seg->Base() = '2';
// Wait for termination.
test_env_->WaitForChildren();
seg.reset(NULL);
DestroyDefault();
EXPECT_EQ(0, handler_.SeriousMessages());
}
void SharedMemTestBase::TestReadWriteChild() {
scoped_ptr<AbstractSharedMemSegment> seg(AttachDefault());
// Write out '1', which the parent will wait for.
*seg->Base() = '1';
// Wait for '2' from parent
while (*seg->Base() != '2') {
test_env_->ShortSleep();
}
}
void SharedMemTestBase::TestLarge() {
scoped_ptr<AbstractSharedMemSegment> seg(
shmem_runtime_->CreateSegment(kTestSegment, kLarge, &handler_));
ASSERT_TRUE(seg.get() != NULL);
// Make sure everything is zeroed
for (int c = 0; c < kLarge; ++c) {
EXPECT_EQ(0, seg->Base()[c]);
}
seg.reset(NULL);
ASSERT_TRUE(CreateChild(&SharedMemTestBase::TestLargeChild));
test_env_->WaitForChildren();
seg.reset(shmem_runtime_->AttachToSegment(kTestSegment, kLarge, &handler_));
for (int i = 0; i < kLarge; i+=4) {
EXPECT_EQ(i, *IntPtr(seg.get(), i));
}
DestroyDefault();
}
void SharedMemTestBase::TestLargeChild() {
scoped_ptr<AbstractSharedMemSegment> seg(
shmem_runtime_->AttachToSegment(kTestSegment, kLarge, &handler_));
for (int i = 0; i < kLarge; i+=4) {
*IntPtr(seg.get(), i) = i;
}
}
// Make sure that 2 segments don't interfere.
void SharedMemTestBase::TestDistinct() {
scoped_ptr<AbstractSharedMemSegment> seg(CreateDefault());
ASSERT_TRUE(seg.get() != NULL);
scoped_ptr<AbstractSharedMemSegment> seg2(
shmem_runtime_->CreateSegment(kOtherSegment, 4, &handler_));
ASSERT_TRUE(seg2.get() != NULL);
ASSERT_TRUE(CreateChild(&SharedMemTestBase::WriteSeg1Child));
ASSERT_TRUE(CreateChild(&SharedMemTestBase::WriteSeg2Child));
test_env_->WaitForChildren();
EXPECT_EQ('1', *seg->Base());
EXPECT_EQ('2', *seg2->Base());
seg.reset(NULL);
seg2.reset(NULL);
DestroyDefault();
shmem_runtime_->DestroySegment(kOtherSegment, &handler_);
EXPECT_EQ(0, handler_.SeriousMessages());
}
// Make sure destruction destroys things properly...
void SharedMemTestBase::TestDestroy() {
scoped_ptr<AbstractSharedMemSegment> seg(CreateDefault());
ASSERT_TRUE(seg.get() != NULL);
ASSERT_TRUE(CreateChild(&SharedMemTestBase::WriteSeg1Child));
test_env_->WaitForChildren();
EXPECT_EQ('1', *seg->Base());
seg.reset(NULL);
DestroyDefault();
// Attach should fail now
seg.reset(AttachDefault());
EXPECT_EQ(NULL, seg.get());
// Newly created one should have zeroed memory
seg.reset(CreateDefault());
EXPECT_EQ('\0', *seg->Base());
DestroyDefault();
}
// Make sure that re-creating a segment without a Destroy is safe and
// produces a distinct segment
void SharedMemTestBase::TestCreateTwice() {
scoped_ptr<AbstractSharedMemSegment> seg(CreateDefault());
ASSERT_TRUE(seg.get() != NULL);
ASSERT_TRUE(CreateChild(&SharedMemTestBase::WriteSeg1Child));
test_env_->WaitForChildren();
EXPECT_EQ('1', *seg->Base());
seg.reset(CreateDefault());
EXPECT_EQ('\0', *seg->Base());
DestroyDefault();
}
// Make sure between two kids see the SHM as well.
void SharedMemTestBase::TestTwoKids() {
scoped_ptr<AbstractSharedMemSegment> seg(CreateDefault());
ASSERT_TRUE(seg.get() != NULL);
seg.reset(NULL);
ASSERT_TRUE(CreateChild(&SharedMemTestBase::TwoKidsChild1));
ASSERT_TRUE(CreateChild(&SharedMemTestBase::TwoKidsChild2));
test_env_->WaitForChildren();
seg.reset(AttachDefault());
EXPECT_EQ('2', *seg->Base());
DestroyDefault();
EXPECT_EQ(0, handler_.SeriousMessages());
}
void SharedMemTestBase::TwoKidsChild1() {
scoped_ptr<AbstractSharedMemSegment> seg(AttachDefault());
ASSERT_TRUE(seg.get() != NULL);
// Write out '1', which the other kid will wait for.
*seg->Base() = '1';
}
void SharedMemTestBase::TwoKidsChild2() {
scoped_ptr<AbstractSharedMemSegment> seg(AttachDefault());
ASSERT_TRUE(seg.get() != NULL);
// Wait for '1'
while (*seg->Base() != '1') {
test_env_->ShortSleep();
}
*seg->Base() = '2';
}
// Test for mutex operation. This attempts to detect lack of mutual exclusion
// by hammering on a shared location (protected by a lock) with non-atomic
// increments. This test does not guarantee that it will detect a failure
// (the schedule might just end up such that things work out), but it's
// been found to be effective in practice.
void SharedMemTestBase::TestMutex() {
size_t mutex_size = shmem_runtime_->SharedMutexSize();
scoped_ptr<AbstractSharedMemSegment> seg(
shmem_runtime_->CreateSegment(kTestSegment, mutex_size + 4, &handler_));
ASSERT_TRUE(seg.get() != NULL);
ASSERT_EQ(mutex_size, seg->SharedMutexSize());
ASSERT_TRUE(seg->InitializeSharedMutex(0, &handler_));
seg.reset(
shmem_runtime_->AttachToSegment(kTestSegment, mutex_size + 4, &handler_));
scoped_ptr<AbstractMutex> mutex(seg->AttachToSharedMutex(0));
mutex->Lock();
ASSERT_TRUE(CreateChild(&SharedMemTestBase::MutexChild));
// Unblock the kid. Before that, it shouldn't have written
EXPECT_EQ(0, *IntPtr(seg.get(), mutex_size));
mutex->Unlock();
mutex->Lock();
EXPECT_TRUE(IncrementStorm(seg.get(), mutex_size));
mutex->Unlock();
test_env_->WaitForChildren();
DestroyDefault();
}
void SharedMemTestBase::MutexChild() {
size_t mutex_size = shmem_runtime_->SharedMutexSize();
scoped_ptr<AbstractSharedMemSegment> seg(
shmem_runtime_->AttachToSegment(kTestSegment, mutex_size + 4, &handler_));
ASSERT_TRUE(seg.get() != NULL);
scoped_ptr<AbstractMutex> mutex(seg->AttachToSharedMutex(0));
mutex->Lock();
if (!IncrementStorm(seg.get(), mutex_size)) {
mutex->Unlock();
test_env_->ChildFailed();
return;
}
mutex->Unlock();
}
// Returns if successful
bool SharedMemTestBase::IncrementStorm(AbstractSharedMemSegment* seg,
size_t mutex_size) {
// We are either the first or second to do the increments.
int init = *IntPtr(seg, mutex_size);
if ((init != 0) && (init != kNumIncrements)) {
return false;
}
for (int i = 0; i < kNumIncrements; ++i) {
++*IntPtr(seg, mutex_size);
if (*IntPtr(seg, mutex_size) != (i + init + 1)) {
return false;
}
++*IntPtr(seg, mutex_size);
if (*IntPtr(seg, mutex_size) != (i + init + 2)) {
return false;
}
--*IntPtr(seg, mutex_size);
if (*IntPtr(seg, mutex_size) != (i + init + 1)) {
return false;
}
}
return true;
}
void SharedMemTestBase::WriteSeg1Child() {
scoped_ptr<AbstractSharedMemSegment> seg(AttachDefault());
ASSERT_TRUE(seg.get() != NULL);
*seg->Base() = '1';
}
void SharedMemTestBase::WriteSeg2Child() {
scoped_ptr<AbstractSharedMemSegment> seg(
shmem_runtime_->AttachToSegment(kOtherSegment, 4, &handler_));
ASSERT_TRUE(seg.get() != NULL);
*seg->Base() = '2';
}
AbstractSharedMemSegment* SharedMemTestBase::CreateDefault() {
return shmem_runtime_->CreateSegment(kTestSegment, 4, &handler_);
}
AbstractSharedMemSegment* SharedMemTestBase::AttachDefault() {
return shmem_runtime_->AttachToSegment(kTestSegment, 4, &handler_);
}
void SharedMemTestBase::DestroyDefault() {
shmem_runtime_->DestroySegment(kTestSegment, &handler_);
}
} // namespace net_instaweb
<|endoftext|> |
<commit_before>/* Copyright (C) 2010-present, Zhenkai Zhu <zhenkai@cs.ucla.edu>
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 Mumble Developers 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 FOUNDATION 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 "murmur_pch.h"
#include "RemoteUser.h"
#define REFRESH_INTERVAL 10
#define REMOVE_INTERVAL 21
RemoteUser::RemoteUser(QString prefix, QString name) : remoteUserPrefix(prefix) {
qsName = name;
timestamp = QDateTime::currentDateTime();
left = false;
}
void RemoteUser::refreshReceived() {
timestamp = QDateTime::currentDateTime();
}
bool RemoteUser::needRefresh() {
QDateTime now = QDateTime::currentDateTime();
if (timestamp.secsTo(now) > REFRESH_INTERVAL) {
return true;
}
return false;
}
bool RemoteUser::isStaled() {
if (left)
return true;
QDateTime now = QDateTime::currentDateTime();
if (timestamp.secsTo(now) > REMOVE_INTERVAL) {
return true;
}
return false;
}
<commit_msg>check timestamp is not null<commit_after>/* Copyright (C) 2010-present, Zhenkai Zhu <zhenkai@cs.ucla.edu>
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 Mumble Developers 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 FOUNDATION 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 "murmur_pch.h"
#include "RemoteUser.h"
#define REFRESH_INTERVAL 10
#define REMOVE_INTERVAL 21
RemoteUser::RemoteUser(QString prefix, QString name) : remoteUserPrefix(prefix) {
qsName = name;
timestamp = QDateTime::currentDateTime();
left = false;
}
void RemoteUser::refreshReceived() {
timestamp = QDateTime::currentDateTime();
}
bool RemoteUser::needRefresh() {
QDateTime now = QDateTime::currentDateTime();
if (timestamp.secsTo(now) > REFRESH_INTERVAL) {
return true;
}
return false;
}
bool RemoteUser::isStaled() {
if (left)
return true;
QDateTime now = QDateTime::currentDateTime();
if (timestamp.isNull()) {
fprintf(stderr, "timestamp is null, will initialize one");
timestamp = QDateTime::currentDateTime();
}
if (timestamp.secsTo(now) > REMOVE_INTERVAL) {
return true;
}
return false;
}
<|endoftext|> |
<commit_before>/**@file hdfsdumper.cpp
* @brief CLI utility that wraps hdfsdumpreader code into a CLI program.
*
*/
#include "hdfscpp.h"
#include "hdfsdumpreader.h"
#include <iostream>
void ShowUsage()
{
std::cerr << "Usage: hdfsdumper <path> " << std::endl;
}
void ProcessFile(tmacam::hdfs::FileSystem* fs, const char* path)
{
using namespace tmacam;
HdfsDumpReader reader(fs, path);
while(reader.HasNext()) {
reader.GetNext();
std::cout << ".";
std::cout.flush();
}
std::cout<< std::endl;
}
void ProcessDirectory(tmacam::hdfs::FileSystem* fs, const char* path)
{
using namespace tmacam;
hdfs::FileInfoList files;
fs->ListDirectory(path, &files);
if (files.empty()) {
std::cout << "Directory is empty" << std::endl;
} else {
for (int i = 0; i < files.size(); ++i) {
std::cout << "# " << files[i].mName << std::endl;
ProcessFile(fs, files[i].mName);
}
}
}
int main(int argc, char* argv[])
{
using namespace tmacam;
// Check command line arguments
if ( argc != 2) {
std::cerr << "Wrong number of arguments" << std::endl;
ShowUsage();
exit(EXIT_FAILURE);
}
const char* path = argv[1];
// Connect to HDFS / get filesystem handle
hdfs::FileSystem fs;
// Path is a file, right?
if (!fs.Exists(path)) {
std::cerr << "Path '" << path << "' does not exist." << std::endl;
exit(EXIT_FAILURE);
}
hdfs::FileInfoList path_info;
fs.GetPathInfo(path, &path_info);
switch (path_info->mKind) {
case kObjectKindFile:
// reader.ReadFile();
ProcessFile(&fs, path);
break;
case kObjectKindDirectory:
ProcessDirectory(&fs, path);
break;
default:
std::cerr << "Path '" << path << "' is not a regular file " <<
"nor a directory." << std::endl;
exit(EXIT_FAILURE);
break;
}
return 0;
}
// vim: et ai sts=4 ts=4 sw=4
<commit_msg>Aux. function added to hdfsdumper<commit_after>/**@file hdfsdumper.cpp
* @brief CLI utility that wraps hdfsdumpreader code into a CLI program.
*
*/
#include "hdfscpp.h"
#include "hdfsdumpreader.h"
#include <iostream>
#include <vector>
#include <string>
#include <assert.h>
#include <algorithm>
/**Retrieve a sorted list of the entries inside a given directory
*
* @param fs FileSystem handle
* @param path Path to be checked. Should be a directory.
* @param files Vector through which the file list will be returned.
*
*/
void ListDirectoryEntries(tmacam::hdfs::FileSystem* fs, const char* path,
std::vector<std::string>* files)
{
using namespace tmacam;
assert(files);
files->clear();
// We are dealing with a directory.. right? XXX check
hdfs::FileInfoList info_list;
fs->ListDirectory(path, &info_list);
if (info_list.empty()) {
return;
} else {
files->reserve(info_list.size());
for (int i = 0; i < info_list.size(); ++i) {
files->push_back(info_list[i].mName);
}
std::sort(files->begin(), files->end());
}
}
void ShowUsage()
{
std::cerr << "Usage: hdfsdumper <path> " << std::endl;
}
void ProcessFile(tmacam::hdfs::FileSystem* fs, const char* path)
{
using namespace tmacam;
HdfsDumpReader reader(fs, path);
while(reader.HasNext()) {
reader.GetNext();
std::cout << ".";
std::cout.flush();
}
std::cout<< std::endl;
}
void ProcessDirectory(tmacam::hdfs::FileSystem* fs, const char* path)
{
using namespace tmacam;
hdfs::FileInfoList files;
fs->ListDirectory(path, &files);
if (files.empty()) {
std::cout << "Directory is empty" << std::endl;
} else {
for (int i = 0; i < files.size(); ++i) {
std::cout << "# " << files[i].mName << std::endl;
ProcessFile(fs, files[i].mName);
}
}
}
void ProcessDirectory2(tmacam::hdfs::FileSystem* fs, const char* path)
{
using namespace tmacam;
std::vector<std::string> files;
ListDirectoryEntries(fs, path, &files);
if (files.empty()) {
std::cout << "Directory is empty" << std::endl;
} else {
for (int i = 0; i < files.size(); ++i) {
std::cout << "# " << files[i] << std::endl;
ProcessFile(fs, files[i].c_str());
}
}
}
int main(int argc, char* argv[])
{
using namespace tmacam;
// Check command line arguments
if ( argc != 2) {
std::cerr << "Wrong number of arguments" << std::endl;
ShowUsage();
exit(EXIT_FAILURE);
}
const char* path = argv[1];
// Connect to HDFS / get filesystem handle
hdfs::FileSystem fs;
// Path is a file, right?
if (!fs.Exists(path)) {
std::cerr << "Path '" << path << "' does not exist." << std::endl;
exit(EXIT_FAILURE);
}
hdfs::FileInfoList path_info;
fs.GetPathInfo(path, &path_info);
switch (path_info->mKind) {
case kObjectKindFile:
// reader.ReadFile();
ProcessFile(&fs, path);
break;
case kObjectKindDirectory:
ProcessDirectory2(&fs, path);
break;
default:
std::cerr << "Path '" << path << "' is not a regular file " <<
"nor a directory." << std::endl;
exit(EXIT_FAILURE);
break;
}
return 0;
}
// vim: et ai sts=4 ts=4 sw=4
<|endoftext|> |
<commit_before>#include <iostream>
#include <cmath>
/*
* # Calculate Force
* F = (GmM)/d^2 ((Gravitational Constant * Mass-1 * Mass-2) / Distance^2)
* # Resolve Vectors
* Fx = FcosA
* Fy = FsinA
* # Calcualate Acceleration
* a = F/m (Acceleration = Force / Mass)
* # Calcualate Change in Velocity
* tf * a = dv (Time per Frame * Acceleration = Change in Velocity)
* # Calculate Change in Position
* tf * v = dP (Time per Frame * Velocity = Change in Position)
* # Calculate New Position
*/
int main() {
}
<commit_msg>Created nsl function. /proto/01.<commit_after>#include <iostream>
#include <cmath>
/*
* # Calculate Force
* F = (GmM)/d^2 ((Gravitational Constant * Mass-1 * Mass-2) / Distance^2)
* # Resolve Vectors
* Fx = FcosA
* Fy = FsinA
* # Calcualate Acceleration
* a = F/m (Acceleration = Force / Mass)
* # Calcualate Change in Velocity
* tf * a = dv (Time per Frame * Acceleration = Change in Velocity)
* # Calculate Change in Position
* tf * v = dP (Time per Frame * Velocity = Change in Position)
* # Calculate New Position
*/
// Prototypes
// Resolve Vectors
double resolveX(double force, double angle);
double resolveY(double force, double angle);
// Newtons Second Law (Flexible Function)
double nsl(double force = NULL; double mass = NULL, double accel = NULL);
// Functions
int main() {
}
double nsl(double force = NULL; double mass = NULL, double accel = NULL) {
double result = 0;
// Check for NULL parameter
if(force == NULL & mass != NULL & accel != NULL)
result = mass * accel;
if(force != NULL & mass == NULL & accel != NULL)
result = force / accel;
if(force != NULL & mass != NULL & accel == NULL)
result = force / mass;
// If more than one parameter is NULL 0 is returned.
return result;
}
<|endoftext|> |
<commit_before>#include "strutil.h" // TODO This header is from the offical protobuf source, but it is not normally installed
#include <map>
#include <string>
#include <algorithm>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/compiler/plugin.h>
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
using namespace google::protobuf;
using namespace google::protobuf::compiler;
class PHPCodeGenerator : public CodeGenerator {
private:
void PrintMessage (io::Printer &printer, const Descriptor & message) const;
void PrintMessages (io::Printer &printer, const FileDescriptor & file) const;
void PrintEnum (io::Printer &printer, const EnumDescriptor & e) const;
void PrintEnums (io::Printer &printer, const FileDescriptor & file) const;
void PrintService (io::Printer &printer, const ServiceDescriptor & service) const;
void PrintServices (io::Printer &printer, const FileDescriptor & file) const;
string DefaultValueAsString(const FieldDescriptor & field, bool quote_string_type) const;
string ClassName(const string & full_name) const;
public:
PHPCodeGenerator();
~PHPCodeGenerator();
bool Generate(const FileDescriptor* file, const string& parameter, OutputDirectory* output_directory, string* error) const;
};
PHPCodeGenerator::PHPCodeGenerator() {}
PHPCodeGenerator::~PHPCodeGenerator() {}
string UnderscoresToCamelCaseImpl(const string& input, bool cap_next_letter) {
string result;
// Note: I distrust ctype.h due to locales.
for (int i = 0; i < input.size(); i++) {
if ('a' <= input[i] && input[i] <= 'z') {
if (cap_next_letter) {
result += input[i] + ('A' - 'a');
} else {
result += input[i];
}
cap_next_letter = false;
} else if ('A' <= input[i] && input[i] <= 'Z') {
if (i == 0 && !cap_next_letter) {
// Force first letter to lower-case unless explicitly told to
// capitalize it.
result += input[i] + ('a' - 'A');
} else {
// Capital letters after the first are left as-is.
result += input[i];
}
cap_next_letter = false;
} else if ('0' <= input[i] && input[i] <= '9') {
result += input[i];
cap_next_letter = true;
} else {
cap_next_letter = true;
}
}
return result;
}
const string& FieldName(const FieldDescriptor & field) {
// Groups are hacky: The name of the field is just the lower-cased name
// of the group type. In Java, though, we would like to retain the original
// capitalization of the type name.
if (field.type() == FieldDescriptor::TYPE_GROUP) {
return field.message_type()->name();
} else {
return field.name();
}
}
string UnderscoresToCamelCase(const FieldDescriptor & field) {
return UnderscoresToCamelCaseImpl(FieldName(field), false);
}
string UnderscoresToCapitalizedCamelCase(const FieldDescriptor & field) {
return UnderscoresToCamelCaseImpl(FieldName(field), true);
}
string StripProto(const string& filename) {
if (HasSuffixString(filename, ".protodevel")) {
return StripSuffixString(filename, ".protodevel");
} else {
return StripSuffixString(filename, ".proto");
}
}
string LowerString(const string & s) {
string newS (s);
LowerString(&newS);
return newS;
}
string UpperString(const string & s) {
string newS (s);
UpperString(&newS);
return newS;
}
// Maps a Message full_name into a PHP name
string PHPCodeGenerator::ClassName(const string & full_name) const {
string name (full_name);
replace(name.begin(), name.end(), '.', '_');
return name;
}
string PHPCodeGenerator::DefaultValueAsString(const FieldDescriptor & field, bool quote_string_type) const {
switch (field.cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32:
return SimpleItoa(field.default_value_int32());
case FieldDescriptor::CPPTYPE_INT64:
return SimpleItoa(field.default_value_int64());
case FieldDescriptor::CPPTYPE_UINT32:
return SimpleItoa(field.default_value_uint32());
case FieldDescriptor::CPPTYPE_UINT64:
return SimpleItoa(field.default_value_uint64());
case FieldDescriptor::CPPTYPE_FLOAT:
return SimpleFtoa(field.default_value_float());
case FieldDescriptor::CPPTYPE_DOUBLE:
return SimpleDtoa(field.default_value_double());
case FieldDescriptor::CPPTYPE_BOOL:
return field.default_value_bool() ? "true" : "false";
case FieldDescriptor::CPPTYPE_STRING:
if (quote_string_type)
return "\"" + CEscape(field.default_value_string()) + "\"";
if (field.type() == FieldDescriptor::TYPE_BYTES)
return CEscape(field.default_value_string());
return field.default_value_string();
case FieldDescriptor::CPPTYPE_ENUM:
return ClassName(field.enum_type()->name()) + "::" + field.default_value_enum()->name();
case FieldDescriptor::CPPTYPE_MESSAGE:
return "null";
}
return "";
}
void PHPCodeGenerator::PrintMessage(io::Printer &printer, const Descriptor & message) const {
// Print nested messages
for (int i = 0; i < message.nested_type_count(); ++i) {
printer.Print("\n");
PrintMessage(printer, *message.nested_type(i));
}
// Print nested enum
for (int i = 0; i < message.enum_type_count(); ++i) {
PrintEnum(printer, *message.enum_type(i) );
}
printer.Print("// message `name`\n",
"name", message.full_name());
printer.Print("class `name` {\n",
"name", ClassName(message.full_name()));
printer.Indent();
// Print fields
for (int i = 0; i < message.field_count(); ++i) {
printer.Print("\n");
const FieldDescriptor &field ( *message.field(i) );
map<string, string> variables;
variables["name"] = UnderscoresToCamelCase(field) + "_"; // Variable name
variables["capitalized_name"] = UnderscoresToCapitalizedCamelCase(field);
variables["number"] = SimpleItoa(field.number());
variables["comment"] = field.DebugString();
variables["default"] = DefaultValueAsString(field, true);
switch (field.type()) {
// If its a enum we should store it as a int
// case FieldDescriptor::TYPE_ENUM:
// variables["type"] = field.enum_type()->name() + " ";
// break;
case FieldDescriptor::TYPE_MESSAGE:
case FieldDescriptor::TYPE_GROUP:
variables["type"] = ClassName(field.message_type()->full_name()) + " ";
break;
default:
variables["type"] = "";
}
printer.Print(variables,
"// `comment`\n"
"private $`name` = null;\n"
"public function has`capitalized_name`() { return !is_null($this->`name`); }\n"
"public function clear`capitalized_name`() { $this->`name` = null; }\n"
"public function get`capitalized_name`() { if(is_null($this->`name`)) return `default`; else return $this->`name`; }\n"
);
// TODO Change the set code to validate input depending on the variable type
printer.Print(variables,
"public function set`capitalized_name`(`type`$value) { $this->`name` = $value; }\n"
);
}
// map<string, string> m;
// m["descriptor_key"] = kDescriptorKey;
// m["descriptor_name"] = ModuleLevelDescriptorName(message);
// printer.Print(m, "$descriptor_key$ = $descriptor_name$\n");
// Class Insertion Point
printer.Print(
"\n"
"// @@protoc_insertion_point(class_scope:`full_name`)\n",
"full_name", message.full_name());
printer.Outdent();
printer.Print("}\n\n");
}
void PHPCodeGenerator::PrintEnum(io::Printer &printer, const EnumDescriptor & e) const {
printer.Print("// enum `name`\n",
"name", e.full_name() );
printer.Print("class `name` {\n",
"name", ClassName(e.full_name()) );
printer.Indent();
// Print fields
for (int j = 0; j < e.value_count(); ++j) {
const EnumValueDescriptor &value ( *e.value(j) );
map<string, string> variables;
variables["name"] = UpperString(value.name());
variables["number"] = SimpleItoa(value.number());
printer.Print(variables,
"const `name` = `number`;\n");
}
printer.Outdent();
printer.Print("}\n\n");
}
void PHPCodeGenerator::PrintMessages(io::Printer &printer, const FileDescriptor & file) const {
for (int i = 0; i < file.message_type_count(); ++i) {
PrintMessage(printer, *file.message_type(i));
}
}
void PHPCodeGenerator::PrintEnums(io::Printer &printer, const FileDescriptor & file) const {
for (int i = 0; i < file.enum_type_count(); ++i) {
PrintEnum(printer, *file.enum_type(i) );
}
}
void PHPCodeGenerator::PrintServices(io::Printer &printer, const FileDescriptor & file) const {
for (int i = 0; i < file.service_count(); ++i) {
printer.Print("////\n//TODO Service\n////\n");
}
}
bool PHPCodeGenerator::Generate(const FileDescriptor* file,
const string& parameter,
OutputDirectory* output_directory,
string* error) const {
string php_filename;
// php_filename += file_generator.filename();
php_filename += "test";
php_filename += ".php";
// Generate main file.
scoped_ptr<io::ZeroCopyOutputStream> output(
output_directory->Open(php_filename)
);
io::Printer printer(output.get(), '`');
printer.Print("<?php\n");
PrintMessages (printer, *file);
PrintEnums (printer, *file);
PrintServices (printer, *file);
printer.Print("?>");
return true;
}
int main(int argc, char* argv[]) {
PHPCodeGenerator generator;
return PluginMain(argc, argv, &generator);
}
<commit_msg>Even more!<commit_after>#include "strutil.h" // TODO This header is from the offical protobuf source, but it is not normally installed
#include <map>
#include <string>
#include <algorithm>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/compiler/plugin.h>
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
using namespace google::protobuf;
using namespace google::protobuf::compiler;
class PHPCodeGenerator : public CodeGenerator {
private:
void PrintMessage (io::Printer &printer, const Descriptor & message) const;
void PrintMessages (io::Printer &printer, const FileDescriptor & file) const;
void PrintEnum (io::Printer &printer, const EnumDescriptor & e) const;
void PrintEnums (io::Printer &printer, const FileDescriptor & file) const;
void PrintService (io::Printer &printer, const ServiceDescriptor & service) const;
void PrintServices (io::Printer &printer, const FileDescriptor & file) const;
string DefaultValueAsString(const FieldDescriptor & field, bool quote_string_type) const;
// Maps names into PHP names
template <class DescriptorType>
string ClassName(const DescriptorType & descriptor) const;
string VariableName(const FieldDescriptor & field) const;
public:
PHPCodeGenerator();
~PHPCodeGenerator();
bool Generate(const FileDescriptor* file, const string& parameter, OutputDirectory* output_directory, string* error) const;
};
PHPCodeGenerator::PHPCodeGenerator() {}
PHPCodeGenerator::~PHPCodeGenerator() {}
string UnderscoresToCamelCaseImpl(const string& input, bool cap_next_letter) {
string result;
// Note: I distrust ctype.h due to locales.
for (int i = 0; i < input.size(); i++) {
if ('a' <= input[i] && input[i] <= 'z') {
if (cap_next_letter) {
result += input[i] + ('A' - 'a');
} else {
result += input[i];
}
cap_next_letter = false;
} else if ('A' <= input[i] && input[i] <= 'Z') {
if (i == 0 && !cap_next_letter) {
// Force first letter to lower-case unless explicitly told to
// capitalize it.
result += input[i] + ('a' - 'A');
} else {
// Capital letters after the first are left as-is.
result += input[i];
}
cap_next_letter = false;
} else if ('0' <= input[i] && input[i] <= '9') {
result += input[i];
cap_next_letter = true;
} else {
cap_next_letter = true;
}
}
return result;
}
string UnderscoresToCamelCase(const FieldDescriptor & field) {
return UnderscoresToCamelCaseImpl(field.name(), false);
}
string UnderscoresToCapitalizedCamelCase(const FieldDescriptor & field) {
return UnderscoresToCamelCaseImpl(field.name(), true);
}
string StripProto(const string& filename) {
if (HasSuffixString(filename, ".protodevel")) {
return StripSuffixString(filename, ".protodevel");
} else {
return StripSuffixString(filename, ".proto");
}
}
string LowerString(const string & s) {
string newS (s);
LowerString(&newS);
return newS;
}
string UpperString(const string & s) {
string newS (s);
UpperString(&newS);
return newS;
}
// Maps a Message full_name into a PHP name
template <class DescriptorType>
string PHPCodeGenerator::ClassName(const DescriptorType & descriptor) const {
string name (descriptor.full_name());
replace(name.begin(), name.end(), '.', '_');
return name;
}
string PHPCodeGenerator::VariableName(const FieldDescriptor & field) const {
return UnderscoresToCamelCase(field) + '_';
}
string PHPCodeGenerator::DefaultValueAsString(const FieldDescriptor & field, bool quote_string_type) const {
switch (field.cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32:
return SimpleItoa(field.default_value_int32());
case FieldDescriptor::CPPTYPE_INT64:
return SimpleItoa(field.default_value_int64());
case FieldDescriptor::CPPTYPE_UINT32:
return SimpleItoa(field.default_value_uint32());
case FieldDescriptor::CPPTYPE_UINT64:
return SimpleItoa(field.default_value_uint64());
case FieldDescriptor::CPPTYPE_FLOAT:
return SimpleFtoa(field.default_value_float());
case FieldDescriptor::CPPTYPE_DOUBLE:
return SimpleDtoa(field.default_value_double());
case FieldDescriptor::CPPTYPE_BOOL:
return field.default_value_bool() ? "true" : "false";
case FieldDescriptor::CPPTYPE_STRING:
if (quote_string_type)
return "\"" + CEscape(field.default_value_string()) + "\"";
if (field.type() == FieldDescriptor::TYPE_BYTES)
return CEscape(field.default_value_string());
return field.default_value_string();
case FieldDescriptor::CPPTYPE_ENUM:
return ClassName(*field.enum_type()) + "::" + field.default_value_enum()->name();
case FieldDescriptor::CPPTYPE_MESSAGE:
return "null";
}
return "";
}
void PHPCodeGenerator::PrintMessage(io::Printer &printer, const Descriptor & message) const {
// Print nested messages
for (int i = 0; i < message.nested_type_count(); ++i) {
printer.Print("\n");
PrintMessage(printer, *message.nested_type(i));
}
// Print nested enum
for (int i = 0; i < message.enum_type_count(); ++i) {
PrintEnum(printer, *message.enum_type(i) );
}
printer.Print("// message `full_name`\n"
"class `name` {\n",
"full_name", message.full_name(),
"name", ClassName(message)
);
printer.Indent();
// Print fields map
printer.Print(
"// Arrays mapps field indexes to members\n"
"private $_map = array (\n"
);
printer.Indent();
for (int i = 0; i < message.field_count(); ++i) {
const FieldDescriptor &field ( *message.field(i) );
printer.Print("`index` => `value`,\n",
"index", SimpleItoa(field.number()),
"value", VariableName(field)
);
}
printer.Outdent();
printer.Print(");\n\n");
vector<const FieldDescriptor *> required_fields;
// Print fields variables and methods
for (int i = 0; i < message.field_count(); ++i) {
printer.Print("\n");
const FieldDescriptor &field ( *message.field(i) );
if (field.is_required())
required_fields.push_back( &field );
map<string, string> variables;
variables["name"] = VariableName(field);
variables["capitalized_name"] = UnderscoresToCapitalizedCamelCase(field);
variables["comment"] = field.DebugString();
variables["default"] = DefaultValueAsString(field, true);
switch (field.type()) {
// If its a enum we should store it as a int
// case FieldDescriptor::TYPE_ENUM:
// variables["type"] = field.enum_type()->name() + " ";
// break;
case FieldDescriptor::TYPE_MESSAGE:
case FieldDescriptor::TYPE_GROUP:
variables["type"] = ClassName(*field.message_type()) + " ";
break;
default:
variables["type"] = "";
}
if (field.is_repeated()) {
// Repeated field
printer.Print(variables,
"// `comment`\n"
"private $`name` = null;\n"
"public function clear`capitalized_name`() { $this->`name` = null; }\n"
"public function get`capitalized_name`Count() { if ($this->`name` === null ) return 0; else return count($this->`name`); }\n"
"public function get`capitalized_name`($index) { return $this->`name`[$index]; }\n"
"public function get`capitalized_name`Array() { if ($this->`name` === null ) return array(); else return $this->`name`; }\n"
"public function set`capitalized_name`($index, $value) {$this->`name`[$index] = $value; }\n"
"public function add`capitalized_name`($value) { $this->`name`[] = $value; }\n"
"public function addAll`capitalized_name`($values) { foreach($values as $value) {$this->`name`[] = $value;} }\n"
);
} else {
// Non repeated field
printer.Print(variables,
"// `comment`\n"
"private $`name` = null;\n"
"public function clear`capitalized_name`() { $this->`name` = null; }\n"
"public function has`capitalized_name`() { return $this->`name` !== null; }\n"
"public function get`capitalized_name`() { if($this->`name` === null) return `default`; else return $this->`name`; }\n"
);
// TODO Change the set code to validate input depending on the variable type
printer.Print(variables,
"public function set`capitalized_name`(`type`$value) { $this->`name` = $value; }\n"
);
}
}
// Validate required fields are included
printer.Print(
"\n"
"public function validateRequired() {\n"
);
printer.Indent();
for (int i = 0; i < required_fields.size(); ++i) {
printer.Print("if ($this->`name` === null) return false;\n",
"name", VariableName(*required_fields[i])
);
}
printer.Print("return true;\n");
printer.Outdent();
printer.Print("}\n");
// Class Insertion Point
printer.Print(
"\n"
"// @@protoc_insertion_point(class_scope:`full_name`)\n",
"full_name", message.full_name()
);
printer.Outdent();
printer.Print("}\n\n");
}
void PHPCodeGenerator::PrintEnum(io::Printer &printer, const EnumDescriptor & e) const {
printer.Print("// enum `full_name`\n"
"class `name` {\n",
"full_name", e.full_name(),
"name", ClassName(e)
);
printer.Indent();
// Print fields
for (int j = 0; j < e.value_count(); ++j) {
const EnumValueDescriptor &value ( *e.value(j) );
map<string, string> variables;
variables["name"] = UpperString(value.name());
variables["number"] = SimpleItoa(value.number());
printer.Print(variables,
"const `name` = `number`;\n");
}
printer.Outdent();
printer.Print("}\n\n");
}
void PHPCodeGenerator::PrintMessages(io::Printer &printer, const FileDescriptor & file) const {
for (int i = 0; i < file.message_type_count(); ++i) {
PrintMessage(printer, *file.message_type(i));
}
}
void PHPCodeGenerator::PrintEnums(io::Printer &printer, const FileDescriptor & file) const {
for (int i = 0; i < file.enum_type_count(); ++i) {
PrintEnum(printer, *file.enum_type(i) );
}
}
void PHPCodeGenerator::PrintServices(io::Printer &printer, const FileDescriptor & file) const {
for (int i = 0; i < file.service_count(); ++i) {
printer.Print("////\n//TODO Service\n////\n");
}
}
bool PHPCodeGenerator::Generate(const FileDescriptor* file,
const string& parameter,
OutputDirectory* output_directory,
string* error) const {
string php_filename;
// php_filename += file_generator.filename();
php_filename += "test";
php_filename += ".php";
// Generate main file.
scoped_ptr<io::ZeroCopyOutputStream> output(
output_directory->Open(php_filename)
);
io::Printer printer(output.get(), '`');
printer.Print("<?php\n");
PrintMessages (printer, *file);
PrintEnums (printer, *file);
PrintServices (printer, *file);
printer.Print("?>");
return true;
}
int main(int argc, char* argv[]) {
PHPCodeGenerator generator;
return PluginMain(argc, argv, &generator);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2016-2017 gtalent2@gmail.com
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <ox/std/types.hpp>
#include "json_err.hpp"
namespace nostalgia {
namespace studio {
class JsonReader {
private:
QJsonObject &m_src;
public:
JsonReader(QJsonObject &obj);
void setFields(int) {};
ox::Error op(QString fieldName, int *dest);
ox::Error op(QString fieldName, bool *dest);
ox::Error op(QString fieldName, double *dest);
ox::Error op(QString fieldName, QString *dest);
template<typename T>
ox::Error op(QString fieldName, T *dest);
template<typename T>
ox::Error op(QString fieldName, QVector<T> *dest);
private:
ox::Error op(QJsonValueRef src, int *dest);
ox::Error op(QJsonValueRef src, bool *dest);
ox::Error op(QJsonValueRef src, double *dest);
ox::Error op(QJsonValueRef src, QString *dest);
template<typename T>
ox::Error op(QJsonValueRef src, T *dest);
};
template<typename T>
ox::Error JsonReader::op(QString fieldName, T *dest) {
auto obj = m_src[fieldName].toObject();
auto reader = JsonReader(obj);
return ioOp(&reader, dest);
};
template<typename T>
ox::Error JsonReader::op(QString fieldName, QVector<T> *dest) {
ox::Error err = 0;
auto a = m_src[fieldName].toArray();
dest->resize(a.size());
for (int i = 0; i < dest->size(); i++) {
err |= op(a[i], &(*dest)[i]);
}
return err;
};
template<typename T>
ox::Error JsonReader::op(QJsonValueRef src, T *dest) {
auto obj = src.toObject();
auto reader = JsonReader(obj);
return ioOp(&reader, dest);
}
template<typename T>
int readJson(QString json, T *dest) {
auto obj = QJsonDocument::fromJson(json.toUtf8()).object();
JsonReader rdr(obj);
return ioOp(&rdr, dest);
}
}
}
<commit_msg>Add some missing field checks to JSON reader<commit_after>/*
* Copyright 2016-2017 gtalent2@gmail.com
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <ox/std/types.hpp>
#include "json_err.hpp"
namespace nostalgia {
namespace studio {
class JsonReader {
private:
QJsonObject &m_src;
public:
JsonReader(QJsonObject &obj);
void setFields(int) {};
ox::Error op(QString fieldName, int *dest);
ox::Error op(QString fieldName, bool *dest);
ox::Error op(QString fieldName, double *dest);
ox::Error op(QString fieldName, QString *dest);
template<typename T>
ox::Error op(QString fieldName, T *dest);
template<typename T>
ox::Error op(QString fieldName, QVector<T> *dest);
private:
ox::Error op(QJsonValueRef src, int *dest);
ox::Error op(QJsonValueRef src, bool *dest);
ox::Error op(QJsonValueRef src, double *dest);
ox::Error op(QJsonValueRef src, QString *dest);
template<typename T>
ox::Error op(QJsonValueRef src, T *dest);
};
template<typename T>
ox::Error JsonReader::op(QString fieldName, T *dest) {
if (m_src.contains(fieldName)) {
auto obj = m_src[fieldName].toObject();
auto reader = JsonReader(obj);
return ioOp(&reader, dest);
} else {
return JSON_ERR_FIELD_MISSING;
}
};
template<typename T>
ox::Error JsonReader::op(QString fieldName, QVector<T> *dest) {
ox::Error err = 0;
if (m_src.contains(fieldName)) {
auto a = m_src[fieldName].toArray();
dest->resize(a.size());
for (int i = 0; i < dest->size(); i++) {
err |= op(a[i], &(*dest)[i]);
}
} else {
err |= JSON_ERR_FIELD_MISSING;
}
return err;
};
template<typename T>
ox::Error JsonReader::op(QJsonValueRef src, T *dest) {
auto obj = src.toObject();
auto reader = JsonReader(obj);
return ioOp(&reader, dest);
}
template<typename T>
int readJson(QString json, T *dest) {
auto obj = QJsonDocument::fromJson(json.toUtf8()).object();
JsonReader rdr(obj);
return ioOp(&rdr, dest);
}
}
}
<|endoftext|> |
<commit_before>#include "QQuickLightOutputPreview.h"
#include <QOpenGLFramebufferObject>
#include <QOpenGLContext>
#include <QOpenGLFunctions>
#include <QOpenGLShaderProgram>
#include <QtDebug>
#include <QQuickWindow>
#include "LightOutputNode.h"
// Renderer
class QQuickLightOutputPreview;
class LightOutputRenderer
: public QQuickFramebufferObject::Renderer
, protected QOpenGLFunctions {
public:
void synchronize(QQuickFramebufferObject *item) override {
auto p = static_cast<QQuickLightOutputPreview *>(item);
m_videoNode = p->videoNodeForRendering();
m_devicePixelRatio = p->window()->devicePixelRatio();
}
void render() override {
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
//glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendEquationSeparate(GL_MAX, GL_MAX);
glEnable(GL_PROGRAM_POINT_SIZE);
if (!m_videoNode.isNull()) {
m_vao.bind();
auto outputSize = m_videoNode->chain()->size();
auto factorFitX = (float)outputSize.height() * m_viewportSize.width() / outputSize.width() / m_viewportSize.height();
auto factorFitY = (float)outputSize.width() * m_viewportSize.height() / outputSize.height() / m_viewportSize.width();
factorFitX = qMax(factorFitX, 1.f);
factorFitY = qMax(factorFitY, 1.f);
auto centerX = 0.5 * (1. - factorFitX);
auto centerY = 0.5 * (1. - factorFitY);
auto marginX = (5 * m_devicePixelRatio) / m_viewportSize.width();
auto marginY = (5 * m_devicePixelRatio) / m_viewportSize.height();
QMatrix4x4 projection;
projection.ortho(centerX - marginX, centerX + factorFitX + marginX, centerY + factorFitY + marginY, centerY - marginY, -1., 1.);
auto posAttr = m_lightShader->attributeLocation("posAttr");
auto colAttr = m_lightShader->attributeLocation("colAttr");
{
QMutexLocker locker(m_videoNode->bufferLock());
auto background = m_videoNode->geometry2DTexture();
auto pixelCount = m_videoNode->pixelCount();
auto colors = m_videoNode->colorsBuffer();
auto displayMode = m_videoNode->displayMode();
auto lookupCoordinates = m_videoNode->lookupCoordinatesBuffer();
auto physicalCoordinates = m_videoNode->physicalCoordinatesBuffer();
// Draw background
m_backgroundShader->bind();
glActiveTexture(GL_TEXTURE0);
background->bind();
m_backgroundShader->setUniformValue("mvp", projection);
m_backgroundShader->setUniformValue("background", 0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
// Draw lights
m_lightShader->bind();
glEnableVertexAttribArray(posAttr);
glEnableVertexAttribArray(colAttr);
m_lightShader->setUniformValue("mvp", projection);
m_lightShader->setUniformValue("dpr", (GLfloat)m_devicePixelRatio);
if (displayMode == LightOutputNode::DisplayPhysical2D) {
physicalCoordinates.bind();
} else {
lookupCoordinates.bind();
}
glVertexAttribPointer(posAttr, 2, GL_FLOAT, GL_FALSE, 0, 0);
colors.bind();
glVertexAttribPointer(colAttr, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0);
colors.release();
glDrawArrays(GL_POINTS, 0, pixelCount);
glDisableVertexAttribArray(posAttr);
glDisableVertexAttribArray(colAttr);
}
m_vao.release();
m_lightShader->release();
}
glDisable(GL_PROGRAM_POINT_SIZE);
glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);
glDisable(GL_BLEND);
update();
}
QOpenGLFramebufferObject *createFramebufferObject(const QSize &size) override {
if (!m_initialized) {
initializeOpenGLFunctions();
initialize();
m_initialized = true;
}
QOpenGLFramebufferObjectFormat format;
format.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
m_viewportSize = size;
return new QOpenGLFramebufferObject(size, format);
}
private:
QSharedPointer<QOpenGLShaderProgram> loadLightShader() {
auto vertexString = QString{
"#version 150\n"
"attribute vec2 posAttr;\n"
"attribute vec4 colAttr;\n"
"out vec4 col;\n"
"uniform mat4 mvp;\n"
"uniform float dpr;\n"
"void main() {\n"
" col = colAttr;\n"
" gl_Position = mvp * vec4(posAttr, 0., 1.);\n"
" gl_PointSize = 10 * dpr;\n"
"}\n"};
auto fragmentString = QString{
"#version 150\n"
"in vec4 col;\n"
"out vec4 fragColor;\n"
"void main() {\n"
" float fadeOut = max(1. - length(2. * gl_PointCoord - 1.), 0.);\n"
" fragColor = col * fadeOut * fadeOut;\n"
"}\n"};
auto shader = QSharedPointer<QOpenGLShaderProgram>(new QOpenGLShaderProgram());
if (!shader->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexString)) {
qWarning() << "Could not compile vertex shader";
return nullptr;
}
if (!shader->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentString)) {
qWarning() << "Could not compile fragment shader";
return nullptr;
}
if (!shader->link()) {
qWarning() << "Could not link shader program";
return nullptr;
}
return shader;
}
QSharedPointer<QOpenGLShaderProgram> loadBackgroundShader() {
auto vertexString = QString{
"#version 150\n"
"out vec2 uv;\n"
"const vec2 varray[4] = vec2[](vec2(1., 1.),vec2(1., 0.),vec2(0., 1.),vec2(0., 0.));\n"
"uniform mat4 mvp;\n"
"void main() {\n"
" vec2 vertex = varray[gl_VertexID];\n"
" gl_Position = mvp * vec4(vertex, 0., 1.);\n"
" uv = vertex;\n"
"}\n"};
auto fragmentString = QString{
"#version 150\n"
"uniform sampler2D background;\n"
"in vec2 uv;\n"
"out vec4 fragColor;\n"
"void main() {\n"
" fragColor = texture(background, uv);\n"
"}\n"};
auto shader = QSharedPointer<QOpenGLShaderProgram>(new QOpenGLShaderProgram());
if (!shader->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexString)) {
qWarning() << "Could not compile vertex shader";
return nullptr;
}
if (!shader->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentString)) {
qWarning() << "Could not compile fragment shader";
return nullptr;
}
if (!shader->link()) {
qWarning() << "Could not link shader program";
return nullptr;
}
return shader;
}
void initialize() {
m_lightShader = loadLightShader();
m_backgroundShader = loadBackgroundShader();
m_vao.create();
}
QSharedPointer<QOpenGLShaderProgram> m_lightShader;
QSharedPointer<QOpenGLShaderProgram> m_backgroundShader;
bool m_initialized{};
QOpenGLVertexArrayObject m_vao;
QSize m_viewportSize;
qreal m_devicePixelRatio;
QSharedPointer<LightOutputNode> m_videoNode;
};
// QQuickItem
QQuickLightOutputPreview::QQuickLightOutputPreview() {
m_renderer = new LightOutputRenderer();
}
QQuickFramebufferObject::Renderer *QQuickLightOutputPreview::createRenderer() const {
return m_renderer;
}
LightOutputNodeSP *QQuickLightOutputPreview::videoNode() {
return m_videoNode;
}
QSharedPointer<LightOutputNode> QQuickLightOutputPreview::videoNodeForRendering() {
if (m_videoNode == nullptr) return nullptr;
return qSharedPointerCast<LightOutputNode>(*m_videoNode);
}
void QQuickLightOutputPreview::setVideoNode(LightOutputNodeSP *videoNode) {
delete m_videoNode;
if (videoNode != nullptr) {
m_videoNode = videoNode->clone();
m_videoNode->setParent(this); // Ensure C++ ownership and proper deletion
} else {
m_videoNode = nullptr;
}
emit videoNodeChanged(m_videoNode);
}
<commit_msg>Fix LightOutputNode crash<commit_after>#include "QQuickLightOutputPreview.h"
#include <QOpenGLFramebufferObject>
#include <QOpenGLContext>
#include <QOpenGLFunctions>
#include <QOpenGLShaderProgram>
#include <QtDebug>
#include <QQuickWindow>
#include "LightOutputNode.h"
// Renderer
class QQuickLightOutputPreview;
class LightOutputRenderer
: public QQuickFramebufferObject::Renderer
, protected QOpenGLFunctions {
public:
void synchronize(QQuickFramebufferObject *item) override {
auto p = static_cast<QQuickLightOutputPreview *>(item);
m_videoNode = p->videoNodeForRendering();
m_devicePixelRatio = p->window()->devicePixelRatio();
}
void render() override {
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
//glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendEquationSeparate(GL_MAX, GL_MAX);
glEnable(GL_PROGRAM_POINT_SIZE);
if (!m_videoNode.isNull()) {
m_vao.bind();
auto outputSize = m_videoNode->chain()->size();
auto factorFitX = (float)outputSize.height() * m_viewportSize.width() / outputSize.width() / m_viewportSize.height();
auto factorFitY = (float)outputSize.width() * m_viewportSize.height() / outputSize.height() / m_viewportSize.width();
factorFitX = qMax(factorFitX, 1.f);
factorFitY = qMax(factorFitY, 1.f);
auto centerX = 0.5 * (1. - factorFitX);
auto centerY = 0.5 * (1. - factorFitY);
auto marginX = (5 * m_devicePixelRatio) / m_viewportSize.width();
auto marginY = (5 * m_devicePixelRatio) / m_viewportSize.height();
QMatrix4x4 projection;
projection.ortho(centerX - marginX, centerX + factorFitX + marginX, centerY + factorFitY + marginY, centerY - marginY, -1., 1.);
auto posAttr = m_lightShader->attributeLocation("posAttr");
auto colAttr = m_lightShader->attributeLocation("colAttr");
{
QMutexLocker locker(m_videoNode->bufferLock());
auto background = m_videoNode->geometry2DTexture();
auto pixelCount = m_videoNode->pixelCount();
auto colors = m_videoNode->colorsBuffer();
auto displayMode = m_videoNode->displayMode();
auto lookupCoordinates = m_videoNode->lookupCoordinatesBuffer();
auto physicalCoordinates = m_videoNode->physicalCoordinatesBuffer();
// Draw background
m_backgroundShader->bind();
glActiveTexture(GL_TEXTURE0);
background->bind();
m_backgroundShader->setUniformValue("mvp", projection);
m_backgroundShader->setUniformValue("background", 0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
// Draw lights
m_lightShader->bind();
glEnableVertexAttribArray(posAttr);
glEnableVertexAttribArray(colAttr);
m_lightShader->setUniformValue("mvp", projection);
m_lightShader->setUniformValue("dpr", (GLfloat)m_devicePixelRatio);
if (displayMode == LightOutputNode::DisplayPhysical2D) {
physicalCoordinates.bind();
} else {
lookupCoordinates.bind();
}
glVertexAttribPointer(posAttr, 2, GL_FLOAT, GL_FALSE, 0, 0);
colors.bind();
glVertexAttribPointer(colAttr, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0);
colors.release();
glDrawArrays(GL_POINTS, 0, pixelCount);
glDisableVertexAttribArray(posAttr);
glDisableVertexAttribArray(colAttr);
}
m_vao.release();
m_lightShader->release();
}
glDisable(GL_PROGRAM_POINT_SIZE);
glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);
glDisable(GL_BLEND);
update();
}
QOpenGLFramebufferObject *createFramebufferObject(const QSize &size) override {
if (!m_initialized) {
initializeOpenGLFunctions();
initialize();
m_initialized = true;
}
QOpenGLFramebufferObjectFormat format;
format.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
m_viewportSize = size;
return new QOpenGLFramebufferObject(size, format);
}
private:
QSharedPointer<QOpenGLShaderProgram> loadLightShader() {
auto vertexString = QString{
"#version 150\n"
"in vec2 posAttr;\n"
"in vec4 colAttr;\n"
"out vec4 col;\n"
"uniform mat4 mvp;\n"
"uniform float dpr;\n"
"void main() {\n"
" col = colAttr;\n"
" gl_Position = mvp * vec4(posAttr, 0., 1.);\n"
" gl_PointSize = 10 * dpr;\n"
"}\n"};
auto fragmentString = QString{
"#version 150\n"
"in vec4 col;\n"
"out vec4 fragColor;\n"
"void main() {\n"
" float fadeOut = max(1. - length(2. * gl_PointCoord - 1.), 0.);\n"
" fragColor = col * fadeOut * fadeOut;\n"
"}\n"};
auto shader = QSharedPointer<QOpenGLShaderProgram>(new QOpenGLShaderProgram());
if (!shader->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexString)) {
qWarning() << "Could not compile vertex shader";
return nullptr;
}
if (!shader->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentString)) {
qWarning() << "Could not compile fragment shader";
return nullptr;
}
if (!shader->link()) {
qWarning() << "Could not link shader program";
return nullptr;
}
return shader;
}
QSharedPointer<QOpenGLShaderProgram> loadBackgroundShader() {
auto vertexString = QString{
"#version 150\n"
"out vec2 uv;\n"
"const vec2 varray[4] = vec2[](vec2(1., 1.),vec2(1., 0.),vec2(0., 1.),vec2(0., 0.));\n"
"uniform mat4 mvp;\n"
"void main() {\n"
" vec2 vertex = varray[gl_VertexID];\n"
" gl_Position = mvp * vec4(vertex, 0., 1.);\n"
" uv = vertex;\n"
"}\n"};
auto fragmentString = QString{
"#version 150\n"
"uniform sampler2D background;\n"
"in vec2 uv;\n"
"out vec4 fragColor;\n"
"void main() {\n"
" fragColor = texture(background, uv);\n"
"}\n"};
auto shader = QSharedPointer<QOpenGLShaderProgram>(new QOpenGLShaderProgram());
if (!shader->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexString)) {
qWarning() << "Could not compile vertex shader";
return nullptr;
}
if (!shader->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentString)) {
qWarning() << "Could not compile fragment shader";
return nullptr;
}
if (!shader->link()) {
qWarning() << "Could not link shader program";
return nullptr;
}
return shader;
}
void initialize() {
m_lightShader = loadLightShader();
m_backgroundShader = loadBackgroundShader();
m_vao.create();
}
QSharedPointer<QOpenGLShaderProgram> m_lightShader;
QSharedPointer<QOpenGLShaderProgram> m_backgroundShader;
bool m_initialized{};
QOpenGLVertexArrayObject m_vao;
QSize m_viewportSize;
qreal m_devicePixelRatio;
QSharedPointer<LightOutputNode> m_videoNode;
};
// QQuickItem
QQuickLightOutputPreview::QQuickLightOutputPreview() {
m_renderer = new LightOutputRenderer();
}
QQuickFramebufferObject::Renderer *QQuickLightOutputPreview::createRenderer() const {
return m_renderer;
}
LightOutputNodeSP *QQuickLightOutputPreview::videoNode() {
return m_videoNode;
}
QSharedPointer<LightOutputNode> QQuickLightOutputPreview::videoNodeForRendering() {
if (m_videoNode == nullptr) return nullptr;
return qSharedPointerCast<LightOutputNode>(*m_videoNode);
}
void QQuickLightOutputPreview::setVideoNode(LightOutputNodeSP *videoNode) {
delete m_videoNode;
if (videoNode != nullptr) {
m_videoNode = videoNode->clone();
m_videoNode->setParent(this); // Ensure C++ ownership and proper deletion
} else {
m_videoNode = nullptr;
}
emit videoNodeChanged(m_videoNode);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <boost/function.hpp>
#include <libport/assert.hh>
#include <libport/foreach.hh>
#include <libport/markup-ostream.hh>
namespace libport
{
class MarkupStreamBuffer: public libport::StreamBuffer
{
public:
MarkupStreamBuffer(std::ostream& output)
: output_(output)
, in_table_(false)
, table_()
{}
void col()
{
sync();
table_.back().push_back("");
}
static void box(std::ostream& tgt, const std::string& data, size_t size)
{
assert(data.size() < size);
tgt << data;
for (size_t i = data.size(); i < size; ++i)
tgt << ' ';
}
void etable()
{
sync();
passert(in_table_, "not in table mode");
typedef std::vector<size_t> widths_type;
widths_type widths;
foreach (const row_type& row, table_)
{
widths_type::iterator width = widths.begin();
foreach (const std::string& cell, row)
{
if (width == widths.end())
{
widths.push_back(0);
width = widths.end() - 1;
}
*width = std::max(*width, cell.size());
++width;
}
}
foreach (const row_type& row, table_)
{
row_type::const_iterator cell = row.begin();
foreach (size_t width, widths)
{
if (cell == row.end())
break;
if (cell != row.end() - 1)
{
box(output_, *cell, width);
output_ << ' ';
}
else
output_ << *cell;
++cell;
}
output_ << std::endl;
}
table_.clear();
in_table_ = false;
}
void row()
{
sync();
table_.push_back(row_type());
}
void table()
{
sync();
passert(!in_table_, "already in table mode");
in_table_ = true;
}
protected:
typedef std::vector<std::string> row_type;
typedef std::vector<row_type> table_type;
virtual size_t read(char*, size_t)
{
pabort("cannot read from MarkupOStream");
}
virtual void write(char* buffer, size_t size)
{
std::string data(buffer, size);
if (in_table_)
{
if (table_.empty())
table_.push_back(row_type());
if (table_.back().empty())
table_.back().push_back("");
table_.back().back() += data;
}
else
output_ << data;
}
private:
std::ostream& output_;
bool in_table_;
table_type table_;
};
MarkupOStream::MarkupOStream(std::ostream& output)
: libport::IOStream(buffer_ = new MarkupStreamBuffer(output))
{}
#define MOD(Name) \
std::ostream& Name(std::ostream& where) \
{ \
assert_exp(dynamic_cast<MarkupOStream*>(&where))->Name(); \
return where; \
} \
\
void MarkupOStream::Name() \
{ \
buffer_->Name(); \
} \
MOD(col);
MOD(etable);
MOD(row);
MOD(table);
#undef MOD
}
<commit_msg>Fix assertion.<commit_after>#include <iostream>
#include <vector>
#include <boost/function.hpp>
#include <libport/assert.hh>
#include <libport/foreach.hh>
#include <libport/markup-ostream.hh>
namespace libport
{
class MarkupStreamBuffer: public libport::StreamBuffer
{
public:
MarkupStreamBuffer(std::ostream& output)
: output_(output)
, in_table_(false)
, table_()
{}
void col()
{
sync();
table_.back().push_back("");
}
static void box(std::ostream& tgt, const std::string& data, size_t size)
{
assert(data.size() <= size);
tgt << data;
for (size_t i = data.size(); i < size; ++i)
tgt << ' ';
}
void etable()
{
sync();
passert(in_table_, "not in table mode");
typedef std::vector<size_t> widths_type;
widths_type widths;
foreach (const row_type& row, table_)
{
widths_type::iterator width = widths.begin();
foreach (const std::string& cell, row)
{
if (width == widths.end())
{
widths.push_back(0);
width = widths.end() - 1;
}
*width = std::max(*width, cell.size());
++width;
}
}
foreach (const row_type& row, table_)
{
row_type::const_iterator cell = row.begin();
foreach (size_t width, widths)
{
if (cell == row.end())
break;
if (cell != row.end() - 1)
{
box(output_, *cell, width);
output_ << ' ';
}
else
output_ << *cell;
++cell;
}
output_ << std::endl;
}
table_.clear();
in_table_ = false;
}
void row()
{
sync();
table_.push_back(row_type());
}
void table()
{
sync();
passert(!in_table_, "already in table mode");
in_table_ = true;
}
protected:
typedef std::vector<std::string> row_type;
typedef std::vector<row_type> table_type;
virtual size_t read(char*, size_t)
{
pabort("cannot read from MarkupOStream");
}
virtual void write(char* buffer, size_t size)
{
std::string data(buffer, size);
if (in_table_)
{
if (table_.empty())
table_.push_back(row_type());
if (table_.back().empty())
table_.back().push_back("");
table_.back().back() += data;
}
else
output_ << data;
}
private:
std::ostream& output_;
bool in_table_;
table_type table_;
};
MarkupOStream::MarkupOStream(std::ostream& output)
: libport::IOStream(buffer_ = new MarkupStreamBuffer(output))
{}
#define MOD(Name) \
std::ostream& Name(std::ostream& where) \
{ \
assert_exp(dynamic_cast<MarkupOStream*>(&where))->Name(); \
return where; \
} \
\
void MarkupOStream::Name() \
{ \
buffer_->Name(); \
} \
MOD(col);
MOD(etable);
MOD(row);
MOD(table);
#undef MOD
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015 cpichard.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#if HAVE_ALEMBIC
#include "AlembicImporter.hpp"
#include <Alembic/AbcGeom/All.h>
#include <Alembic/AbcCoreFactory/All.h>
using namespace Alembic::Abc;
namespace AbcG = Alembic::AbcGeom;
using namespace AbcG;
namespace openMVG {
namespace dataio {
/**
* @brief Retrieve an Abc property.
* Maya convert everything into arrays. So here we made a trick
* to retrieve the element directly or the first element
* if it's an array.
* @param userProps
* @param id
* @return value
*/
template<class AbcProperty>
typename AbcProperty::traits_type::value_type getAbcProp(ICompoundProperty& userProps, const Alembic::Abc::PropertyHeader& propHeader, const std::string& id)
{
typedef typename AbcProperty::traits_type traits_type;
typedef typename traits_type::value_type value_type;
typedef typename Alembic::Abc::ITypedArrayProperty<traits_type> array_type;
typedef typename array_type::sample_ptr_type array_sample_ptr_type;
// Maya transforms everything into arrays
if(propHeader.isArray())
{
Alembic::Abc::ITypedArrayProperty<traits_type> prop(userProps, id);
array_sample_ptr_type sample;
prop.get(sample);
return (*sample)[0];
}
else
{
value_type v;
AbcProperty prop(userProps, id);
prop.get(v);
return v;
}
}
template<class ABCSCHEMA>
inline ICompoundProperty getAbcUserProperties(ABCSCHEMA& schema)
{
ICompoundProperty userProps = schema.getUserProperties();
if(userProps && userProps.getNumProperties() != 0)
return userProps;
// Maya always use ArbGeomParams instead of user properties.
return schema.getArbGeomParams();
}
bool AlembicImporter::readPointCloud(IObject iObj, M44d mat, sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part)
{
using namespace openMVG::geometry;
using namespace openMVG::sfm;
IPoints points(iObj, kWrapExisting);
IPointsSchema& ms = points.getSchema();
P3fArraySamplePtr positions = ms.getValue().getPositions();
ICompoundProperty userProps = getAbcUserProperties(ms);
// Number of points before adding the Alembic data
const std::size_t nbPointsInit = sfmdata.structure.size();
// Number of points with all the new Alembic data
std::size_t nbPointsAll = nbPointsInit + positions->size();
for(std::size_t point3d_i = nbPointsInit;
point3d_i < nbPointsAll;
++point3d_i)
{
const P3fArraySamplePtr::element_type::value_type & pos_i = positions->get()[point3d_i];
Landmark& landmark = sfmdata.structure[point3d_i] = Landmark(Vec3(pos_i.x, pos_i.y, pos_i.z));
}
if(userProps.getPropertyHeader("mvg_visibilitySize") &&
userProps.getPropertyHeader("mvg_visibilityIds") &&
userProps.getPropertyHeader("mvg_visibilityFeatPos")
)
{
IUInt32ArrayProperty propVisibilitySize(userProps, "mvg_visibilitySize");
std::shared_ptr<UInt32ArraySample> sampleVisibilitySize;
propVisibilitySize.get(sampleVisibilitySize);
IUInt32ArrayProperty propVisibilityIds(userProps, "mvg_visibilityIds");
std::shared_ptr<UInt32ArraySample> sampleVisibilityIds;
propVisibilityIds.get(sampleVisibilityIds);
IFloatArrayProperty propFeatPos2d(userProps, "mvg_visibilityFeatPos");
std::shared_ptr<FloatArraySample> sampleFeatPos2d;
propFeatPos2d.get(sampleFeatPos2d);
if( positions->size() != sampleVisibilitySize->size() )
{
std::cerr << "ABC Error: number of observations per 3D point should be identical to the number of 2D features." << std::endl;
std::cerr << "Number of observations per 3D point size is " << sampleVisibilitySize->size() << std::endl;
std::cerr << "Number of 3D points is " << positions->size() << std::endl;
return false;
}
if( sampleVisibilityIds->size() != sampleFeatPos2d->size() )
{
std::cerr << "ABC Error: visibility Ids and features 2D pos should have the same size." << std::endl;
std::cerr << "Visibility Ids size is " << sampleVisibilityIds->size() << std::endl;
std::cerr << "Features 2d Pos size is " << sampleFeatPos2d->size() << std::endl;
return false;
}
std::size_t obsGlobal_i = 0;
for(std::size_t point3d_i = nbPointsInit;
point3d_i < nbPointsAll;
++point3d_i)
{
Landmark& landmark = sfmdata.structure[point3d_i];
// Number of observation for this 3d point
const std::size_t visibilitySize = (*sampleVisibilitySize)[point3d_i];
for(std::size_t obs_i = 0;
obs_i < visibilitySize*2;
obs_i+=2, obsGlobal_i+=2)
{
const int viewID = (*sampleVisibilityIds)[obsGlobal_i];
const int featID = (*sampleVisibilityIds)[obsGlobal_i+1];
Observation& obs = landmark.obs[viewID];
obs.id_feat = featID;
const float posX = (*sampleFeatPos2d)[obsGlobal_i];
const float posY = (*sampleFeatPos2d)[obsGlobal_i+1];
obs.x[0] = posX;
obs.x[1] = posY;
}
}
}
return true;
}
bool AlembicImporter::readCamera(IObject iObj, M44d mat, sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part)
{
using namespace openMVG::geometry;
using namespace openMVG::cameras;
using namespace openMVG::sfm;
ICamera camera(iObj, kWrapExisting);
ICameraSchema cs = camera.getSchema();
CameraSample camSample = cs.getValue();
// Check if we have an associated image plane
ICompoundProperty userProps = getAbcUserProperties(cs);
std::string imagePath;
float sensorWidth_pix = 2048.0;
std::string mvg_intrinsicType = "PINHOLE_CAMERA";
std::vector<double> mvg_intrinsicParams;
IndexT id_view = sfmdata.GetViews().size();
IndexT id_intrinsic = sfmdata.GetIntrinsics().size();
if(userProps)
{
if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_imagePath"))
{
imagePath = getAbcProp<Alembic::Abc::IStringProperty>(userProps, *propHeader, "mvg_imagePath");
}
if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_sensorWidth_pix"))
{
try {
sensorWidth_pix = getAbcProp<Alembic::Abc::IUInt32Property>(userProps, *propHeader, "mvg_sensorWidth_pix");
} catch(Alembic::Util::v7::Exception&)
{
sensorWidth_pix = getAbcProp<Alembic::Abc::IInt32Property>(userProps, *propHeader, "mvg_sensorWidth_pix");
}
}
if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_intrinsicType"))
{
mvg_intrinsicType = getAbcProp<Alembic::Abc::IStringProperty>(userProps, *propHeader, "mvg_intrinsicType");
}
if(userProps.getPropertyHeader("mvg_intrinsicParams"))
{
Alembic::Abc::IDoubleArrayProperty prop(userProps, "mvg_intrinsicParams");
std::shared_ptr<DoubleArraySample> sample;
prop.get(sample);
mvg_intrinsicParams.assign(sample->get(), sample->get()+sample->size());
}
if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_viewId"))
{
try {
id_view = getAbcProp<Alembic::Abc::IUInt32Property>(userProps, *propHeader, "mvg_viewId");
} catch(Alembic::Util::v7::Exception&)
{
id_view = getAbcProp<Alembic::Abc::IInt32Property>(userProps, *propHeader, "mvg_viewId");
}
}
if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_intrinsicId"))
{
try {
id_intrinsic = getAbcProp<Alembic::Abc::IUInt32Property>(userProps, *propHeader, "mvg_intrinsicId");
} catch(Alembic::Util::v7::Exception&)
{
id_intrinsic = getAbcProp<Alembic::Abc::IInt32Property>(userProps, *propHeader, "mvg_intrinsicId");
}
}
}
// OpenMVG Camera
Mat3 cam_r;
cam_r(0,0) = mat[0][0];
cam_r(0,1) = mat[0][1];
cam_r(0,2) = mat[0][2];
cam_r(1,0) = mat[1][0];
cam_r(1,1) = mat[1][1];
cam_r(1,2) = mat[1][2];
cam_r(2,0) = mat[2][0];
cam_r(2,1) = mat[2][1];
cam_r(2,2) = mat[2][2];
Vec3 cam_t;
cam_t(0) = mat[3][0];
cam_t(1) = mat[3][1];
cam_t(2) = mat[3][2];
// Correct camera orientation from alembic
Mat3 scale;
scale(0,0) = 1;
scale(1,1) = -1;
scale(2,2) = -1;
cam_r = scale*cam_r;
Pose3 pose(cam_r, cam_t);
// Get known values from alembic
const float haperture_cm = camSample.getHorizontalAperture();
const float vaperture_cm = camSample.getVerticalAperture();
const float hoffset_cm = camSample.getHorizontalFilmOffset();
const float voffset_cm = camSample.getVerticalFilmOffset();
const float focalLength_mm = camSample.getFocalLength();
// Compute other needed values
const float sensorWidth_mm = std::max(vaperture_cm, haperture_cm) * 10.0;
const float mm2pix = sensorWidth_pix / sensorWidth_mm;
const float imgWidth = haperture_cm * 10.0 * mm2pix;
const float imgHeight = vaperture_cm * 10.0 * mm2pix;
const float focalLength_pix = focalLength_mm * mm2pix;
// Following values are in cm, hence the 10.0 multiplier
const float hoffset_pix = (imgWidth*0.5) - (10.0 * hoffset_cm * mm2pix);
const float voffset_pix = (imgHeight*0.5) + (10.0 * voffset_cm * mm2pix);
// Create intrinsic parameters object
std::shared_ptr<Pinhole_Intrinsic> pinholeIntrinsic = createPinholeIntrinsic(EINTRINSIC_stringToEnum(mvg_intrinsicType));
pinholeIntrinsic->setWidth(imgWidth);
pinholeIntrinsic->setHeight(imgHeight);
pinholeIntrinsic->setK(focalLength_pix, hoffset_pix, voffset_pix);
pinholeIntrinsic->updateFromParams(mvg_intrinsicParams);
// Add imported data to the SfM_Data container TODO use UID
sfmdata.views.emplace(id_view, std::make_shared<View>(imagePath, id_view, id_intrinsic, id_view, imgWidth, imgHeight));
sfmdata.poses.emplace(id_view, pose);
sfmdata.intrinsics.emplace(id_intrinsic, pinholeIntrinsic);
return true;
}
// Top down read of 3d objects
void AlembicImporter::visitObject(IObject iObj, M44d mat, sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part)
{
// std::cout << "ABC visit: " << iObj.getFullName() << std::endl;
const MetaData& md = iObj.getMetaData();
if(IPoints::matches(md) && (flags_part & sfm::ESfM_Data::STRUCTURE))
{
readPointCloud(iObj, mat, sfmdata, flags_part);
}
else if(IXform::matches(md))
{
IXform xform(iObj, kWrapExisting);
XformSample xs;
xform.getSchema().get(xs);
mat *= xs.getMatrix();
}
else if(ICamera::matches(md) && (flags_part & sfm::ESfM_Data::EXTRINSICS))
{
readCamera(iObj, mat, sfmdata, flags_part);
}
// Recurse
for(size_t i = 0; i < iObj.getNumChildren(); i++)
{
visitObject(iObj.getChild(i), mat, sfmdata, flags_part);
}
}
AlembicImporter::AlembicImporter(const std::string &filename)
{
Alembic::AbcCoreFactory::IFactory factory;
Alembic::AbcCoreFactory::IFactory::CoreType coreType;
Abc::IArchive archive = factory.getArchive(filename, coreType);
// TODO : test if archive is correctly opened
_rootEntity = archive.getTop();
}
void AlembicImporter::populate(sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part)
{
// TODO : handle the case where the archive wasn't correctly opened
M44d xformMat;
visitObject(_rootEntity, xformMat, sfmdata, flags_part);
// TODO: fusion of common intrinsics
}
} // namespace data_io
} // namespace openMVG
#endif // WITH_ALEMBIC
<commit_msg>[dataio] correct initialization for scale fix poparteu/openMVG#80<commit_after>// Copyright (c) 2015 cpichard.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#if HAVE_ALEMBIC
#include "AlembicImporter.hpp"
#include <Alembic/AbcGeom/All.h>
#include <Alembic/AbcCoreFactory/All.h>
using namespace Alembic::Abc;
namespace AbcG = Alembic::AbcGeom;
using namespace AbcG;
namespace openMVG {
namespace dataio {
/**
* @brief Retrieve an Abc property.
* Maya convert everything into arrays. So here we made a trick
* to retrieve the element directly or the first element
* if it's an array.
* @param userProps
* @param id
* @return value
*/
template<class AbcProperty>
typename AbcProperty::traits_type::value_type getAbcProp(ICompoundProperty& userProps, const Alembic::Abc::PropertyHeader& propHeader, const std::string& id)
{
typedef typename AbcProperty::traits_type traits_type;
typedef typename traits_type::value_type value_type;
typedef typename Alembic::Abc::ITypedArrayProperty<traits_type> array_type;
typedef typename array_type::sample_ptr_type array_sample_ptr_type;
// Maya transforms everything into arrays
if(propHeader.isArray())
{
Alembic::Abc::ITypedArrayProperty<traits_type> prop(userProps, id);
array_sample_ptr_type sample;
prop.get(sample);
return (*sample)[0];
}
else
{
value_type v;
AbcProperty prop(userProps, id);
prop.get(v);
return v;
}
}
template<class ABCSCHEMA>
inline ICompoundProperty getAbcUserProperties(ABCSCHEMA& schema)
{
ICompoundProperty userProps = schema.getUserProperties();
if(userProps && userProps.getNumProperties() != 0)
return userProps;
// Maya always use ArbGeomParams instead of user properties.
return schema.getArbGeomParams();
}
bool AlembicImporter::readPointCloud(IObject iObj, M44d mat, sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part)
{
using namespace openMVG::geometry;
using namespace openMVG::sfm;
IPoints points(iObj, kWrapExisting);
IPointsSchema& ms = points.getSchema();
P3fArraySamplePtr positions = ms.getValue().getPositions();
ICompoundProperty userProps = getAbcUserProperties(ms);
// Number of points before adding the Alembic data
const std::size_t nbPointsInit = sfmdata.structure.size();
// Number of points with all the new Alembic data
std::size_t nbPointsAll = nbPointsInit + positions->size();
for(std::size_t point3d_i = nbPointsInit;
point3d_i < nbPointsAll;
++point3d_i)
{
const P3fArraySamplePtr::element_type::value_type & pos_i = positions->get()[point3d_i];
Landmark& landmark = sfmdata.structure[point3d_i] = Landmark(Vec3(pos_i.x, pos_i.y, pos_i.z));
}
if(userProps.getPropertyHeader("mvg_visibilitySize") &&
userProps.getPropertyHeader("mvg_visibilityIds") &&
userProps.getPropertyHeader("mvg_visibilityFeatPos")
)
{
IUInt32ArrayProperty propVisibilitySize(userProps, "mvg_visibilitySize");
std::shared_ptr<UInt32ArraySample> sampleVisibilitySize;
propVisibilitySize.get(sampleVisibilitySize);
IUInt32ArrayProperty propVisibilityIds(userProps, "mvg_visibilityIds");
std::shared_ptr<UInt32ArraySample> sampleVisibilityIds;
propVisibilityIds.get(sampleVisibilityIds);
IFloatArrayProperty propFeatPos2d(userProps, "mvg_visibilityFeatPos");
std::shared_ptr<FloatArraySample> sampleFeatPos2d;
propFeatPos2d.get(sampleFeatPos2d);
if( positions->size() != sampleVisibilitySize->size() )
{
std::cerr << "ABC Error: number of observations per 3D point should be identical to the number of 2D features." << std::endl;
std::cerr << "Number of observations per 3D point size is " << sampleVisibilitySize->size() << std::endl;
std::cerr << "Number of 3D points is " << positions->size() << std::endl;
return false;
}
if( sampleVisibilityIds->size() != sampleFeatPos2d->size() )
{
std::cerr << "ABC Error: visibility Ids and features 2D pos should have the same size." << std::endl;
std::cerr << "Visibility Ids size is " << sampleVisibilityIds->size() << std::endl;
std::cerr << "Features 2d Pos size is " << sampleFeatPos2d->size() << std::endl;
return false;
}
std::size_t obsGlobal_i = 0;
for(std::size_t point3d_i = nbPointsInit;
point3d_i < nbPointsAll;
++point3d_i)
{
Landmark& landmark = sfmdata.structure[point3d_i];
// Number of observation for this 3d point
const std::size_t visibilitySize = (*sampleVisibilitySize)[point3d_i];
for(std::size_t obs_i = 0;
obs_i < visibilitySize*2;
obs_i+=2, obsGlobal_i+=2)
{
const int viewID = (*sampleVisibilityIds)[obsGlobal_i];
const int featID = (*sampleVisibilityIds)[obsGlobal_i+1];
Observation& obs = landmark.obs[viewID];
obs.id_feat = featID;
const float posX = (*sampleFeatPos2d)[obsGlobal_i];
const float posY = (*sampleFeatPos2d)[obsGlobal_i+1];
obs.x[0] = posX;
obs.x[1] = posY;
}
}
}
return true;
}
bool AlembicImporter::readCamera(IObject iObj, M44d mat, sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part)
{
using namespace openMVG::geometry;
using namespace openMVG::cameras;
using namespace openMVG::sfm;
ICamera camera(iObj, kWrapExisting);
ICameraSchema cs = camera.getSchema();
CameraSample camSample = cs.getValue();
// Check if we have an associated image plane
ICompoundProperty userProps = getAbcUserProperties(cs);
std::string imagePath;
float sensorWidth_pix = 2048.0;
std::string mvg_intrinsicType = "PINHOLE_CAMERA";
std::vector<double> mvg_intrinsicParams;
IndexT id_view = sfmdata.GetViews().size();
IndexT id_intrinsic = sfmdata.GetIntrinsics().size();
if(userProps)
{
if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_imagePath"))
{
imagePath = getAbcProp<Alembic::Abc::IStringProperty>(userProps, *propHeader, "mvg_imagePath");
}
if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_sensorWidth_pix"))
{
try {
sensorWidth_pix = getAbcProp<Alembic::Abc::IUInt32Property>(userProps, *propHeader, "mvg_sensorWidth_pix");
} catch(Alembic::Util::v7::Exception&)
{
sensorWidth_pix = getAbcProp<Alembic::Abc::IInt32Property>(userProps, *propHeader, "mvg_sensorWidth_pix");
}
}
if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_intrinsicType"))
{
mvg_intrinsicType = getAbcProp<Alembic::Abc::IStringProperty>(userProps, *propHeader, "mvg_intrinsicType");
}
if(userProps.getPropertyHeader("mvg_intrinsicParams"))
{
Alembic::Abc::IDoubleArrayProperty prop(userProps, "mvg_intrinsicParams");
std::shared_ptr<DoubleArraySample> sample;
prop.get(sample);
mvg_intrinsicParams.assign(sample->get(), sample->get()+sample->size());
}
if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_viewId"))
{
try {
id_view = getAbcProp<Alembic::Abc::IUInt32Property>(userProps, *propHeader, "mvg_viewId");
} catch(Alembic::Util::v7::Exception&)
{
id_view = getAbcProp<Alembic::Abc::IInt32Property>(userProps, *propHeader, "mvg_viewId");
}
}
if(const Alembic::Abc::PropertyHeader *propHeader = userProps.getPropertyHeader("mvg_intrinsicId"))
{
try {
id_intrinsic = getAbcProp<Alembic::Abc::IUInt32Property>(userProps, *propHeader, "mvg_intrinsicId");
} catch(Alembic::Util::v7::Exception&)
{
id_intrinsic = getAbcProp<Alembic::Abc::IInt32Property>(userProps, *propHeader, "mvg_intrinsicId");
}
}
}
// OpenMVG Camera
Mat3 cam_r;
cam_r(0,0) = mat[0][0];
cam_r(0,1) = mat[0][1];
cam_r(0,2) = mat[0][2];
cam_r(1,0) = mat[1][0];
cam_r(1,1) = mat[1][1];
cam_r(1,2) = mat[1][2];
cam_r(2,0) = mat[2][0];
cam_r(2,1) = mat[2][1];
cam_r(2,2) = mat[2][2];
Vec3 cam_t;
cam_t(0) = mat[3][0];
cam_t(1) = mat[3][1];
cam_t(2) = mat[3][2];
// Correct camera orientation from alembic
const Mat3 scale = Vec3(1,-1,-1).asDiagonal();
cam_r = scale*cam_r;
Pose3 pose(cam_r, cam_t);
// Get known values from alembic
const float haperture_cm = camSample.getHorizontalAperture();
const float vaperture_cm = camSample.getVerticalAperture();
const float hoffset_cm = camSample.getHorizontalFilmOffset();
const float voffset_cm = camSample.getVerticalFilmOffset();
const float focalLength_mm = camSample.getFocalLength();
// Compute other needed values
const float sensorWidth_mm = std::max(vaperture_cm, haperture_cm) * 10.0;
const float mm2pix = sensorWidth_pix / sensorWidth_mm;
const float imgWidth = haperture_cm * 10.0 * mm2pix;
const float imgHeight = vaperture_cm * 10.0 * mm2pix;
const float focalLength_pix = focalLength_mm * mm2pix;
// Following values are in cm, hence the 10.0 multiplier
const float hoffset_pix = (imgWidth*0.5) - (10.0 * hoffset_cm * mm2pix);
const float voffset_pix = (imgHeight*0.5) + (10.0 * voffset_cm * mm2pix);
// Create intrinsic parameters object
std::shared_ptr<Pinhole_Intrinsic> pinholeIntrinsic = createPinholeIntrinsic(EINTRINSIC_stringToEnum(mvg_intrinsicType));
pinholeIntrinsic->setWidth(imgWidth);
pinholeIntrinsic->setHeight(imgHeight);
pinholeIntrinsic->setK(focalLength_pix, hoffset_pix, voffset_pix);
pinholeIntrinsic->updateFromParams(mvg_intrinsicParams);
// Add imported data to the SfM_Data container TODO use UID
sfmdata.views.emplace(id_view, std::make_shared<View>(imagePath, id_view, id_intrinsic, id_view, imgWidth, imgHeight));
sfmdata.poses.emplace(id_view, pose);
sfmdata.intrinsics.emplace(id_intrinsic, pinholeIntrinsic);
return true;
}
// Top down read of 3d objects
void AlembicImporter::visitObject(IObject iObj, M44d mat, sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part)
{
// std::cout << "ABC visit: " << iObj.getFullName() << std::endl;
const MetaData& md = iObj.getMetaData();
if(IPoints::matches(md) && (flags_part & sfm::ESfM_Data::STRUCTURE))
{
readPointCloud(iObj, mat, sfmdata, flags_part);
}
else if(IXform::matches(md))
{
IXform xform(iObj, kWrapExisting);
XformSample xs;
xform.getSchema().get(xs);
mat *= xs.getMatrix();
}
else if(ICamera::matches(md) && (flags_part & sfm::ESfM_Data::EXTRINSICS))
{
readCamera(iObj, mat, sfmdata, flags_part);
}
// Recurse
for(size_t i = 0; i < iObj.getNumChildren(); i++)
{
visitObject(iObj.getChild(i), mat, sfmdata, flags_part);
}
}
AlembicImporter::AlembicImporter(const std::string &filename)
{
Alembic::AbcCoreFactory::IFactory factory;
Alembic::AbcCoreFactory::IFactory::CoreType coreType;
Abc::IArchive archive = factory.getArchive(filename, coreType);
// TODO : test if archive is correctly opened
_rootEntity = archive.getTop();
}
void AlembicImporter::populate(sfm::SfM_Data &sfmdata, sfm::ESfM_Data flags_part)
{
// TODO : handle the case where the archive wasn't correctly opened
M44d xformMat;
visitObject(_rootEntity, xformMat, sfmdata, flags_part);
// TODO: fusion of common intrinsics
}
} // namespace data_io
} // namespace openMVG
#endif // WITH_ALEMBIC
<|endoftext|> |
<commit_before>/*
* ArcScripts for ArcEmu MMORPG Server
* Copyright (C) 2009 ArcEmu Team <http://www.arcemu.org/>
* Copyright (C) 2008-2009 Sun++ Team <http://www.sunscripting.com/>
* Copyright (C) 2008 WEmu Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Setup.h"
#define SendQuickMenu(textid) objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), textid, plr); \
Menu->SendTo(plr);
class TheSummoning : public GossipScript
{
public:
void GossipHello(Object* pObject, Player* plr)
{
if(!plr)
return;
GossipMenu* Menu;
Creature* windwatcher = TO_CREATURE(pObject);
if(windwatcher == NULL)
return;
objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 1, plr);
if(plr->GetQuestLogForEntry(1713))
Menu->AddItem(0, "I'm ready, Summon Him!", 1);
Menu->SendTo(plr);
}
void GossipSelectOption(Object* pObject, Player* plr, uint32 Id, uint32 IntId, const char* EnteredCode)
{
if(!plr)
return;
Creature* windwatcher = TO_CREATURE(pObject);
if(windwatcher == NULL)
return;
switch(IntId)
{
case 0:
GossipHello(pObject, plr);
break;
case 1:
{
Creature* whirlwind = plr->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(plr->GetPositionX(), plr->GetPositionY(), plr->GetPositionZ(), 6239);
if(whirlwind != NULL)
{
if(!whirlwind->isAlive())
{
whirlwind->Delete();
}
else
return;
}
whirlwind = sEAS.SpawnCreature(plr, 6239, plr->GetPositionX() + 7, plr->GetPositionY() + 7, plr->GetPositionZ(), plr->GetOrientation(), 0);
whirlwind->Despawn(5 * 60 * 1000, 0);
}
break;
}
}
};
class Bartleby : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(Bartleby);
Bartleby(Creature* pCreature) : CreatureAIScript(pCreature) {}
void OnLoad()
{
_unit->SetFaction(11);
_unit->setEmoteState(7);
}
void OnDamageTaken(Unit* mAttacker, uint32 fAmount)
{
if(_unit->GetUInt32Value(UNIT_FIELD_HEALTH) - fAmount <= _unit->GetUInt32Value(UNIT_FIELD_MAXHEALTH) * 0.37f)
{
if(mAttacker->IsPlayer())
{
_unit->SetUInt64Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
RegisterAIUpdateEvent(1000);
QuestLogEntry* qle = (TO_PLAYER(mAttacker))->GetQuestLogForEntry(1640);
if(!qle)
return;
qle->SendQuestComplete();
}
}
}
void AIUpdate()
{
_unit->RemoveNegativeAuras();
_unit->SetFaction(11);
_unit->SetHealthPct(100);
_unit->GetAIInterface()->WipeTargetList();
_unit->GetAIInterface()->WipeHateList();
_unit->GetAIInterface()->HandleEvent(EVENT_LEAVECOMBAT, _unit, 0);
_unit->GetAIInterface()->disable_melee = true;
_unit->GetAIInterface()->SetAllowedToEnterCombat(false);
_unit->SetUInt32Value(UNIT_FIELD_FLAGS, 0);
}
void OnDied(Unit* mKiller)
{
RemoveAIUpdateEvent();
}
};
class BeatBartleby : public QuestScript
{
public:
void OnQuestStart(Player* mTarget, QuestLogEntry* qLogEntry)
{
float SSX = mTarget->GetPositionX();
float SSY = mTarget->GetPositionY();
float SSZ = mTarget->GetPositionZ();
Creature* Bartleby = mTarget->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(SSX, SSY, SSZ, 6090);
if(Bartleby == NULL)
return;
Bartleby->SetFaction(168);
Bartleby->GetAIInterface()->disable_melee = false;
Bartleby->GetAIInterface()->SetAllowedToEnterCombat(true);
}
};
void SetupWarrior(ScriptMgr* mgr)
{
GossipScript* gossip1 = new TheSummoning();
mgr->register_gossip_script(6176, gossip1);
mgr->register_creature_script(6090, &Bartleby::Create);
mgr->register_quest_script(1640, new BeatBartleby());
}
<commit_msg>Script Warrior Quest 1713 The Summoning<commit_after>/*
* ArcScripts for ArcEmu MMORPG Server
* Copyright (C) 2009 ArcEmu Team <http://www.arcemu.org/>
* Copyright (C) 2008-2009 Sun++ Team <http://www.sunscripting.com/>
* Copyright (C) 2008 WEmu Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Setup.h"
#define SendQuickMenu(textid) objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), textid, plr); \
Menu->SendTo(plr);
class TheSummoning : public QuestScript
{
public:
void OnQuestStart(Player* pPlayer, QuestLogEntry* qLogEntry) {}
{
Creature *windwatcher = pPlayer->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(pPlayer->GetPositionX(), pPlayer->GetPositionY(), pPlayer->GetPositionZ(), 6176);
if(!windwatcher) return;
// questgiver will walk to the place where Cyclonian is spawned
// only walk when we are at home
if(windwatcher->CalcDistance(250.839996, -1470.579956, 55.4491) > 1) return;
{
windwatcher->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Follow me");
sEAS.CreateCustomWaypointMap(windwatcher);
sEAS.WaypointCreate(windwatcher, 269.29, -1433.32, 50.31, 0.19, 0, 0, 0);
sEAS.WaypointCreate(windwatcher, 328.52, -1442.03, 40.5, 5.65, 0, 0, 0);
sEAS.WaypointCreate(windwatcher, 333.31, -1453.69, 42.01, 4.68, 0, 0, 0);
sEAS.EnableWaypoints(windwatcher);
windwatcher->GetAIInterface()->setMoveType(11);
}
windwatcher->Despawn(15*60*1000);
// spawn cyclonian if not spawned already
Creature *cyclonian = pPlayer->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(323.947, -1483.68, 43.1363, 6239);
if(pPlayer->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(323.947, -1483.68, 43.1363, 6239) == NULL)
cyclonian = sEAS.SpawnCreature(plr, 6239, 323.947, -1483.68, 43.1363, 0.682991);
cyclonian->Despawn(15*60*1000);
}
};
class Bartleby : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(Bartleby);
Bartleby(Creature* pCreature) : CreatureAIScript(pCreature) {}
void OnLoad()
{
_unit->SetFaction(11);
_unit->setEmoteState(7);
}
void OnDamageTaken(Unit* mAttacker, uint32 fAmount)
{
if(_unit->GetUInt32Value(UNIT_FIELD_HEALTH) - fAmount <= _unit->GetUInt32Value(UNIT_FIELD_MAXHEALTH) * 0.37f)
{
if(mAttacker->IsPlayer())
{
_unit->SetUInt64Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
RegisterAIUpdateEvent(1000);
QuestLogEntry* qle = (TO_PLAYER(mAttacker))->GetQuestLogForEntry(1640);
if(!qle)
return;
qle->SendQuestComplete();
}
}
}
void AIUpdate()
{
_unit->RemoveNegativeAuras();
_unit->SetFaction(11);
_unit->SetHealthPct(100);
_unit->GetAIInterface()->WipeTargetList();
_unit->GetAIInterface()->WipeHateList();
_unit->GetAIInterface()->HandleEvent(EVENT_LEAVECOMBAT, _unit, 0);
_unit->GetAIInterface()->disable_melee = true;
_unit->GetAIInterface()->SetAllowedToEnterCombat(false);
_unit->SetUInt32Value(UNIT_FIELD_FLAGS, 0);
}
void OnDied(Unit* mKiller)
{
RemoveAIUpdateEvent();
}
};
class BeatBartleby : public QuestScript
{
public:
void OnQuestStart(Player* mTarget, QuestLogEntry* qLogEntry)
{
float SSX = mTarget->GetPositionX();
float SSY = mTarget->GetPositionY();
float SSZ = mTarget->GetPositionZ();
Creature* Bartleby = mTarget->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(SSX, SSY, SSZ, 6090);
if(Bartleby == NULL)
return;
Bartleby->SetFaction(168);
Bartleby->GetAIInterface()->disable_melee = false;
Bartleby->GetAIInterface()->SetAllowedToEnterCombat(true);
}
};
void SetupWarrior(ScriptMgr* mgr)
{
mgr->register_quest_script(1713, new TheSummoning());
mgr->register_creature_script(6090, &Bartleby::Create);
mgr->register_quest_script(1640, new BeatBartleby());
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014, peelo.net
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 <peelo/io/filename.hpp>
#if defined(_WIN32)
# include <windows.h>
#else
# include <unistd.h>
# include <sys/stat.h>
#endif
namespace peelo
{
filename::filename() {}
filename::filename(const filename& that)
: m_path(that.m_path)
, m_device(that.m_device)
, m_location(that.m_location)
, m_file(that.m_file)
, m_extension(that.m_extension) {}
bool filename::is_separator(const rune& r)
{
return r == '/' || r == '\\';
}
bool filename::empty() const
{
return m_path.empty();
}
filename& filename::assign(const filename& that)
{
m_path = that.m_path;
m_device = that.m_device;
m_location = that.m_location;
m_file = that.m_file;
m_extension = that.m_extension;
return *this;
}
bool filename::equals(const filename& that) const
{
return m_path == that.m_path;
}
bool filename::is_absolute() const
{
return !m_location.empty() && is_separator(m_location[0]);
}
bool filename::exists() const
{
if (empty())
{
return false;
}
#if defined(_WIN32)
return ::GetFileAttributesW(m_path.widen().data())
!= INVALID_FILE_ATTRIBUTES;
#else
return !::access(m_path.utf8().data(), F_OK);
#endif
}
}
<commit_msg>add missing comparison method<commit_after>/*
* Copyright (c) 2014, peelo.net
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 <peelo/io/filename.hpp>
#if defined(_WIN32)
# include <windows.h>
#else
# include <unistd.h>
# include <sys/stat.h>
#endif
namespace peelo
{
filename::filename() {}
filename::filename(const filename& that)
: m_path(that.m_path)
, m_device(that.m_device)
, m_location(that.m_location)
, m_file(that.m_file)
, m_extension(that.m_extension) {}
bool filename::is_separator(const rune& r)
{
return r == '/' || r == '\\';
}
bool filename::empty() const
{
return m_path.empty();
}
filename& filename::assign(const filename& that)
{
m_path = that.m_path;
m_device = that.m_device;
m_location = that.m_location;
m_file = that.m_file;
m_extension = that.m_extension;
return *this;
}
bool filename::equals(const filename& that) const
{
return m_path == that.m_path;
}
int filename::compare(const filename& that) const
{
#if defined(_WIN32)
return m_path.compare_icase(that.m_path);
#else
return m_path.compare(that.m_path);
#endif
}
bool filename::is_absolute() const
{
return !m_location.empty() && is_separator(m_location[0]);
}
bool filename::exists() const
{
if (empty())
{
return false;
}
#if defined(_WIN32)
return ::GetFileAttributesW(m_path.widen().data())
!= INVALID_FILE_ATTRIBUTES;
#else
return !::access(m_path.utf8().data(), F_OK);
#endif
}
}
<|endoftext|> |
<commit_before>#include "particle_emitter.h"
static const char kVertexShader[] =
"attribute vec4 vertex;\n"
"attribute vec4 incolor;\n"
"uniform mat4 mvp;\n"
"varying vec4 v_color;\n"
"void main() {\n"
" gl_PointSize = 16.0;\n"
" gl_Position = mvp*vertex;\n"
" v_color = incolor;\n"
"}\n";
static const char kFragmentShader[] = "varying vec4 v_color;\n"
"void main() {\n"
" gl_FragColor = v_color;\n"
"}\n";
float starting_alpha = 0.25f;
ParticleEmitter::ParticleEmitter() {
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
shader_program_ = GlUtil::CreateProgram(kVertexShader, kFragmentShader);
if (!shader_program_) {
LOGE("Could not create program.");
}
uniform_mvp_mat_ = glGetUniformLocation(shader_program_, "mvp");
attrib_vertices_ = glGetAttribLocation(shader_program_, "vertex");
attrib_colors_ = glGetAttribLocation(shader_program_, "incolor");
glGenBuffers(1, &vertex_buffers_);
glGenBuffers(1, &color_buffers_);
num_parts = 64;
part_start_coords = new float[num_parts*3];
part_end_coords = new float[num_parts*3];
part_coords = new float[num_parts*3];
part_colors = new float[num_parts*4];
part_ratios = new float[num_parts];
for(int i=0; i<3*num_parts; i++){
part_start_coords[i] = 0.0f;
part_end_coords[i] = (rand()%256 - 128)/(128.0f*24);
}
for(int i=0;i<num_parts;i++){
part_ratios[i] = (rand()%256)/256.0f;
part_coords[3*i] = part_start_coords[3*i]*(1.0f-part_ratios[i]) + part_end_coords[3*i]*part_ratios[i];
part_coords[3*i+1] = part_start_coords[3*i+1]*(1.0f-part_ratios[i]) + part_end_coords[3*i+1]*part_ratios[i];
part_coords[3*i+2] = part_start_coords[3*i+2]*(1.0f-part_ratios[i]) + part_end_coords[3*i+2]*part_ratios[i];
}
for(int i=0;i<num_parts;i++){
part_colors[4*i] = 1.0f;
part_colors[4*i+1] = 0.5f;
part_colors[4*i+2] = 0.75f;
part_colors[4*i+3] = starting_alpha*(1.0f-part_ratios[i]);
}
}
void ParticleEmitter::UpdateParticles(){
for(int i=0;i<num_parts;i++){
part_ratios[i] = part_ratios[i] + 1.0f/16.0f;
if(part_ratios[i] >= 1.0f){
part_ratios[i] -= 1.0f;
}
part_coords[3*i] = part_start_coords[3*i]*(1.0f-part_ratios[i]) + part_end_coords[3*i]*part_ratios[i];
part_coords[3*i+1] = part_start_coords[3*i+1]*(1.0f-part_ratios[i]) + part_end_coords[3*i+1]*part_ratios[i];
part_coords[3*i+2] = part_start_coords[3*i+2]*(1.0f-part_ratios[i]) + part_end_coords[3*i+2]*part_ratios[i];
part_colors[4*i+3] = starting_alpha*(1.0f-part_ratios[i]);
}
}
void ParticleEmitter::Render(glm::mat4 projection_mat, glm::mat4 view_mat){
glUseProgram(shader_program_);
glm::mat4 model_mat =
glm::translate(glm::mat4(1.0f), emitter_location);
// Calculate model view projection matrix.
static glm::mat4 inverse_z_mat(1.0f, 0.0f, 0.0f, 0.0f,
0.0f, -1.0f, 0.0f, 0.0f,
0.0f, 0.0f, -1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
glm::mat4 mvp_mat = projection_mat * view_mat * model_mat * inverse_z_mat;
glUniformMatrix4fv(uniform_mvp_mat_, 1, GL_FALSE, glm::value_ptr(mvp_mat));
// Bind vertex buffer.
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffers_);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * num_parts * 3,
part_coords, GL_STATIC_DRAW);
glEnableVertexAttribArray(attrib_vertices_);
glVertexAttribPointer(attrib_vertices_, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
//Bind color buffer
glBindBuffer(GL_ARRAY_BUFFER, color_buffers_);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * num_parts * 4,
part_colors, GL_STATIC_DRAW);
glEnableVertexAttribArray(attrib_colors_);
glVertexAttribPointer(attrib_colors_, 4, GL_FLOAT, GL_FALSE, 0, nullptr);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glDrawArrays(GL_POINTS, 0, 3 * num_parts);
glDisable(GL_BLEND);
glUseProgram(0);
}
<commit_msg>Use color to indicate distance<commit_after>#include "particle_emitter.h"
#include "tango_data.h"
static const char kVertexShader[] =
"attribute vec4 vertex;\n"
"attribute vec4 incolor;\n"
"uniform mat4 mvp;\n"
"varying vec4 v_color;\n"
"void main() {\n"
" gl_PointSize = 16.0;\n"
" gl_Position = mvp*vertex;\n"
" v_color = incolor;\n"
"}\n";
static const char kFragmentShader[] = "varying vec4 v_color;\n"
"void main() {\n"
" gl_FragColor = v_color;\n"
"}\n";
float starting_alpha = 0.25f;
ParticleEmitter::ParticleEmitter() {
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
shader_program_ = GlUtil::CreateProgram(kVertexShader, kFragmentShader);
if (!shader_program_) {
LOGE("Could not create program.");
}
uniform_mvp_mat_ = glGetUniformLocation(shader_program_, "mvp");
attrib_vertices_ = glGetAttribLocation(shader_program_, "vertex");
attrib_colors_ = glGetAttribLocation(shader_program_, "incolor");
glGenBuffers(1, &vertex_buffers_);
glGenBuffers(1, &color_buffers_);
num_parts = 64;
part_start_coords = new float[num_parts*3];
part_end_coords = new float[num_parts*3];
part_coords = new float[num_parts*3];
part_colors = new float[num_parts*4];
part_ratios = new float[num_parts];
for(int i=0; i<3*num_parts; i++){
part_start_coords[i] = 0.0f;
part_end_coords[i] = (rand()%256 - 128)/(128.0f*24);
}
for(int i=0;i<num_parts;i++){
part_ratios[i] = (rand()%256)/256.0f;
part_coords[3*i] = part_start_coords[3*i]*(1.0f-part_ratios[i]) + part_end_coords[3*i]*part_ratios[i];
part_coords[3*i+1] = part_start_coords[3*i+1]*(1.0f-part_ratios[i]) + part_end_coords[3*i+1]*part_ratios[i];
part_coords[3*i+2] = part_start_coords[3*i+2]*(1.0f-part_ratios[i]) + part_end_coords[3*i+2]*part_ratios[i];
}
for(int i=0;i<num_parts;i++){
part_colors[4*i] = 1.0f;
part_colors[4*i+1] = 0.0f;
part_colors[4*i+2] = 0.25f;
part_colors[4*i+3] = starting_alpha*(1.0f-part_ratios[i]);
}
}
void ParticleEmitter::UpdateParticles(){
glm::vec3 tango_loc = TangoData::GetInstance().tango_position_depth;
glm::vec3 diff = tango_loc - emitter_location;
float dist = glm::length(diff);
float whiten_amt = 0.0f;
if(dist > 0.5f){
whiten_amt = 1.0f*(0.5f/dist);
} else {
whiten_amt = 1.0f;
}
for(int i=0;i<num_parts;i++){
part_ratios[i] = part_ratios[i] + 1.0f/16.0f;
if(part_ratios[i] >= 1.0f){
part_ratios[i] -= 1.0f;
}
part_coords[3*i] = part_start_coords[3*i]*(1.0f-part_ratios[i]) + part_end_coords[3*i]*part_ratios[i];
part_coords[3*i+1] = part_start_coords[3*i+1]*(1.0f-part_ratios[i]) + part_end_coords[3*i+1]*part_ratios[i];
part_coords[3*i+2] = part_start_coords[3*i+2]*(1.0f-part_ratios[i]) + part_end_coords[3*i+2]*part_ratios[i];
part_colors[4*i] = 1.0f;
part_colors[4*i+1] = 0.0f+whiten_amt;
part_colors[4*i+2] = 0.5f+0.5f*whiten_amt;
part_colors[4*i+3] = starting_alpha*(1.0f-part_ratios[i]);
}
}
void ParticleEmitter::Render(glm::mat4 projection_mat, glm::mat4 view_mat){
glUseProgram(shader_program_);
glm::mat4 model_mat =
glm::translate(glm::mat4(1.0f), emitter_location);
// Calculate model view projection matrix.
static glm::mat4 inverse_z_mat(1.0f, 0.0f, 0.0f, 0.0f,
0.0f, -1.0f, 0.0f, 0.0f,
0.0f, 0.0f, -1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
glm::mat4 mvp_mat = projection_mat * view_mat * model_mat * inverse_z_mat;
glUniformMatrix4fv(uniform_mvp_mat_, 1, GL_FALSE, glm::value_ptr(mvp_mat));
// Bind vertex buffer.
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffers_);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * num_parts * 3,
part_coords, GL_STATIC_DRAW);
glEnableVertexAttribArray(attrib_vertices_);
glVertexAttribPointer(attrib_vertices_, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
//Bind color buffer
glBindBuffer(GL_ARRAY_BUFFER, color_buffers_);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * num_parts * 4,
part_colors, GL_STATIC_DRAW);
glEnableVertexAttribArray(attrib_colors_);
glVertexAttribPointer(attrib_colors_, 4, GL_FLOAT, GL_FALSE, 0, nullptr);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glDrawArrays(GL_POINTS, 0, 3 * num_parts);
glDisable(GL_BLEND);
glUseProgram(0);
}
<|endoftext|> |
<commit_before>#include "vector.hpp"
#include <viennacl/ocl/context.hpp>
#include <viennacl/ocl/device.hpp>
#include <viennacl/ocl/platform.hpp>
std::vector<vcl::ocl::device>
get_platform_devices(vcl::ocl::platform& p) {
return p.devices();
}
std::string get_device_info(vcl::ocl::device& d) {
return d.info();
}
std::string get_device_full_info(vcl::ocl::device& d) {
return d.full_info();
}
PYVCL_SUBMODULE(opencl_support)
{
PYTHON_SCOPE_SUBMODULE(opencl_support);
bp::class_<vcl::ocl::platform>("platform", bp::no_init)
.add_property("info", &vcl::ocl::platform::info)
.add_property("devices", get_platform_devices)
;
bp::to_python_converter<std::vector<vcl::ocl::platform>,
vector_to_list_converter<vcl::ocl::platform> >();
bp::def("get_platforms", vcl::ocl::get_platforms);
bp::class_<vcl::ocl::device>("device")
.add_property("name", &vcl::ocl::device::name)
.add_property("vendor", &vcl::ocl::device::vendor)
.add_property("version", &vcl::ocl::device::version)
.add_property("driver_version", &vcl::ocl::device::driver_version)
.add_property("info", get_device_info)
.add_property("full_info", get_device_full_info)
.add_property("extensions", &vcl::ocl::device::extensions)
.add_property("double_support", &vcl::ocl::device::double_support)
;
bp::to_python_converter<std::vector<vcl::ocl::device>,
vector_to_list_converter<vcl::ocl::device> >();
DISAMBIGUATE_CLASS_FUNCTION_PTR(vcl::ocl::context, void,
init, init_new_context,
());
DISAMBIGUATE_CLASS_FUNCTION_PTR(vcl::ocl::context, void,
add_device, context_add_device,
(viennacl::ocl::device const&));
DISAMBIGUATE_CLASS_FUNCTION_PTR(vcl::ocl::context, void,
switch_device, context_switch_device,
(viennacl::ocl::device const&));
DISAMBIGUATE_CLASS_FUNCTION_PTR(vcl::ocl::context, void,
platform_index, context_set_platform_index,
(vcl::vcl_size_t));
DISAMBIGUATE_CLASS_FUNCTION_PTR(vcl::ocl::context, vcl::vcl_size_t,
platform_index, context_get_platform_index,
() const);
bp::class_<vcl::ocl::context>("context")
.def("init_new_context", init_new_context)
.def("current_device", &vcl::ocl::context::current_device,
bp::return_value_policy<bp::copy_const_reference>())
.def("devices", &vcl::ocl::context::devices,
bp::return_value_policy<bp::copy_const_reference>())
.def("add_device", context_add_device)
.def("switch_active_device", context_switch_device)
.add_property("platform_index", context_get_platform_index, context_set_platform_index)
;
bp::def("get_current_context", vcl::ocl::current_context,
bp::return_value_policy<bp::copy_non_const_reference>());
bp::def("get_current_device", vcl::ocl::current_device,
bp::return_value_policy<bp::copy_const_reference>());
#ifdef VIENNACL_WITH_OPENCL
DISAMBIGUATE_FUNCTION_PTR(void,
vcl::ocl::setup_context,
setup_context_single,
(long, vcl::ocl::device const&));
bp::def("setup_context", setup_context_single);
bp::def("switch_context", vcl::ocl::switch_context);
#endif
}
<commit_msg>Add to / from int_ptr in opencl_support<commit_after>#ifdef VIENNACL_WITH_OPENCL
#include "vector.hpp"
#include <viennacl/ocl/context.hpp>
#include <viennacl/ocl/device.hpp>
#include <viennacl/ocl/platform.hpp>
vcl::vcl_size_t get_platform_ptr(vcl::ocl::platform& p) {
return (vcl::vcl_size_t) p.id();
}
vcl::vcl_size_t get_device_ptr(vcl::ocl::device& d) {
return (vcl::vcl_size_t) d.id();
}
vcl::vcl_size_t get_context_ptr(vcl::ocl::context& c) {
return (vcl::vcl_size_t) c.handle().get();
}
template<class VCLType, class PtrType>
vcl::tools::shared_ptr<VCLType>
vcl_object_from_int_ptr(vcl::vcl_size_t int_ptr) {
VCLType *p = new VCLType((PtrType)int_ptr);
return vcl::tools::shared_ptr<VCLType>(p);
}
void init_vcl_context_from_int_ptr(vcl::ocl::context& c, vcl::vcl_size_t int_ptr) {
c.init((cl_context)int_ptr);
}
std::vector<vcl::ocl::device>
get_platform_devices(vcl::ocl::platform& p) {
return p.devices();
}
std::string get_device_info(vcl::ocl::device& d) {
return d.info();
}
std::string get_device_full_info(vcl::ocl::device& d) {
return d.full_info();
}
#endif
PYVCL_SUBMODULE(opencl_support)
{
#ifdef VIENNACL_WITH_OPENCL
PYTHON_SCOPE_SUBMODULE(opencl_support);
bp::class_<vcl::ocl::platform>("platform", bp::no_init)
.def("__init__", bp::make_constructor(vcl_object_from_int_ptr<vcl::ocl::platform, cl_platform_id>))
.add_property("info", &vcl::ocl::platform::info)
.add_property("devices", get_platform_devices)
.add_property("int_ptr", get_platform_ptr)
;
bp::to_python_converter<std::vector<vcl::ocl::platform>,
vector_to_list_converter<vcl::ocl::platform> >();
bp::def("get_platforms", vcl::ocl::get_platforms);
bp::class_<vcl::ocl::device, vcl::tools::shared_ptr<vcl::ocl::device> >
("device")
.def("__init__", bp::make_constructor(vcl_object_from_int_ptr<vcl::ocl::device, cl_device_id>))
.add_property("name", &vcl::ocl::device::name)
.add_property("vendor", &vcl::ocl::device::vendor)
.add_property("version", &vcl::ocl::device::version)
.add_property("driver_version", &vcl::ocl::device::driver_version)
.add_property("info", get_device_info)
.add_property("full_info", get_device_full_info)
.add_property("extensions", &vcl::ocl::device::extensions)
.add_property("double_support", &vcl::ocl::device::double_support)
.add_property("int_ptr", get_device_ptr)
;
bp::to_python_converter<std::vector<vcl::ocl::device>,
vector_to_list_converter<vcl::ocl::device> >();
DISAMBIGUATE_CLASS_FUNCTION_PTR(vcl::ocl::context, void,
init, init_new_context,
());
DISAMBIGUATE_CLASS_FUNCTION_PTR(vcl::ocl::context, void,
add_device, context_add_device,
(viennacl::ocl::device const&));
DISAMBIGUATE_CLASS_FUNCTION_PTR(vcl::ocl::context, void,
switch_device, context_switch_device,
(viennacl::ocl::device const&));
DISAMBIGUATE_CLASS_FUNCTION_PTR(vcl::ocl::context, void,
platform_index, context_set_platform_index,
(vcl::vcl_size_t));
DISAMBIGUATE_CLASS_FUNCTION_PTR(vcl::ocl::context, vcl::vcl_size_t,
platform_index, context_get_platform_index,
() const);
bp::class_<vcl::ocl::context>("context")
.def("init_new_context", init_new_context)
.def("init_from_int_ptr", init_vcl_context_from_int_ptr)
.def("current_device", &vcl::ocl::context::current_device,
bp::return_value_policy<bp::copy_const_reference>())
.def("devices", &vcl::ocl::context::devices,
bp::return_value_policy<bp::copy_const_reference>())
.def("add_device", context_add_device)
.def("switch_active_device", context_switch_device)
.add_property("platform_index", context_get_platform_index, context_set_platform_index)
.add_property("int_ptr", get_context_ptr)
;
bp::def("get_current_context", vcl::ocl::current_context,
bp::return_value_policy<bp::copy_non_const_reference>());
bp::def("get_current_device", vcl::ocl::current_device,
bp::return_value_policy<bp::copy_const_reference>());
DISAMBIGUATE_FUNCTION_PTR(void,
vcl::ocl::setup_context,
setup_context_single,
(long, vcl::ocl::device const&));
bp::def("setup_context", setup_context_single);
bp::def("switch_context", vcl::ocl::switch_context);
#endif
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2013 The Communi Project
*
* 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.
*
* 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.
*/
#include "highlighterplugin.h"
#include "treewidget.h"
#include "treeitem.h"
#include <IrcConnection>
#include <IrcMessage>
#include <IrcBuffer>
#include <QTimer>
#include <QEvent>
HighlighterPlugin::HighlighterPlugin(QObject* parent) : QObject(parent)
{
d.blocked = false;
d.tree = 0;
d.shortcut = 0;
}
void HighlighterPlugin::initialize(TreeWidget* tree)
{
d.tree = tree;
connect(tree, SIGNAL(bufferAdded(IrcBuffer*)), this, SLOT(onBufferAdded(IrcBuffer*)));
connect(tree, SIGNAL(bufferRemoved(IrcBuffer*)), this, SLOT(onBufferRemoved(IrcBuffer*)));
connect(tree, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),
this, SLOT(onCurrentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)));
d.shortcut = new QShortcut(tree);
d.shortcut->setKey(QKeySequence(tr("Ctrl+R")));
connect(d.shortcut, SIGNAL(activated()), this, SLOT(resetItems()));
}
bool HighlighterPlugin::eventFilter(QObject *object, QEvent* event)
{
Q_UNUSED(object);
switch (event->type()) {
case QEvent::WindowActivate:
delayedReset(d.tree->currentItem());
break;
case QEvent::WindowBlocked:
d.blocked = true;
break;
case QEvent::WindowUnblocked:
d.blocked = false;
delayedReset(d.tree->currentItem());
break;
default:
break;
}
return false;
}
void HighlighterPlugin::onBufferAdded(IrcBuffer* buffer)
{
connect(buffer, SIGNAL(messageReceived(IrcMessage*)), this, SLOT(onMessageReceived(IrcMessage*)));
}
void HighlighterPlugin::onBufferRemoved(IrcBuffer* buffer)
{
disconnect(buffer, SIGNAL(messageReceived(IrcMessage*)), this, SLOT(onMessageReceived(IrcMessage*)));
}
void HighlighterPlugin::onMessageReceived(IrcMessage* message)
{
IrcBuffer* buffer = qobject_cast<IrcBuffer*>(sender());
TreeItem* item = d.tree->bufferItem(buffer);
if (item && item != d.tree->currentItem()) {
if (message->type() == IrcMessage::Private || message->type() == IrcMessage::Notice) {
item->setBadge(item->badge() + 1);
if (message->property("content").toString().contains(message->connection()->nickName()))
item->setHighlighted(true);
}
}
}
void HighlighterPlugin::onCurrentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous)
{
if (!d.blocked) {
if (previous)
static_cast<TreeItem*>(previous)->reset();
}
if (current)
delayedReset(current);
}
void HighlighterPlugin::delayedReset(QTreeWidgetItem* item)
{
if (item)
QTimer::singleShot(500, static_cast<TreeItem*>(item), SLOT(reset()));
}
void HighlighterPlugin::resetItems()
{
QTreeWidgetItemIterator it(d.tree);
while (*it) {
static_cast<TreeItem*>(*it)->reset();
++it;
}
}
#if QT_VERSION < 0x050000
Q_EXPORT_STATIC_PLUGIN(HighlighterPlugin)
#endif
<commit_msg>Highlight messages<commit_after>/*
* Copyright (C) 2008-2013 The Communi Project
*
* 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.
*
* 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.
*/
#include "highlighterplugin.h"
#include "textdocument.h"
#include "treewidget.h"
#include "treeitem.h"
#include <IrcConnection>
#include <IrcMessage>
#include <IrcBuffer>
#include <QTimer>
#include <QEvent>
HighlighterPlugin::HighlighterPlugin(QObject* parent) : QObject(parent)
{
d.blocked = false;
d.tree = 0;
d.shortcut = 0;
}
void HighlighterPlugin::initialize(TreeWidget* tree)
{
d.tree = tree;
connect(tree, SIGNAL(bufferAdded(IrcBuffer*)), this, SLOT(onBufferAdded(IrcBuffer*)));
connect(tree, SIGNAL(bufferRemoved(IrcBuffer*)), this, SLOT(onBufferRemoved(IrcBuffer*)));
connect(tree, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),
this, SLOT(onCurrentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)));
d.shortcut = new QShortcut(tree);
d.shortcut->setKey(QKeySequence(tr("Ctrl+R")));
connect(d.shortcut, SIGNAL(activated()), this, SLOT(resetItems()));
}
bool HighlighterPlugin::eventFilter(QObject *object, QEvent* event)
{
Q_UNUSED(object);
switch (event->type()) {
case QEvent::WindowActivate:
delayedReset(d.tree->currentItem());
break;
case QEvent::WindowBlocked:
d.blocked = true;
break;
case QEvent::WindowUnblocked:
d.blocked = false;
delayedReset(d.tree->currentItem());
break;
default:
break;
}
return false;
}
void HighlighterPlugin::onBufferAdded(IrcBuffer* buffer)
{
connect(buffer, SIGNAL(messageReceived(IrcMessage*)), this, SLOT(onMessageReceived(IrcMessage*)));
}
void HighlighterPlugin::onBufferRemoved(IrcBuffer* buffer)
{
disconnect(buffer, SIGNAL(messageReceived(IrcMessage*)), this, SLOT(onMessageReceived(IrcMessage*)));
}
void HighlighterPlugin::onMessageReceived(IrcMessage* message)
{
if (message->type() == IrcMessage::Private || message->type() == IrcMessage::Notice) {
IrcBuffer* buffer = qobject_cast<IrcBuffer*>(sender());
const bool highlight = message->property("content").toString().contains(message->connection()->nickName());
TreeItem* item = d.tree->bufferItem(buffer);
if (item && item != d.tree->currentItem()) {
item->setBadge(item->badge() + 1);
if (highlight)
item->setHighlighted(true);
}
if (highlight) {
TextDocument* document = buffer->property("document").value<TextDocument*>();
document->addHighlight(document->totalCount() - 2); // TODO: -2??
}
}
}
void HighlighterPlugin::onCurrentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous)
{
if (!d.blocked) {
if (previous)
static_cast<TreeItem*>(previous)->reset();
}
if (current)
delayedReset(current);
}
void HighlighterPlugin::delayedReset(QTreeWidgetItem* item)
{
if (item)
QTimer::singleShot(500, static_cast<TreeItem*>(item), SLOT(reset()));
}
void HighlighterPlugin::resetItems()
{
QTreeWidgetItemIterator it(d.tree);
while (*it) {
static_cast<TreeItem*>(*it)->reset();
++it;
}
}
#if QT_VERSION < 0x050000
Q_EXPORT_STATIC_PLUGIN(HighlighterPlugin)
#endif
<|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 Qt Creator.
**
** 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.
**
****************************************************************************/
#include "qmldesignerplugin.h"
#include "exception.h"
#include "qmldesignerconstants.h"
#include "designmodewidget.h"
#include "settingspage.h"
#include "designmodecontext.h"
#include <qmljseditor/qmljseditorconstants.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/designmode.h>
#include <coreplugin/icore.h>
#include <coreplugin/modemanager.h>
#include <extensionsystem/pluginspec.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <utils/hostosinfo.h>
#include <QAction>
#include <QCoreApplication>
#include <qplugin.h>
#include <QDebug>
#include <QProcessEnvironment>
namespace QmlDesigner {
QmlDesignerPlugin *QmlDesignerPlugin::m_instance = 0;
static bool isQmlFile(Core::IEditor *editor)
{
return editor && editor->id() == QmlJSEditor::Constants::C_QMLJSEDITOR_ID;
}
static bool isInDesignerMode()
{
return Core::ModeManager::currentMode() == Core::DesignMode::instance();
}
bool shouldAssertInException()
{
QProcessEnvironment processEnvironment = QProcessEnvironment::systemEnvironment();
return !processEnvironment.value("QMLDESIGNER_ASSERT_ON_EXCEPTION").isEmpty();
}
QmlDesignerPlugin::QmlDesignerPlugin() :
m_isActive(false)
{
// Exceptions should never ever assert: they are handled in a number of
// places where it is actually VALID AND EXPECTED BEHAVIOUR to get an
// exception.
// If you still want to see exactly where the exception originally
// occurred, then you have various ways to do this:
// 1. set a breakpoint on the constructor of the exception
// 2. in gdb: "catch throw" or "catch throw Exception"
// 3. set a breakpoint on __raise_exception()
// And with gdb, you can even do this from your ~/.gdbinit file.
// DnD is not working with gdb so this is still needed to get a good stacktrace
Exception::setShouldAssert(shouldAssertInException());
}
QmlDesignerPlugin::~QmlDesignerPlugin()
{
Core::ICore::removeContextObject(m_context);
m_context = 0;
m_instance = 0;
}
////////////////////////////////////////////////////
//
// INHERITED FROM ExtensionSystem::Plugin
//
////////////////////////////////////////////////////
bool QmlDesignerPlugin::initialize(const QStringList & /*arguments*/, QString *errorMessage/* = 0*/) // =0;
{
const Core::Context switchContext(QmlDesigner::Constants::C_QMLDESIGNER,
QmlJSEditor::Constants::C_QMLJSEDITOR_ID);
QAction *switchAction = new QAction(tr("Switch Text/Design"), this);
Core::Command *command = Core::ActionManager::registerAction(
switchAction, QmlDesigner::Constants::SWITCH_TEXT_DESIGN, switchContext);
command->setDefaultKeySequence(QKeySequence(Qt::Key_F4));
m_instance = this;
const QString pluginPath = Utils::HostOsInfo::isMacHost()
? QString(QCoreApplication::applicationDirPath() + "/../PlugIns/QmlDesigner")
: QString(QCoreApplication::applicationDirPath() + "/../"
+ QLatin1String(IDE_LIBRARY_BASENAME) + "/qtcreator/qmldesigner");
m_pluginManager.setPluginPaths(QStringList() << pluginPath);
createDesignModeWidget();
connect(switchAction, SIGNAL(triggered()), this, SLOT(switchTextDesign()));
addAutoReleasedObject(new Internal::SettingsPage);
m_settings.fromSettings(Core::ICore::settings());
errorMessage->clear();
return true;
}
void QmlDesignerPlugin::createDesignModeWidget()
{
m_mainWidget = new Internal::DesignModeWidget;
m_context = new Internal::DesignModeContext(m_mainWidget);
Core::ICore::addContextObject(m_context);
Core::Context qmlDesignerMainContext(Constants::C_QMLDESIGNER);
Core::Context qmlDesignerFormEditorContext(Constants::C_QMLFORMEDITOR);
Core::Context qmlDesignerNavigatorContext(Constants::C_QMLNAVIGATOR);
m_context->context().add(qmlDesignerMainContext);
m_context->context().add(qmlDesignerFormEditorContext);
m_context->context().add(qmlDesignerNavigatorContext);
m_context->context().add(ProjectExplorer::Constants::LANG_QMLJS);
m_shortCutManager.registerActions(qmlDesignerMainContext, qmlDesignerFormEditorContext, qmlDesignerNavigatorContext);
connect(Core::ICore::editorManager(),
SIGNAL(currentEditorChanged(Core::IEditor*)),
this,
SLOT(onCurrentEditorChanged(Core::IEditor*)));
connect(Core::ICore::editorManager(),
SIGNAL(editorsClosed(QList<Core::IEditor*>)),
this,
SLOT(onTextEditorsClosed(QList<Core::IEditor*>)));
// connect(Core::ICore::editorManager(), SIGNAL(currentEditorChanged(Core::IEditor*)),
// &m_documentManager, SLOT(currentTextEditorChanged(Core::IEditor*)));
// connect(Core::ICore::instance(), SIGNAL(contextChanged(Core::IContext*,Core::Context)),
// this, SLOT(contextChanged(Core::IContext*,Core::Context)));
connect(Core::ModeManager::instance(),
SIGNAL(currentModeChanged(Core::IMode*,Core::IMode*)),
SLOT(onCurrentModeChanged(Core::IMode*,Core::IMode*)));
}
void QmlDesignerPlugin::showDesigner()
{
Q_ASSERT(!m_documentManager.hasCurrentDesignDocument());
m_shortCutManager.disconnectUndoActions(currentDesignDocument());
m_documentManager.setCurrentDesignDocument(Core::EditorManager::currentEditor());
m_shortCutManager.connectUndoActions(currentDesignDocument());
m_mainWidget->initialize();
if (m_documentManager.hasCurrentDesignDocument()) {
activateAutoSynchronization();
m_shortCutManager.updateActions(currentDesignDocument()->textEditor());
m_viewManager.pushFileOnCrumbleBar(m_documentManager.currentDesignDocument()->fileName());
}
m_shortCutManager.updateUndoActions(currentDesignDocument());
}
void QmlDesignerPlugin::hideDesigner()
{
if (currentDesignDocument()->currentModel()
&& !currentDesignDocument()->hasQmlSyntaxErrors())
jumpTextCursorToSelectedModelNode();
if (m_documentManager.hasCurrentDesignDocument()) {
deactivateAutoSynchronization();
m_mainWidget->saveSettings();
}
m_shortCutManager.disconnectUndoActions(currentDesignDocument());
m_documentManager.setCurrentDesignDocument(0);
m_shortCutManager.updateUndoActions(0);
}
void QmlDesignerPlugin::changeEditor()
{
if (m_documentManager.hasCurrentDesignDocument()) {
deactivateAutoSynchronization();
m_mainWidget->saveSettings();
}
m_shortCutManager.disconnectUndoActions(currentDesignDocument());
m_documentManager.setCurrentDesignDocument(Core::EditorManager::currentEditor());
m_mainWidget->initialize();
m_shortCutManager.connectUndoActions(currentDesignDocument());
if (m_documentManager.hasCurrentDesignDocument()) {
activateAutoSynchronization();
m_viewManager.pushFileOnCrumbleBar(m_documentManager.currentDesignDocument()->fileName());
}
m_shortCutManager.updateUndoActions(currentDesignDocument());
}
void QmlDesignerPlugin::jumpTextCursorToSelectedModelNode()
{
// visual editor -> text editor
ModelNode selectedNode;
if (!currentDesignDocument()->rewriterView()->selectedModelNodes().isEmpty())
selectedNode = currentDesignDocument()->rewriterView()->selectedModelNodes().first();
if (selectedNode.isValid()) {
const int nodeOffset = currentDesignDocument()->rewriterView()->nodeOffset(selectedNode);
if (nodeOffset > 0) {
const ModelNode currentSelectedNode
= currentDesignDocument()->rewriterView()->nodeAtTextCursorPosition(currentDesignDocument()->plainTextEdit()->textCursor().position());
if (currentSelectedNode != selectedNode) {
int line, column;
currentDesignDocument()->textEditor()->convertPosition(nodeOffset, &line, &column);
currentDesignDocument()->textEditor()->gotoLine(line, column);
}
}
}
}
void QmlDesignerPlugin::selectModelNodeUnderTextCursor()
{
const int cursorPos = currentDesignDocument()->plainTextEdit()->textCursor().position();
ModelNode node = currentDesignDocument()->rewriterView()->nodeAtTextCursorPosition(cursorPos);
if (currentDesignDocument()->rewriterView() && node.isValid()) {
currentDesignDocument()->rewriterView()->setSelectedModelNodes(QList<ModelNode>() << node);
}
}
void QmlDesignerPlugin::activateAutoSynchronization()
{
// text editor -> visual editor
if (!currentDesignDocument()->isDocumentLoaded()) {
currentDesignDocument()->loadDocument(currentDesignDocument()->plainTextEdit());
}
currentDesignDocument()->attachRewriterToModel();
resetModelSelection();
viewManager().attachComponentView();
viewManager().attachViewsExceptRewriterAndComponetView();
QList<RewriterView::Error> errors = currentDesignDocument()->qmlSyntaxErrors();
if (errors.isEmpty()) {
selectModelNodeUnderTextCursor();
m_mainWidget->enableWidgets();
m_mainWidget->setupNavigatorHistory(currentDesignDocument()->textEditor());
} else {
m_mainWidget->disableWidgets();
m_mainWidget->showErrorMessage(errors);
}
currentDesignDocument()->updateSubcomponentManager();
connect(currentDesignDocument()->rewriterView(),
SIGNAL(errorsChanged(QList<RewriterView::Error>)),
m_mainWidget,
SLOT(updateErrorStatus(QList<RewriterView::Error>)));
}
void QmlDesignerPlugin::deactivateAutoSynchronization()
{
viewManager().detachViewsExceptRewriterAndComponetView();
viewManager().detachComponentView();
viewManager().detachRewriterView();
documentManager().currentDesignDocument()->resetToDocumentModel();
disconnect(currentDesignDocument()->rewriterView(),
SIGNAL(errorsChanged(QList<RewriterView::Error>)),
m_mainWidget,
SLOT(updateErrorStatus(QList<RewriterView::Error>)));
}
void QmlDesignerPlugin::resetModelSelection()
{
if (currentDesignDocument()->rewriterView() && currentDesignDocument()->currentModel())
currentDesignDocument()->rewriterView()->setSelectedModelNodes(QList<ModelNode>());
}
void QmlDesignerPlugin::onCurrentEditorChanged(Core::IEditor *editor)
{
if (editor
&& editor->id() == QmlJSEditor::Constants::C_QMLJSEDITOR_ID
&& isInDesignerMode())
{
m_shortCutManager.updateActions(editor);
changeEditor();
}
}
static bool isDesignerMode(Core::IMode *mode)
{
return mode == Core::DesignMode::instance();
}
void QmlDesignerPlugin::onCurrentModeChanged(Core::IMode *newMode, Core::IMode *oldMode)
{
if (!Core::EditorManager::currentEditor())
return;
if (Core::EditorManager::currentEditor()
&& Core::EditorManager::currentEditor()->id() != QmlJSEditor::Constants::C_QMLJSEDITOR_ID)
return;
if ((currentDesignDocument()
&& Core::EditorManager::currentEditor() == currentDesignDocument()->editor())
&& isDesignerMode(newMode))
return;
if (!isDesignerMode(newMode) && isDesignerMode(oldMode))
hideDesigner();
else if (Core::EditorManager::currentEditor()
&& isDesignerMode(newMode)
&& isQmlFile(Core::EditorManager::currentEditor()))
showDesigner();
else if (currentDesignDocument())
hideDesigner();
}
DesignDocument *QmlDesignerPlugin::currentDesignDocument() const
{
return m_documentManager.currentDesignDocument();
}
Internal::DesignModeWidget *QmlDesignerPlugin::mainWidget() const
{
return m_mainWidget;
}
void QmlDesignerPlugin::onTextEditorsClosed(QList<Core::IEditor*> editors)
{
if (m_documentManager.hasCurrentDesignDocument()
&& editors.contains(m_documentManager.currentDesignDocument()->textEditor()))
hideDesigner();
m_documentManager.removeEditors(editors);
}
void QmlDesignerPlugin::extensionsInitialized()
{
QStringList mimeTypes;
mimeTypes.append("application/x-qml");
Core::DesignMode::instance()->registerDesignWidget(m_mainWidget, mimeTypes, m_context->context());
connect(Core::DesignMode::instance(),
SIGNAL(actionsUpdated(Core::IEditor*)),
&m_shortCutManager,
SLOT(updateActions(Core::IEditor*)));
}
QmlDesignerPlugin *QmlDesignerPlugin::instance()
{
return m_instance;
}
DocumentManager &QmlDesignerPlugin::documentManager()
{
return m_documentManager;
}
const DocumentManager &QmlDesignerPlugin::documentManager() const
{
return m_documentManager;
}
ViewManager &QmlDesignerPlugin::viewManager()
{
return m_viewManager;
}
const ViewManager &QmlDesignerPlugin::viewManager() const
{
return m_viewManager;
}
void QmlDesignerPlugin::switchTextDesign()
{
if (Core::ModeManager::currentMode()->id() == Core::Constants::MODE_EDIT) {
Core::IEditor *editor = Core::EditorManager::currentEditor();
if (editor->id() == QmlJSEditor::Constants::C_QMLJSEDITOR_ID)
Core::ModeManager::activateMode(Core::Constants::MODE_DESIGN);
} else if (Core::ModeManager::currentMode()->id() == Core::Constants::MODE_DESIGN) {
Core::ModeManager::activateMode(Core::Constants::MODE_EDIT);
}
}
DesignerSettings QmlDesignerPlugin::settings()
{
m_settings.fromSettings(Core::ICore::settings());
return m_settings;
}
void QmlDesignerPlugin::setSettings(const DesignerSettings &s)
{
if (s != m_settings) {
m_settings = s;
m_settings.toSettings(Core::ICore::settings());
}
}
}
Q_EXPORT_PLUGIN(QmlDesigner::QmlDesignerPlugin)
<commit_msg>QmlDesigner: adding check for null pointer<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** 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.
**
****************************************************************************/
#include "qmldesignerplugin.h"
#include "exception.h"
#include "qmldesignerconstants.h"
#include "designmodewidget.h"
#include "settingspage.h"
#include "designmodecontext.h"
#include <qmljseditor/qmljseditorconstants.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/designmode.h>
#include <coreplugin/icore.h>
#include <coreplugin/modemanager.h>
#include <extensionsystem/pluginspec.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <utils/hostosinfo.h>
#include <QAction>
#include <QCoreApplication>
#include <qplugin.h>
#include <QDebug>
#include <QProcessEnvironment>
namespace QmlDesigner {
QmlDesignerPlugin *QmlDesignerPlugin::m_instance = 0;
static bool isQmlFile(Core::IEditor *editor)
{
return editor && editor->id() == QmlJSEditor::Constants::C_QMLJSEDITOR_ID;
}
static bool isInDesignerMode()
{
return Core::ModeManager::currentMode() == Core::DesignMode::instance();
}
bool shouldAssertInException()
{
QProcessEnvironment processEnvironment = QProcessEnvironment::systemEnvironment();
return !processEnvironment.value("QMLDESIGNER_ASSERT_ON_EXCEPTION").isEmpty();
}
QmlDesignerPlugin::QmlDesignerPlugin() :
m_isActive(false)
{
// Exceptions should never ever assert: they are handled in a number of
// places where it is actually VALID AND EXPECTED BEHAVIOUR to get an
// exception.
// If you still want to see exactly where the exception originally
// occurred, then you have various ways to do this:
// 1. set a breakpoint on the constructor of the exception
// 2. in gdb: "catch throw" or "catch throw Exception"
// 3. set a breakpoint on __raise_exception()
// And with gdb, you can even do this from your ~/.gdbinit file.
// DnD is not working with gdb so this is still needed to get a good stacktrace
Exception::setShouldAssert(shouldAssertInException());
}
QmlDesignerPlugin::~QmlDesignerPlugin()
{
Core::ICore::removeContextObject(m_context);
m_context = 0;
m_instance = 0;
}
////////////////////////////////////////////////////
//
// INHERITED FROM ExtensionSystem::Plugin
//
////////////////////////////////////////////////////
bool QmlDesignerPlugin::initialize(const QStringList & /*arguments*/, QString *errorMessage/* = 0*/) // =0;
{
const Core::Context switchContext(QmlDesigner::Constants::C_QMLDESIGNER,
QmlJSEditor::Constants::C_QMLJSEDITOR_ID);
QAction *switchAction = new QAction(tr("Switch Text/Design"), this);
Core::Command *command = Core::ActionManager::registerAction(
switchAction, QmlDesigner::Constants::SWITCH_TEXT_DESIGN, switchContext);
command->setDefaultKeySequence(QKeySequence(Qt::Key_F4));
m_instance = this;
const QString pluginPath = Utils::HostOsInfo::isMacHost()
? QString(QCoreApplication::applicationDirPath() + "/../PlugIns/QmlDesigner")
: QString(QCoreApplication::applicationDirPath() + "/../"
+ QLatin1String(IDE_LIBRARY_BASENAME) + "/qtcreator/qmldesigner");
m_pluginManager.setPluginPaths(QStringList() << pluginPath);
createDesignModeWidget();
connect(switchAction, SIGNAL(triggered()), this, SLOT(switchTextDesign()));
addAutoReleasedObject(new Internal::SettingsPage);
m_settings.fromSettings(Core::ICore::settings());
errorMessage->clear();
return true;
}
void QmlDesignerPlugin::createDesignModeWidget()
{
m_mainWidget = new Internal::DesignModeWidget;
m_context = new Internal::DesignModeContext(m_mainWidget);
Core::ICore::addContextObject(m_context);
Core::Context qmlDesignerMainContext(Constants::C_QMLDESIGNER);
Core::Context qmlDesignerFormEditorContext(Constants::C_QMLFORMEDITOR);
Core::Context qmlDesignerNavigatorContext(Constants::C_QMLNAVIGATOR);
m_context->context().add(qmlDesignerMainContext);
m_context->context().add(qmlDesignerFormEditorContext);
m_context->context().add(qmlDesignerNavigatorContext);
m_context->context().add(ProjectExplorer::Constants::LANG_QMLJS);
m_shortCutManager.registerActions(qmlDesignerMainContext, qmlDesignerFormEditorContext, qmlDesignerNavigatorContext);
connect(Core::ICore::editorManager(),
SIGNAL(currentEditorChanged(Core::IEditor*)),
this,
SLOT(onCurrentEditorChanged(Core::IEditor*)));
connect(Core::ICore::editorManager(),
SIGNAL(editorsClosed(QList<Core::IEditor*>)),
this,
SLOT(onTextEditorsClosed(QList<Core::IEditor*>)));
// connect(Core::ICore::editorManager(), SIGNAL(currentEditorChanged(Core::IEditor*)),
// &m_documentManager, SLOT(currentTextEditorChanged(Core::IEditor*)));
// connect(Core::ICore::instance(), SIGNAL(contextChanged(Core::IContext*,Core::Context)),
// this, SLOT(contextChanged(Core::IContext*,Core::Context)));
connect(Core::ModeManager::instance(),
SIGNAL(currentModeChanged(Core::IMode*,Core::IMode*)),
SLOT(onCurrentModeChanged(Core::IMode*,Core::IMode*)));
}
void QmlDesignerPlugin::showDesigner()
{
Q_ASSERT(!m_documentManager.hasCurrentDesignDocument());
m_shortCutManager.disconnectUndoActions(currentDesignDocument());
m_documentManager.setCurrentDesignDocument(Core::EditorManager::currentEditor());
m_shortCutManager.connectUndoActions(currentDesignDocument());
m_mainWidget->initialize();
if (m_documentManager.hasCurrentDesignDocument()) {
activateAutoSynchronization();
m_shortCutManager.updateActions(currentDesignDocument()->textEditor());
m_viewManager.pushFileOnCrumbleBar(m_documentManager.currentDesignDocument()->fileName());
}
m_shortCutManager.updateUndoActions(currentDesignDocument());
}
void QmlDesignerPlugin::hideDesigner()
{
if (currentDesignDocument()
&& currentDesignDocument()->currentModel()
&& !currentDesignDocument()->hasQmlSyntaxErrors())
jumpTextCursorToSelectedModelNode();
if (m_documentManager.hasCurrentDesignDocument()) {
deactivateAutoSynchronization();
m_mainWidget->saveSettings();
}
m_shortCutManager.disconnectUndoActions(currentDesignDocument());
m_documentManager.setCurrentDesignDocument(0);
m_shortCutManager.updateUndoActions(0);
}
void QmlDesignerPlugin::changeEditor()
{
if (m_documentManager.hasCurrentDesignDocument()) {
deactivateAutoSynchronization();
m_mainWidget->saveSettings();
}
m_shortCutManager.disconnectUndoActions(currentDesignDocument());
m_documentManager.setCurrentDesignDocument(Core::EditorManager::currentEditor());
m_mainWidget->initialize();
m_shortCutManager.connectUndoActions(currentDesignDocument());
if (m_documentManager.hasCurrentDesignDocument()) {
activateAutoSynchronization();
m_viewManager.pushFileOnCrumbleBar(m_documentManager.currentDesignDocument()->fileName());
}
m_shortCutManager.updateUndoActions(currentDesignDocument());
}
void QmlDesignerPlugin::jumpTextCursorToSelectedModelNode()
{
// visual editor -> text editor
ModelNode selectedNode;
if (!currentDesignDocument()->rewriterView()->selectedModelNodes().isEmpty())
selectedNode = currentDesignDocument()->rewriterView()->selectedModelNodes().first();
if (selectedNode.isValid()) {
const int nodeOffset = currentDesignDocument()->rewriterView()->nodeOffset(selectedNode);
if (nodeOffset > 0) {
const ModelNode currentSelectedNode
= currentDesignDocument()->rewriterView()->nodeAtTextCursorPosition(currentDesignDocument()->plainTextEdit()->textCursor().position());
if (currentSelectedNode != selectedNode) {
int line, column;
currentDesignDocument()->textEditor()->convertPosition(nodeOffset, &line, &column);
currentDesignDocument()->textEditor()->gotoLine(line, column);
}
}
}
}
void QmlDesignerPlugin::selectModelNodeUnderTextCursor()
{
const int cursorPos = currentDesignDocument()->plainTextEdit()->textCursor().position();
ModelNode node = currentDesignDocument()->rewriterView()->nodeAtTextCursorPosition(cursorPos);
if (currentDesignDocument()->rewriterView() && node.isValid()) {
currentDesignDocument()->rewriterView()->setSelectedModelNodes(QList<ModelNode>() << node);
}
}
void QmlDesignerPlugin::activateAutoSynchronization()
{
// text editor -> visual editor
if (!currentDesignDocument()->isDocumentLoaded()) {
currentDesignDocument()->loadDocument(currentDesignDocument()->plainTextEdit());
}
currentDesignDocument()->attachRewriterToModel();
resetModelSelection();
viewManager().attachComponentView();
viewManager().attachViewsExceptRewriterAndComponetView();
QList<RewriterView::Error> errors = currentDesignDocument()->qmlSyntaxErrors();
if (errors.isEmpty()) {
selectModelNodeUnderTextCursor();
m_mainWidget->enableWidgets();
m_mainWidget->setupNavigatorHistory(currentDesignDocument()->textEditor());
} else {
m_mainWidget->disableWidgets();
m_mainWidget->showErrorMessage(errors);
}
currentDesignDocument()->updateSubcomponentManager();
connect(currentDesignDocument()->rewriterView(),
SIGNAL(errorsChanged(QList<RewriterView::Error>)),
m_mainWidget,
SLOT(updateErrorStatus(QList<RewriterView::Error>)));
}
void QmlDesignerPlugin::deactivateAutoSynchronization()
{
viewManager().detachViewsExceptRewriterAndComponetView();
viewManager().detachComponentView();
viewManager().detachRewriterView();
documentManager().currentDesignDocument()->resetToDocumentModel();
disconnect(currentDesignDocument()->rewriterView(),
SIGNAL(errorsChanged(QList<RewriterView::Error>)),
m_mainWidget,
SLOT(updateErrorStatus(QList<RewriterView::Error>)));
}
void QmlDesignerPlugin::resetModelSelection()
{
if (currentDesignDocument()->rewriterView() && currentDesignDocument()->currentModel())
currentDesignDocument()->rewriterView()->setSelectedModelNodes(QList<ModelNode>());
}
void QmlDesignerPlugin::onCurrentEditorChanged(Core::IEditor *editor)
{
if (editor
&& editor->id() == QmlJSEditor::Constants::C_QMLJSEDITOR_ID
&& isInDesignerMode())
{
m_shortCutManager.updateActions(editor);
changeEditor();
}
}
static bool isDesignerMode(Core::IMode *mode)
{
return mode == Core::DesignMode::instance();
}
void QmlDesignerPlugin::onCurrentModeChanged(Core::IMode *newMode, Core::IMode *oldMode)
{
if (!Core::EditorManager::currentEditor())
return;
if (Core::EditorManager::currentEditor()
&& Core::EditorManager::currentEditor()->id() != QmlJSEditor::Constants::C_QMLJSEDITOR_ID)
return;
if ((currentDesignDocument()
&& Core::EditorManager::currentEditor() == currentDesignDocument()->editor())
&& isDesignerMode(newMode))
return;
if (!isDesignerMode(newMode) && isDesignerMode(oldMode))
hideDesigner();
else if (Core::EditorManager::currentEditor()
&& isDesignerMode(newMode)
&& isQmlFile(Core::EditorManager::currentEditor()))
showDesigner();
else if (currentDesignDocument())
hideDesigner();
}
DesignDocument *QmlDesignerPlugin::currentDesignDocument() const
{
return m_documentManager.currentDesignDocument();
}
Internal::DesignModeWidget *QmlDesignerPlugin::mainWidget() const
{
return m_mainWidget;
}
void QmlDesignerPlugin::onTextEditorsClosed(QList<Core::IEditor*> editors)
{
if (m_documentManager.hasCurrentDesignDocument()
&& editors.contains(m_documentManager.currentDesignDocument()->textEditor()))
hideDesigner();
m_documentManager.removeEditors(editors);
}
void QmlDesignerPlugin::extensionsInitialized()
{
QStringList mimeTypes;
mimeTypes.append("application/x-qml");
Core::DesignMode::instance()->registerDesignWidget(m_mainWidget, mimeTypes, m_context->context());
connect(Core::DesignMode::instance(),
SIGNAL(actionsUpdated(Core::IEditor*)),
&m_shortCutManager,
SLOT(updateActions(Core::IEditor*)));
}
QmlDesignerPlugin *QmlDesignerPlugin::instance()
{
return m_instance;
}
DocumentManager &QmlDesignerPlugin::documentManager()
{
return m_documentManager;
}
const DocumentManager &QmlDesignerPlugin::documentManager() const
{
return m_documentManager;
}
ViewManager &QmlDesignerPlugin::viewManager()
{
return m_viewManager;
}
const ViewManager &QmlDesignerPlugin::viewManager() const
{
return m_viewManager;
}
void QmlDesignerPlugin::switchTextDesign()
{
if (Core::ModeManager::currentMode()->id() == Core::Constants::MODE_EDIT) {
Core::IEditor *editor = Core::EditorManager::currentEditor();
if (editor->id() == QmlJSEditor::Constants::C_QMLJSEDITOR_ID)
Core::ModeManager::activateMode(Core::Constants::MODE_DESIGN);
} else if (Core::ModeManager::currentMode()->id() == Core::Constants::MODE_DESIGN) {
Core::ModeManager::activateMode(Core::Constants::MODE_EDIT);
}
}
DesignerSettings QmlDesignerPlugin::settings()
{
m_settings.fromSettings(Core::ICore::settings());
return m_settings;
}
void QmlDesignerPlugin::setSettings(const DesignerSettings &s)
{
if (s != m_settings) {
m_settings = s;
m_settings.toSettings(Core::ICore::settings());
}
}
}
Q_EXPORT_PLUGIN(QmlDesigner::QmlDesignerPlugin)
<|endoftext|> |
<commit_before>#include <plugins/symboliclog/PluginSymbolicLog.h>
namespace beliefstate {
namespace plugins {
PluginSymbolicLog::PluginSymbolicLog() {
m_ndActive = NULL;
}
PluginSymbolicLog::~PluginSymbolicLog() {
for(list<Node*>::iterator itNode = m_lstNodes.begin();
itNode != m_lstNodes.end();
itNode++) {
Node* ndCurrent = *itNode;
delete ndCurrent;
}
m_lstNodes.clear();
}
Result PluginSymbolicLog::init(int argc, char** argv) {
Result resInit = defaultResult();
// Plan node control events
this->setSubscribedToEvent("begin-context", true);
this->setSubscribedToEvent("end-context", true);
// Extra information assertion
this->setSubscribedToEvent("add-designator", true);
this->setSubscribedToEvent("add-object", true);
this->setSubscribedToEvent("add-failure", true);
this->setSubscribedToEvent("add-image-from-file", true);
this->setSubscribedToEvent("equate-designators", true);
// Information supply services
this->setOffersService("symbolic-plan-tree", true);
return resInit;
}
Result PluginSymbolicLog::deinit() {
return defaultResult();
}
Result PluginSymbolicLog::cycle() {
Result resCycle = defaultResult();
m_mtxEventsStore.lock();
resCycle.lstEvents = m_lstEvents;
m_lstEvents.clear();
m_mtxEventsStore.unlock();
return resCycle;
}
Event PluginSymbolicLog::consumeServiceEvent(ServiceEvent seServiceEvent) {
Event evReturn = defaultEvent();
if(seServiceEvent.siServiceIdentifier == SI_REQUEST) {
if(seServiceEvent.strServiceName == "symbolic-plan-tree") {
evReturn.lstNodes = m_lstNodes;
evReturn.lstDesignatorIDs = m_lstDesignatorIDs;
evReturn.lstEquations = m_lstDesignatorEquations;
evReturn.lstEquationTimes = m_lstDesignatorEquationTimes;
}
}
return evReturn;
}
void PluginSymbolicLog::consumeEvent(Event evEvent) {
//int nID = (evEvent.nContextID == -1 ? (evEvent.cdDesignator ? (int)evEvent.cdDesignator->floatValue("_id") : -1) : evEvent.nContextID);
if(evEvent.strEventName == "begin-context") {
string strName = evEvent.cdDesignator->stringValue("_name");
Node* ndNew = this->addNode(strName, evEvent.nContextID);
stringstream stsTimeStart;
stsTimeStart << this->getTimeStamp();
ndNew->metaInformation()->setValue(string("time-start"), stsTimeStart.str());
int nDetailLevel = (int)evEvent.cdDesignator->floatValue("_detail-level");
ndNew->metaInformation()->setValue(string("detail-level"), nDetailLevel);
Event evSymbolicBeginCtx = defaultEvent("symbolic-begin-context");
evSymbolicBeginCtx.lstNodes.push_back(ndNew);
this->deployEvent(evSymbolicBeginCtx);
} else if(evEvent.strEventName == "end-context") {
int nID = (int)evEvent.cdDesignator->floatValue("_id");
int nSuccess = (int)evEvent.cdDesignator->floatValue("_success");
Node *ndCurrent = this->activeNode();
if(ndCurrent) {
if(ndCurrent->id() == nID) {
stringstream sts;
sts << "Received stop context designator for ID " << nID << " (success: " << (nSuccess ? "yes" : "no") << ")";
this->info(sts.str());
ndCurrent->metaInformation()->setValue(string("success"), nSuccess);
stringstream stsTimeEnd;
stsTimeEnd << this->getTimeStamp();
ndCurrent->metaInformation()->setValue(string("time-end"), stsTimeEnd.str());
Node *ndParent = ndCurrent->parent();
this->setNodeAsActive(ndParent);
while(ndParent) {
if(ndParent->prematurelyEnded()) {
ndParent = ndParent->parent();
this->setNodeAsActive(ndParent);
} else {
this->setNodeAsActive(ndParent);
break;
}
}
Event evSymbolicEndCtx = defaultEvent("symbolic-end-context");
evSymbolicEndCtx.lstNodes.push_back(ndCurrent);
this->deployEvent(evSymbolicEndCtx);
} else {
stringstream sts;
sts << "Received stop node designator for ID " << nID << " while ID " << ndCurrent->id() << " is active.";
this->info(sts.str());
Node *ndEndedPrematurely = NULL;
Node *ndSearchTemp = ndCurrent->parent();
while(ndSearchTemp) {
if(ndSearchTemp->id() == nID) {
ndEndedPrematurely = ndSearchTemp;
ndSearchTemp = NULL;
} else {
ndSearchTemp = ndSearchTemp->parent();
}
}
if(ndEndedPrematurely) {
// Found the prematurely ended node in this branch
stringstream sts;
sts << "Marking node " << nID << " as prematurely ended.";
this->info(sts.str());
ndEndedPrematurely->setPrematurelyEnded(true);
} else {
// Didn't find the prematurely ended node in this branch
stringstream sts;
sts << "The apparently prematurely ended node " << nID << " was not found. This is probably a problem.";
this->warn(sts.str());
}
}
} else {
stringstream sts;
sts << "Received stop node designator for ID " << nID << " while in top-level.";
this->warn(sts.str());
}
} else if(evEvent.strEventName == "add-image-from-file") {
if(evEvent.cdDesignator) {
if(this->activeNode()) {
string strFilepath = evEvent.cdDesignator->stringValue("filename");
string strTopic = evEvent.cdDesignator->stringValue("origin");
if(strFilepath != "") {
this->activeNode()->addImage(strTopic, strFilepath);
stringstream sts;
sts << this->activeNode()->id();
this->info("Added image to active node (id " + sts.str() + "): '" + strFilepath + "'");
} else {
this->warn("No filename given. Will not add unnamed image to active node. The designator was:");
evEvent.cdDesignator->printDesignator();
}
} else {
this->warn("No node context available. Cannot add image from file while on top-level.");
}
}
this->warn("Adding images from file is not yet implemented!");
} else if(evEvent.strEventName == "add-failure") {
if(evEvent.cdDesignator) {
if(this->activeNode()) {
// Adding a failure to a node also means to set its success state to 'false'.
string strCondition = evEvent.cdDesignator->stringValue("condition");
stringstream stsTimeFail;
stsTimeFail << this->getTimeStamp();
this->activeNode()->addFailure(strCondition, stsTimeFail.str());
this->activeNode()->setSuccess(false);
stringstream sts;
sts << this->activeNode()->id();
this->info("Added failure to active node (id " + sts.str() + "): '" + strCondition.c_str() + "'");
} else {
this->warn("No node context available. Cannot add failure while on top-level.");
}
}
} else if(evEvent.strEventName == "add-designator") {
if(evEvent.cdDesignator) {
if(this->activeNode()) {
string strType = evEvent.cdDesignator->stringValue("type");
string strAnnotation = evEvent.cdDesignator->stringValue("annotation");
string strMemAddr = evEvent.cdDesignator->stringValue("memory-address");
CKeyValuePair *ckvpDesc = evEvent.cdDesignator->childForKey("description");
list<CKeyValuePair*> lstDescription = ckvpDesc->children();
bool bDesigExists = (this->getDesignatorID(strMemAddr) != "");
string strUniqueID = this->getUniqueDesignatorID(strMemAddr);
this->activeNode()->addDesignator(strType, lstDescription, strUniqueID, strAnnotation);
stringstream sts;
sts << this->activeNode()->id();
this->info("Added '" + strType + "' designator (addr=" + strMemAddr + ") to active context (id " + sts.str() + "): '" + strUniqueID + "'");
// desigResponse->setValue("id", strUniqueID);
// desigResponse->setValue(string("is-new"), (bDesigExists ? 0.0 : 1.0));
//bReturnvalue = true;
} else {
this->warn("No node context available. Cannot add designator while on top-level.");
}
}
} else if(evEvent.strEventName == "equate-designators") {
if(evEvent.cdDesignator) {
string strMemAddrChild = evEvent.cdDesignator->stringValue("memory-address-child");
string strMemAddrParent = evEvent.cdDesignator->stringValue("memory-address-parent");
if(strMemAddrChild != "" && strMemAddrParent != "") {
if(this->activeNode()) {
this->equateDesignators(strMemAddrChild, strMemAddrParent);
}
}
}
} else if(evEvent.strEventName == "add-object") {
if(evEvent.cdDesignator) {
CKeyValuePair *ckvpDesc = evEvent.cdDesignator->childForKey("description");
if(ckvpDesc) {
if(this->activeNode()) {
string strType = evEvent.cdDesignator->stringValue("type");
string strMemAddr = evEvent.cdDesignator->stringValue("memory-address");
bool bDesigExists = (this->getDesignatorID(strMemAddr) != "");
string strUniqueID = this->getUniqueDesignatorID(strMemAddr);
ckvpDesc->setValue("__id", strUniqueID);
this->activeNode()->addObject(ckvpDesc->children());
stringstream sts;
sts << this->activeNode()->id();
this->info("Added object (" + strUniqueID + ") to active node (id " + sts.str() + ").");
} else {
this->warn("No node context available. Cannot add object while on top-level.");
}
}
}
} else {
this->warn("Unknown event name: '" + evEvent.strEventName + "'");
}
}
Node* PluginSymbolicLog::addNode(string strName, int nContextID) {
Node *ndNew = new Node(strName);
ndNew->setID(nContextID);
if(m_ndActive == NULL) {
// Add a new top-level node
m_lstNodes.push_back(ndNew);
stringstream sts;
sts << nContextID;
this->info("Adding new top-level context with ID " + sts.str());
} else {
// Add it as a subnode to the current contextual node
m_ndActive->addSubnode(ndNew);
stringstream sts;
sts << nContextID;
this->info("Adding new sub context with ID " + sts.str());
}
this->info("The new context's name is '" + strName + "'");
this->setNodeAsActive(ndNew);
return ndNew;
}
void PluginSymbolicLog::setNodeAsActive(Node* ndActive) {
m_ndActive = ndActive;
if(m_ndActive) {
stringstream sts;
sts << m_ndActive->id();
this->info("Setting context ID " + sts.str() + " as active context");
} else {
this->info("Removed active context, returning to top-level");
}
}
Node* PluginSymbolicLog::activeNode() {
return m_ndActive;
}
string PluginSymbolicLog::getDesignatorID(string strMemoryAddress) {
string strID = "";
for(list< pair<string, string> >::iterator itPair = m_lstDesignatorIDs.begin();
itPair != m_lstDesignatorIDs.end();
itPair++) {
pair<string, string> prPair = *itPair;
if(prPair.first == strMemoryAddress) {
strID = prPair.second;
break;
}
}
return strID;
}
string PluginSymbolicLog::getUniqueDesignatorID(string strMemoryAddress) {
string strID = this->getDesignatorID(strMemoryAddress);
if(strID == "") {
strID = this->generateRandomIdentifier("designator_", 14);
m_lstDesignatorIDs.push_back(make_pair(strMemoryAddress, strID));
}
return strID;
}
string PluginSymbolicLog::generateRandomIdentifier(string strPrefix, unsigned int unLength) {
stringstream sts;
sts << strPrefix;
for(unsigned int unI = 0; unI < unLength; unI++) {
int nRandom;
do {
nRandom = rand() % 122 + 48;
} while(nRandom < 48 ||
(nRandom > 57 && nRandom < 65) ||
(nRandom > 90 && nRandom < 97) ||
nRandom > 122);
char cRandom = (char)nRandom;
sts << cRandom;
}
return sts.str();
}
void PluginSymbolicLog::equateDesignators(string strMAChild, string strMAParent) {
string strIDChild = this->getUniqueDesignatorID(strMAChild);
string strIDParent = this->getUniqueDesignatorID(strMAParent);
stringstream stsTimeEquate;
stsTimeEquate << this->getTimeStamp();
m_lstDesignatorEquations.push_back(make_pair(strIDParent, strIDChild));
m_lstDesignatorEquationTimes.push_back(make_pair(strIDChild, stsTimeEquate.str()));
}
}
extern "C" plugins::PluginSymbolicLog* createInstance() {
return new plugins::PluginSymbolicLog();
}
extern "C" void destroyInstance(plugins::PluginSymbolicLog* icDestroy) {
delete icDestroy;
}
}
<commit_msg>Trigger symbolic add image and set subcontext when respective plan events arrive<commit_after>#include <plugins/symboliclog/PluginSymbolicLog.h>
namespace beliefstate {
namespace plugins {
PluginSymbolicLog::PluginSymbolicLog() {
m_ndActive = NULL;
}
PluginSymbolicLog::~PluginSymbolicLog() {
for(list<Node*>::iterator itNode = m_lstNodes.begin();
itNode != m_lstNodes.end();
itNode++) {
Node* ndCurrent = *itNode;
delete ndCurrent;
}
m_lstNodes.clear();
}
Result PluginSymbolicLog::init(int argc, char** argv) {
Result resInit = defaultResult();
// Plan node control events
this->setSubscribedToEvent("begin-context", true);
this->setSubscribedToEvent("end-context", true);
// Extra information assertion
this->setSubscribedToEvent("add-designator", true);
this->setSubscribedToEvent("add-object", true);
this->setSubscribedToEvent("add-failure", true);
this->setSubscribedToEvent("add-image-from-file", true);
this->setSubscribedToEvent("equate-designators", true);
// Information supply services
this->setOffersService("symbolic-plan-tree", true);
return resInit;
}
Result PluginSymbolicLog::deinit() {
return defaultResult();
}
Result PluginSymbolicLog::cycle() {
Result resCycle = defaultResult();
m_mtxEventsStore.lock();
resCycle.lstEvents = m_lstEvents;
m_lstEvents.clear();
m_mtxEventsStore.unlock();
return resCycle;
}
Event PluginSymbolicLog::consumeServiceEvent(ServiceEvent seServiceEvent) {
Event evReturn = defaultEvent();
if(seServiceEvent.siServiceIdentifier == SI_REQUEST) {
if(seServiceEvent.strServiceName == "symbolic-plan-tree") {
evReturn.lstNodes = m_lstNodes;
evReturn.lstDesignatorIDs = m_lstDesignatorIDs;
evReturn.lstEquations = m_lstDesignatorEquations;
evReturn.lstEquationTimes = m_lstDesignatorEquationTimes;
}
}
return evReturn;
}
void PluginSymbolicLog::consumeEvent(Event evEvent) {
//int nID = (evEvent.nContextID == -1 ? (evEvent.cdDesignator ? (int)evEvent.cdDesignator->floatValue("_id") : -1) : evEvent.nContextID);
if(evEvent.strEventName == "begin-context") {
string strName = evEvent.cdDesignator->stringValue("_name");
Node* ndFormerParent = this->activeNode();
Node* ndNew = this->addNode(strName, evEvent.nContextID);
stringstream stsTimeStart;
stsTimeStart << this->getTimeStamp();
ndNew->metaInformation()->setValue(string("time-start"), stsTimeStart.str());
int nDetailLevel = (int)evEvent.cdDesignator->floatValue("_detail-level");
ndNew->metaInformation()->setValue(string("detail-level"), nDetailLevel);
Event evSymbolicBeginCtx = defaultEvent("symbolic-begin-context");
evSymbolicBeginCtx.lstNodes.push_back(ndNew);
this->deployEvent(evSymbolicBeginCtx);
if(ndFormerParent) {
Event evSymbolicSetSubcontext = defaultEvent("symbolic-set-subcontext");
evSymbolicSetSubcontext.lstNodes.push_back(ndFormerParent);
evSymbolicSetSubcontext.lstNodes.push_back(ndNew);
this->deployEvent(evSymbolicSetSubcontext);
}
} else if(evEvent.strEventName == "end-context") {
int nID = (int)evEvent.cdDesignator->floatValue("_id");
int nSuccess = (int)evEvent.cdDesignator->floatValue("_success");
Node *ndCurrent = this->activeNode();
if(ndCurrent) {
if(ndCurrent->id() == nID) {
stringstream sts;
sts << "Received stop context designator for ID " << nID << " (success: " << (nSuccess ? "yes" : "no") << ")";
this->info(sts.str());
ndCurrent->metaInformation()->setValue(string("success"), nSuccess);
stringstream stsTimeEnd;
stsTimeEnd << this->getTimeStamp();
ndCurrent->metaInformation()->setValue(string("time-end"), stsTimeEnd.str());
Node *ndParent = ndCurrent->parent();
this->setNodeAsActive(ndParent);
while(ndParent) {
if(ndParent->prematurelyEnded()) {
ndParent = ndParent->parent();
this->setNodeAsActive(ndParent);
} else {
this->setNodeAsActive(ndParent);
break;
}
}
Event evSymbolicEndCtx = defaultEvent("symbolic-end-context");
evSymbolicEndCtx.lstNodes.push_back(ndCurrent);
this->deployEvent(evSymbolicEndCtx);
} else {
stringstream sts;
sts << "Received stop node designator for ID " << nID << " while ID " << ndCurrent->id() << " is active.";
this->info(sts.str());
Node *ndEndedPrematurely = NULL;
Node *ndSearchTemp = ndCurrent->parent();
while(ndSearchTemp) {
if(ndSearchTemp->id() == nID) {
ndEndedPrematurely = ndSearchTemp;
ndSearchTemp = NULL;
} else {
ndSearchTemp = ndSearchTemp->parent();
}
}
if(ndEndedPrematurely) {
// Found the prematurely ended node in this branch
stringstream sts;
sts << "Marking node " << nID << " as prematurely ended.";
this->info(sts.str());
ndEndedPrematurely->setPrematurelyEnded(true);
} else {
// Didn't find the prematurely ended node in this branch
stringstream sts;
sts << "The apparently prematurely ended node " << nID << " was not found. This is probably a problem.";
this->warn(sts.str());
}
}
} else {
stringstream sts;
sts << "Received stop node designator for ID " << nID << " while in top-level.";
this->warn(sts.str());
}
} else if(evEvent.strEventName == "add-image-from-file") {
if(evEvent.cdDesignator) {
if(this->activeNode()) {
string strFilepath = evEvent.cdDesignator->stringValue("filename");
string strTopic = evEvent.cdDesignator->stringValue("origin");
if(strFilepath != "") {
this->activeNode()->addImage(strTopic, strFilepath);
stringstream sts;
sts << this->activeNode()->id();
this->info("Added image to active node (id " + sts.str() + "): '" + strFilepath + "'");
Event evSymbolicAddImage = defaultEvent("symbolic-add-image");
evSymbolicAddImage.lstNodes.push_back(this->activeNode());
evSymbolicAddImage.cdDesignator = new CDesignator();
evSymbolicAddImage.cdDesignator->setType(ACTION);
evSymbolicAddImage.cdDesignator->setValue("origin", strTopic);
evSymbolicAddImage.cdDesignator->setValue("filename", strFilepath);
this->deployEvent(evSymbolicAddImage);
} else {
this->warn("No filename given. Will not add unnamed image to active node. The designator was:");
evEvent.cdDesignator->printDesignator();
}
} else {
this->warn("No node context available. Cannot add image from file while on top-level.");
}
}
this->warn("Adding images from file is not yet implemented!");
} else if(evEvent.strEventName == "add-failure") {
if(evEvent.cdDesignator) {
if(this->activeNode()) {
// Adding a failure to a node also means to set its success state to 'false'.
string strCondition = evEvent.cdDesignator->stringValue("condition");
stringstream stsTimeFail;
stsTimeFail << this->getTimeStamp();
this->activeNode()->addFailure(strCondition, stsTimeFail.str());
this->activeNode()->setSuccess(false);
stringstream sts;
sts << this->activeNode()->id();
this->info("Added failure to active node (id " + sts.str() + "): '" + strCondition.c_str() + "'");
} else {
this->warn("No node context available. Cannot add failure while on top-level.");
}
}
} else if(evEvent.strEventName == "add-designator") {
if(evEvent.cdDesignator) {
if(this->activeNode()) {
string strType = evEvent.cdDesignator->stringValue("type");
string strAnnotation = evEvent.cdDesignator->stringValue("annotation");
string strMemAddr = evEvent.cdDesignator->stringValue("memory-address");
CKeyValuePair *ckvpDesc = evEvent.cdDesignator->childForKey("description");
list<CKeyValuePair*> lstDescription = ckvpDesc->children();
bool bDesigExists = (this->getDesignatorID(strMemAddr) != "");
string strUniqueID = this->getUniqueDesignatorID(strMemAddr);
this->activeNode()->addDesignator(strType, lstDescription, strUniqueID, strAnnotation);
stringstream sts;
sts << this->activeNode()->id();
this->info("Added '" + strType + "' designator (addr=" + strMemAddr + ") to active context (id " + sts.str() + "): '" + strUniqueID + "'");
// desigResponse->setValue("id", strUniqueID);
// desigResponse->setValue(string("is-new"), (bDesigExists ? 0.0 : 1.0));
//bReturnvalue = true;
} else {
this->warn("No node context available. Cannot add designator while on top-level.");
}
}
} else if(evEvent.strEventName == "equate-designators") {
if(evEvent.cdDesignator) {
string strMemAddrChild = evEvent.cdDesignator->stringValue("memory-address-child");
string strMemAddrParent = evEvent.cdDesignator->stringValue("memory-address-parent");
if(strMemAddrChild != "" && strMemAddrParent != "") {
if(this->activeNode()) {
this->equateDesignators(strMemAddrChild, strMemAddrParent);
}
}
}
} else if(evEvent.strEventName == "add-object") {
if(evEvent.cdDesignator) {
CKeyValuePair *ckvpDesc = evEvent.cdDesignator->childForKey("description");
if(ckvpDesc) {
if(this->activeNode()) {
string strType = evEvent.cdDesignator->stringValue("type");
string strMemAddr = evEvent.cdDesignator->stringValue("memory-address");
bool bDesigExists = (this->getDesignatorID(strMemAddr) != "");
string strUniqueID = this->getUniqueDesignatorID(strMemAddr);
ckvpDesc->setValue("__id", strUniqueID);
this->activeNode()->addObject(ckvpDesc->children());
stringstream sts;
sts << this->activeNode()->id();
this->info("Added object (" + strUniqueID + ") to active node (id " + sts.str() + ").");
} else {
this->warn("No node context available. Cannot add object while on top-level.");
}
}
}
} else {
this->warn("Unknown event name: '" + evEvent.strEventName + "'");
}
}
Node* PluginSymbolicLog::addNode(string strName, int nContextID) {
Node *ndNew = new Node(strName);
ndNew->setID(nContextID);
if(m_ndActive == NULL) {
// Add a new top-level node
m_lstNodes.push_back(ndNew);
stringstream sts;
sts << nContextID;
this->info("Adding new top-level context with ID " + sts.str());
} else {
// Add it as a subnode to the current contextual node
m_ndActive->addSubnode(ndNew);
stringstream sts;
sts << nContextID;
this->info("Adding new sub context with ID " + sts.str());
}
this->info("The new context's name is '" + strName + "'");
this->setNodeAsActive(ndNew);
return ndNew;
}
void PluginSymbolicLog::setNodeAsActive(Node* ndActive) {
m_ndActive = ndActive;
if(m_ndActive) {
stringstream sts;
sts << m_ndActive->id();
this->info("Setting context ID " + sts.str() + " as active context");
} else {
this->info("Removed active context, returning to top-level");
}
}
Node* PluginSymbolicLog::activeNode() {
return m_ndActive;
}
string PluginSymbolicLog::getDesignatorID(string strMemoryAddress) {
string strID = "";
for(list< pair<string, string> >::iterator itPair = m_lstDesignatorIDs.begin();
itPair != m_lstDesignatorIDs.end();
itPair++) {
pair<string, string> prPair = *itPair;
if(prPair.first == strMemoryAddress) {
strID = prPair.second;
break;
}
}
return strID;
}
string PluginSymbolicLog::getUniqueDesignatorID(string strMemoryAddress) {
string strID = this->getDesignatorID(strMemoryAddress);
if(strID == "") {
strID = this->generateRandomIdentifier("designator_", 14);
m_lstDesignatorIDs.push_back(make_pair(strMemoryAddress, strID));
}
return strID;
}
string PluginSymbolicLog::generateRandomIdentifier(string strPrefix, unsigned int unLength) {
stringstream sts;
sts << strPrefix;
for(unsigned int unI = 0; unI < unLength; unI++) {
int nRandom;
do {
nRandom = rand() % 122 + 48;
} while(nRandom < 48 ||
(nRandom > 57 && nRandom < 65) ||
(nRandom > 90 && nRandom < 97) ||
nRandom > 122);
char cRandom = (char)nRandom;
sts << cRandom;
}
return sts.str();
}
void PluginSymbolicLog::equateDesignators(string strMAChild, string strMAParent) {
string strIDChild = this->getUniqueDesignatorID(strMAChild);
string strIDParent = this->getUniqueDesignatorID(strMAParent);
stringstream stsTimeEquate;
stsTimeEquate << this->getTimeStamp();
m_lstDesignatorEquations.push_back(make_pair(strIDParent, strIDChild));
m_lstDesignatorEquationTimes.push_back(make_pair(strIDChild, stsTimeEquate.str()));
}
}
extern "C" plugins::PluginSymbolicLog* createInstance() {
return new plugins::PluginSymbolicLog();
}
extern "C" void destroyInstance(plugins::PluginSymbolicLog* icDestroy) {
delete icDestroy;
}
}
<|endoftext|> |
<commit_before>#include "kvazzupcore.h"
#include "statisticsinterface.h"
#include "globalsdpstate.h"
#include <QHostAddress>
KvazzupCore::KvazzupCore():
media_(),
sip_(),
window_(nullptr)
{}
void KvazzupCore::init()
{
window_.init(this);
window_.show();
sip_.init(this);
QSettings settings("kvazzup.ini", QSettings::IniFormat);
int autoConnect = settings.value("sip/AutoConnect").toInt();
if(autoConnect == 1)
{
sip_.bindToServer();
}
// register the GUI signals indicating GUI changes to be handled approrietly in a system wide manner
QObject::connect(&window_, SIGNAL(settingsChanged()), this, SLOT(updateSettings()));
QObject::connect(&window_, SIGNAL(micStateSwitch()), this, SLOT(micState()));
QObject::connect(&window_, SIGNAL(cameraStateSwitch()), this, SLOT(cameraState()));
QObject::connect(&window_, SIGNAL(endCall()), this, SLOT(endTheCall()));
QObject::connect(&window_, SIGNAL(closed()), this, SLOT(windowClosed()));
QObject::connect(&window_, &CallWindow::callAccepted, this, &KvazzupCore::userAcceptsCall);
QObject::connect(&window_, &CallWindow::callRejected, this, &KvazzupCore::userRejectsCall);
QObject::connect(&window_, &CallWindow::callCancelled, this, &KvazzupCore::userCancelsCall);
stats_ = window_.createStatsWindow();
media_.init(window_.getViewFactory(), stats_);
}
void KvazzupCore::uninit()
{
endTheCall();
sip_.uninit();
media_.uninit();
}
void KvazzupCore::windowClosed()
{
uninit();
}
void KvazzupCore::callToParticipant(QString name, QString username, QString ip)
{
QString ip_str = ip;
Contact con;
con.remoteAddress = ip_str;
con.realName = name;
con.username = username;
//start negotiations for this connection
qDebug() << "Session Initiation," << metaObject()->className()
<< ": Start Call," << metaObject()->className() << ": Initiated call starting to" << con.realName;
sip_.startCall(con);
}
void KvazzupCore::chatWithParticipant(QString name, QString username, QString ip)
{
qDebug() << "Chatting," << metaObject()->className()
<< ": Chatting with:" << name << '(' << username << ") at ip:" << ip << ": Chat not implemented yet";
}
void KvazzupCore::outgoingCall(uint32_t sessionID, QString callee)
{
window_.displayOutgoingCall(sessionID, callee);
if(states_.find(sessionID) == states_.end())
{
states_[sessionID] = CALLINGTHEM;
}
}
bool KvazzupCore::incomingCall(uint32_t sessionID, QString caller)
{
if(states_.find(sessionID) != states_.end())
{
qDebug() << "Incoming call," << metaObject()->className() << ": ERROR: Overwriting and existing session in the Kvazzup Core!";
}
QSettings settings("kvazzup.ini", QSettings::IniFormat);
int autoAccept = settings.value("local/Auto-Accept").toInt();
if(autoAccept == 1)
{
qDebug() << "Incoming call," << metaObject()->className() << ": Incoming call auto-accepted!";
userAcceptsCall(sessionID);
states_[sessionID] = CALLNEGOTIATING;
return true;
}
else
{
window_.displayIncomingCall(sessionID, caller);
states_[sessionID] = CALLRINGINGWITHUS;
}
return false;
}
void KvazzupCore::callRinging(uint32_t sessionID)
{
if(states_.find(sessionID) != states_.end() && states_[sessionID] == CALLINGTHEM)
{
qDebug() << "Ringing," << metaObject()->className() << ": Our call is ringing!";
window_.displayRinging(sessionID);
states_[sessionID] = CALLRINGINWITHTHEM;
}
else
{
qDebug() << "Ringing," << metaObject()->className() << ": PEER ERROR: Got call ringing for nonexisting call:" << sessionID;
}
}
void KvazzupCore::peerAccepted(uint32_t sessionID)
{
if(states_.find(sessionID) != states_.end())
{
if(states_[sessionID] == CALLRINGINWITHTHEM || states_[sessionID] == CALLINGTHEM)
{
qDebug() << "Accepting," << metaObject()->className() << ": They accepted our call!";
states_[sessionID] = CALLNEGOTIATING;
}
else
{
qDebug() << "PEER ERROR, accepting" << metaObject()->className() << ": Got an accepted call even though we have not yet called them!";
}
}
else
{
qDebug() << "ERROR, accepting" << metaObject()->className() << ": : Peer accepted a session which is not in Call manager";
}
}
void KvazzupCore::peerRejected(uint32_t sessionID)
{
if(states_.find(sessionID) != states_.end())
{
if(states_[sessionID] == CALLRINGINWITHTHEM)
{
qDebug() << "Rejection," << metaObject()->className() << ": Our call has been rejected!";
removeSession(sessionID);
}
else
{
qDebug() << "Rejection," << metaObject()->className() << ": PEER ERROR: Got reject when we weren't calling them:" << states_[sessionID];
}
}
else
{
qDebug() << "Rejection," << metaObject()->className() << ": PEER ERROR: Got reject for nonexisting call:" << sessionID;
qDebug() << "Rejection," << metaObject()->className() << ": Number of ongoing sessions:" << states_.size();
}
}
void KvazzupCore::callNegotiated(uint32_t sessionID)
{
if(states_.find(sessionID) != states_.end())
{
if(states_[sessionID] == CALLNEGOTIATING)
{
qDebug() << "Negotiation," << metaObject()->className() << ": Call has been agreed upon with peer:" << sessionID;
window_.addVideoStream(sessionID);
std::shared_ptr<SDPMessageInfo> localSDP;
std::shared_ptr<SDPMessageInfo> remoteSDP;
sip_.getSDPs(sessionID,
localSDP,
remoteSDP);
if(localSDP == nullptr || remoteSDP == nullptr)
{
return;
}
media_.addParticipant(sessionID, remoteSDP, localSDP);
states_[sessionID] = CALLONGOING;
}
else
{
qDebug() << "Negotiation," << metaObject()->className() << ": PEER ERROR: Got call successful negotiation even though we are not there yet:" << states_[sessionID];
}
}
else
{
qDebug() << "Negotiation," << metaObject()->className() << ": ERROR: This session does not exist in Call manager";
}
}
void KvazzupCore::callNegotiationFailed(uint32_t sessionID)
{
// TODO: display a proper error for the user
peerRejected(sessionID);
}
void KvazzupCore::cancelIncomingCall(uint32_t sessionID)
{
// TODO: display a proper message to the user that peer has cancelled their call
removeSession(sessionID);
}
void KvazzupCore::endCall(uint32_t sessionID)
{
if(states_.find(sessionID) != states_.end()
&& states_[sessionID] == CALLONGOING)
{
media_.removeParticipant(sessionID);
}
removeSession(sessionID);
}
void KvazzupCore::registeredToServer()
{
qDebug() << "Core," << metaObject()->className() << ": Got info, that we have been registered to SIP server.";
// TODO: indicate to user in some small detail
}
void KvazzupCore::registeringFailed()
{
qDebug() << "Core," << metaObject()->className() << ": Failed to register";
// TODO: indicate error to user
}
void KvazzupCore::updateSettings()
{
media_.updateSettings();
//sip_.updateSettings(); // for blocking list
}
void KvazzupCore::userAcceptsCall(uint32_t sessionID)
{
qDebug() << "Core," << metaObject()->className() << ": Sending accept";
sip_.acceptCall(sessionID);
states_[sessionID] = CALLNEGOTIATING;
}
void KvazzupCore::userRejectsCall(uint32_t sessionID)
{
qDebug() << "Core," << metaObject()->className() << ": We have rejected their call";
sip_.rejectCall(sessionID);
removeSession(sessionID);
}
void KvazzupCore::userCancelsCall(uint32_t sessionID)
{
qDebug() << "Core," << metaObject()->className() << ": We have cancelled our call";
sip_.cancelCall(sessionID);
removeSession(sessionID);
}
void KvazzupCore::endTheCall()
{
qDebug() << "Core," << metaObject()->className() << ": End all call," << metaObject()->className()
<< ": End all calls button pressed";
sip_.endAllCalls();
media_.endAllCalls();
window_.clearConferenceView();
states_.clear();
}
void KvazzupCore::micState()
{
window_.setMicState(media_.toggleMic());
}
void KvazzupCore::cameraState()
{
window_.setCameraState(media_.toggleCamera());
}
void KvazzupCore::removeSession(uint32_t sessionID)
{
window_.removeParticipant(sessionID);
auto it = states_.find(sessionID);
if(it != states_.end())
{
states_.erase(it);
}
}
<commit_msg>[Core] (feature) Removed the ending of calls when closing the application because uninit should do the same and this way we don't restart self view camera.<commit_after>#include "kvazzupcore.h"
#include "statisticsinterface.h"
#include "globalsdpstate.h"
#include <QHostAddress>
KvazzupCore::KvazzupCore():
media_(),
sip_(),
window_(nullptr)
{}
void KvazzupCore::init()
{
window_.init(this);
window_.show();
sip_.init(this);
QSettings settings("kvazzup.ini", QSettings::IniFormat);
int autoConnect = settings.value("sip/AutoConnect").toInt();
if(autoConnect == 1)
{
sip_.bindToServer();
}
// register the GUI signals indicating GUI changes to be handled approrietly in a system wide manner
QObject::connect(&window_, SIGNAL(settingsChanged()), this, SLOT(updateSettings()));
QObject::connect(&window_, SIGNAL(micStateSwitch()), this, SLOT(micState()));
QObject::connect(&window_, SIGNAL(cameraStateSwitch()), this, SLOT(cameraState()));
QObject::connect(&window_, SIGNAL(endCall()), this, SLOT(endTheCall()));
QObject::connect(&window_, SIGNAL(closed()), this, SLOT(windowClosed()));
QObject::connect(&window_, &CallWindow::callAccepted, this, &KvazzupCore::userAcceptsCall);
QObject::connect(&window_, &CallWindow::callRejected, this, &KvazzupCore::userRejectsCall);
QObject::connect(&window_, &CallWindow::callCancelled, this, &KvazzupCore::userCancelsCall);
stats_ = window_.createStatsWindow();
media_.init(window_.getViewFactory(), stats_);
}
void KvazzupCore::uninit()
{
sip_.uninit();
media_.uninit();
}
void KvazzupCore::windowClosed()
{
uninit();
}
void KvazzupCore::callToParticipant(QString name, QString username, QString ip)
{
QString ip_str = ip;
Contact con;
con.remoteAddress = ip_str;
con.realName = name;
con.username = username;
//start negotiations for this connection
qDebug() << "Session Initiation," << metaObject()->className()
<< ": Start Call," << metaObject()->className() << ": Initiated call starting to" << con.realName;
sip_.startCall(con);
}
void KvazzupCore::chatWithParticipant(QString name, QString username, QString ip)
{
qDebug() << "Chatting," << metaObject()->className()
<< ": Chatting with:" << name << '(' << username << ") at ip:" << ip << ": Chat not implemented yet";
}
void KvazzupCore::outgoingCall(uint32_t sessionID, QString callee)
{
window_.displayOutgoingCall(sessionID, callee);
if(states_.find(sessionID) == states_.end())
{
states_[sessionID] = CALLINGTHEM;
}
}
bool KvazzupCore::incomingCall(uint32_t sessionID, QString caller)
{
if(states_.find(sessionID) != states_.end())
{
qDebug() << "Incoming call," << metaObject()->className() << ": ERROR: Overwriting and existing session in the Kvazzup Core!";
}
QSettings settings("kvazzup.ini", QSettings::IniFormat);
int autoAccept = settings.value("local/Auto-Accept").toInt();
if(autoAccept == 1)
{
qDebug() << "Incoming call," << metaObject()->className() << ": Incoming call auto-accepted!";
userAcceptsCall(sessionID);
states_[sessionID] = CALLNEGOTIATING;
return true;
}
else
{
window_.displayIncomingCall(sessionID, caller);
states_[sessionID] = CALLRINGINGWITHUS;
}
return false;
}
void KvazzupCore::callRinging(uint32_t sessionID)
{
if(states_.find(sessionID) != states_.end() && states_[sessionID] == CALLINGTHEM)
{
qDebug() << "Ringing," << metaObject()->className() << ": Our call is ringing!";
window_.displayRinging(sessionID);
states_[sessionID] = CALLRINGINWITHTHEM;
}
else
{
qDebug() << "Ringing," << metaObject()->className() << ": PEER ERROR: Got call ringing for nonexisting call:" << sessionID;
}
}
void KvazzupCore::peerAccepted(uint32_t sessionID)
{
if(states_.find(sessionID) != states_.end())
{
if(states_[sessionID] == CALLRINGINWITHTHEM || states_[sessionID] == CALLINGTHEM)
{
qDebug() << "Accepting," << metaObject()->className() << ": They accepted our call!";
states_[sessionID] = CALLNEGOTIATING;
}
else
{
qDebug() << "PEER ERROR, accepting" << metaObject()->className() << ": Got an accepted call even though we have not yet called them!";
}
}
else
{
qDebug() << "ERROR, accepting" << metaObject()->className() << ": : Peer accepted a session which is not in Call manager";
}
}
void KvazzupCore::peerRejected(uint32_t sessionID)
{
if(states_.find(sessionID) != states_.end())
{
if(states_[sessionID] == CALLRINGINWITHTHEM)
{
qDebug() << "Rejection," << metaObject()->className() << ": Our call has been rejected!";
removeSession(sessionID);
}
else
{
qDebug() << "Rejection," << metaObject()->className() << ": PEER ERROR: Got reject when we weren't calling them:" << states_[sessionID];
}
}
else
{
qDebug() << "Rejection," << metaObject()->className() << ": PEER ERROR: Got reject for nonexisting call:" << sessionID;
qDebug() << "Rejection," << metaObject()->className() << ": Number of ongoing sessions:" << states_.size();
}
}
void KvazzupCore::callNegotiated(uint32_t sessionID)
{
if(states_.find(sessionID) != states_.end())
{
if(states_[sessionID] == CALLNEGOTIATING)
{
qDebug() << "Negotiation," << metaObject()->className() << ": Call has been agreed upon with peer:" << sessionID;
window_.addVideoStream(sessionID);
std::shared_ptr<SDPMessageInfo> localSDP;
std::shared_ptr<SDPMessageInfo> remoteSDP;
sip_.getSDPs(sessionID,
localSDP,
remoteSDP);
if(localSDP == nullptr || remoteSDP == nullptr)
{
return;
}
media_.addParticipant(sessionID, remoteSDP, localSDP);
states_[sessionID] = CALLONGOING;
}
else
{
qDebug() << "Negotiation," << metaObject()->className() << ": PEER ERROR: Got call successful negotiation even though we are not there yet:" << states_[sessionID];
}
}
else
{
qDebug() << "Negotiation," << metaObject()->className() << ": ERROR: This session does not exist in Call manager";
}
}
void KvazzupCore::callNegotiationFailed(uint32_t sessionID)
{
// TODO: display a proper error for the user
peerRejected(sessionID);
}
void KvazzupCore::cancelIncomingCall(uint32_t sessionID)
{
// TODO: display a proper message to the user that peer has cancelled their call
removeSession(sessionID);
}
void KvazzupCore::endCall(uint32_t sessionID)
{
if(states_.find(sessionID) != states_.end()
&& states_[sessionID] == CALLONGOING)
{
media_.removeParticipant(sessionID);
}
removeSession(sessionID);
}
void KvazzupCore::registeredToServer()
{
qDebug() << "Core," << metaObject()->className() << ": Got info, that we have been registered to SIP server.";
// TODO: indicate to user in some small detail
}
void KvazzupCore::registeringFailed()
{
qDebug() << "Core," << metaObject()->className() << ": Failed to register";
// TODO: indicate error to user
}
void KvazzupCore::updateSettings()
{
media_.updateSettings();
//sip_.updateSettings(); // for blocking list
}
void KvazzupCore::userAcceptsCall(uint32_t sessionID)
{
qDebug() << "Core," << metaObject()->className() << ": Sending accept";
sip_.acceptCall(sessionID);
states_[sessionID] = CALLNEGOTIATING;
}
void KvazzupCore::userRejectsCall(uint32_t sessionID)
{
qDebug() << "Core," << metaObject()->className() << ": We have rejected their call";
sip_.rejectCall(sessionID);
removeSession(sessionID);
}
void KvazzupCore::userCancelsCall(uint32_t sessionID)
{
qDebug() << "Core," << metaObject()->className() << ": We have cancelled our call";
sip_.cancelCall(sessionID);
removeSession(sessionID);
}
void KvazzupCore::endTheCall()
{
qDebug() << "Core," << metaObject()->className() << ": End all call," << metaObject()->className()
<< ": End all calls button pressed";
sip_.endAllCalls();
media_.endAllCalls();
window_.clearConferenceView();
states_.clear();
}
void KvazzupCore::micState()
{
window_.setMicState(media_.toggleMic());
}
void KvazzupCore::cameraState()
{
window_.setCameraState(media_.toggleCamera());
}
void KvazzupCore::removeSession(uint32_t sessionID)
{
window_.removeParticipant(sessionID);
auto it = states_.find(sessionID);
if(it != states_.end())
{
states_.erase(it);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/message_center/web_notification_tray_win.h"
#include "base/i18n/number_formatting.h"
#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/status_icons/status_icon.h"
#include "chrome/browser/status_icons/status_tray.h"
#include "chrome/browser/ui/views/message_center/notification_bubble_wrapper_win.h"
#include "chrome/browser/ui/views/status_icons/status_icon_win.h"
#include "content/public/browser/user_metrics.h"
#include "grit/chromium_strings.h"
#include "grit/theme_resources.h"
#include "grit/ui_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/models/simple_menu_model.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/win/hwnd_util.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/image/image_skia_operations.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/screen.h"
#include "ui/gfx/size.h"
#include "ui/message_center/message_center_tray.h"
#include "ui/message_center/message_center_tray_delegate.h"
#include "ui/message_center/views/message_bubble_base.h"
#include "ui/message_center/views/message_center_bubble.h"
#include "ui/message_center/views/message_popup_collection.h"
#include "ui/views/widget/widget.h"
namespace {
// Tray constants
const int kScreenEdgePadding = 2;
const int kSystemTrayWidth = 16;
const int kSystemTrayHeight = 16;
const int kNumberOfSystemTraySprites = 10;
gfx::Rect GetCornerAnchorRect() {
// TODO(dewittj): Use the preference to determine which corner to anchor from.
gfx::Screen* screen = gfx::Screen::GetNativeScreen();
gfx::Rect rect = screen->GetPrimaryDisplay().work_area();
rect.Inset(kScreenEdgePadding, kScreenEdgePadding);
return gfx::Rect(rect.bottom_right(), gfx::Size());
}
gfx::Point GetClosestCorner(gfx::Rect rect, gfx::Point query) {
gfx::Point center_point = rect.CenterPoint();
gfx::Point rv;
if (query.x() > center_point.x())
rv.set_x(rect.right());
else
rv.set_x(rect.x());
if (query.y() > center_point.y())
rv.set_y(rect.bottom());
else
rv.set_y(rect.y());
return rv;
}
// GetMouseAnchorRect returns a rectangle that has one corner where the mouse
// clicked, and the opposite corner at the closest corner of the work area
// (inset by an appropriate margin.)
gfx::Rect GetMouseAnchorRect(gfx::Point cursor) {
// TODO(dewittj): GetNativeScreen could be wrong for Aura.
gfx::Screen* screen = gfx::Screen::GetNativeScreen();
gfx::Rect work_area = screen->GetPrimaryDisplay().work_area();
work_area.Inset(kScreenEdgePadding, kScreenEdgePadding);
gfx::Point corner = GetClosestCorner(work_area, cursor);
gfx::Rect mouse_anchor_rect(gfx::BoundingRect(cursor, corner));
return mouse_anchor_rect;
}
gfx::ImageSkia GetIcon(int unread_count) {
bool has_unread = unread_count > 0;
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
if (!has_unread)
return *rb.GetImageSkiaNamed(IDR_NOTIFICATION_TRAY_EMPTY);
// TODO(dewittj): Use scale factors other than 100P.
scoped_ptr<gfx::Canvas> canvas(new gfx::Canvas(
gfx::Size(kSystemTrayWidth, kSystemTrayHeight),
ui::SCALE_FACTOR_100P,
false));
// Draw the attention-grabbing background image.
canvas->DrawImageInt(
*rb.GetImageSkiaNamed(IDR_NOTIFICATION_TRAY_ATTENTION), 0, 0);
// |numbers| is a sprite map with the image of a number from 1-9 and 9+. They
// are arranged horizontally, and have a transparent background.
gfx::ImageSkia* numbers = rb.GetImageSkiaNamed(IDR_NOTIFICATION_TRAY_NUMBERS);
// Assume that the last sprite is the catch-all for higher numbers of
// notifications.
int effective_unread = std::min(unread_count, kNumberOfSystemTraySprites);
int x_offset = (effective_unread - 1) * kSystemTrayWidth;
canvas->DrawImageInt(*numbers,
x_offset, 0, kSystemTrayWidth, kSystemTrayHeight,
0, 0, kSystemTrayWidth, kSystemTrayHeight,
false);
return gfx::ImageSkia(canvas->ExtractImageRep());
}
} // namespace
using content::UserMetricsAction;
namespace message_center {
MessageCenterTrayDelegate* CreateMessageCenterTray() {
return new WebNotificationTrayWin();
}
WebNotificationTrayWin::WebNotificationTrayWin()
: status_icon_(NULL),
message_center_visible_(false),
should_update_tray_content_(true) {
message_center_tray_.reset(new MessageCenterTray(
this, g_browser_process->message_center()));
UpdateStatusIcon();
}
WebNotificationTrayWin::~WebNotificationTrayWin() {
// Reset this early so that delegated events during destruction don't cause
// problems.
message_center_tray_.reset();
DestroyStatusIcon();
}
message_center::MessageCenter* WebNotificationTrayWin::message_center() {
return message_center_tray_->message_center();
}
bool WebNotificationTrayWin::ShowPopups() {
popup_collection_.reset(
new message_center::MessagePopupCollection(NULL, message_center()));
return true;
}
void WebNotificationTrayWin::HidePopups() {
popup_collection_.reset();
}
bool WebNotificationTrayWin::ShowMessageCenter() {
content::RecordAction(UserMetricsAction("Notifications.ShowMessageCenter"));
scoped_ptr<message_center::MessageCenterBubble> bubble(
new message_center::MessageCenterBubble(message_center()));
gfx::Screen* screen = gfx::Screen::GetNativeScreen();
gfx::Rect work_area = screen->GetPrimaryDisplay().work_area();
views::TrayBubbleView::AnchorAlignment alignment = GetAnchorAlignment();
int max_height = work_area.height();
// If the alignment is left- or right-oriented, the bubble can fill up the
// entire vertical height of the screen since the bubble is rendered to the
// side of the clicked icon. Otherwise we have to adjust for the arrow's
// height.
if (alignment == views::TrayBubbleView::ANCHOR_ALIGNMENT_BOTTOM ||
alignment == views::TrayBubbleView::ANCHOR_ALIGNMENT_TOP) {
max_height -= 2*kScreenEdgePadding;
// If the work area contains the click point, then we know that the icon is
// not in the taskbar. Then we need to subtract the distance of the click
// point from the edge of the work area so we can see the whole bubble.
if (work_area.Contains(mouse_click_point_)) {
max_height -= std::min(mouse_click_point_.y() - work_area.y(),
work_area.bottom() - mouse_click_point_.y());
}
}
bubble->SetMaxHeight(max_height);
message_center_bubble_.reset(new internal::NotificationBubbleWrapperWin(
this,
bubble.Pass(),
internal::NotificationBubbleWrapperWin::BUBBLE_TYPE_MESSAGE_CENTER));
return true;
}
void WebNotificationTrayWin::HideMessageCenter() {
message_center_bubble_.reset();
}
void WebNotificationTrayWin::UpdatePopups() {
// |popup_collection_| receives notification add/remove events and updates
// itself, so this method doesn't need to do anything.
// TODO(mukai): remove this method (currently this is used by
// non-rich-notifications in ChromeOS).
};
void WebNotificationTrayWin::OnMessageCenterTrayChanged() {
// See the comments in ash/system/web_notification/web_notification_tray.cc
// for why PostTask.
should_update_tray_content_ = true;
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&WebNotificationTrayWin::UpdateStatusIcon, AsWeakPtr()));
}
gfx::Rect WebNotificationTrayWin::GetMessageCenterAnchor() {
return GetMouseAnchorRect(mouse_click_point_);
}
gfx::Rect WebNotificationTrayWin::GetPopupAnchor() {
return GetCornerAnchorRect();
}
views::TrayBubbleView::AnchorAlignment
WebNotificationTrayWin::GetAnchorAlignment() {
gfx::Screen* screen = gfx::Screen::GetNativeScreen();
// TODO(dewittj): It's possible GetPrimaryDisplay is wrong.
gfx::Rect screen_bounds = screen->GetPrimaryDisplay().bounds();
gfx::Rect work_area = screen->GetPrimaryDisplay().work_area();
// Comparing the work area to the screen bounds gives us the location of the
// taskbar. If the work area is less tall than the screen, assume the taskbar
// is on the bottom, and cause the arrow to be displayed on the bottom of the
// bubble. Otherwise, cause the arrow to be displayed on the side of the
// bubble that the taskbar is on.
if (work_area.width() < screen_bounds.width()) {
if (work_area.x() > screen_bounds.x())
return views::TrayBubbleView::ANCHOR_ALIGNMENT_LEFT;
return views::TrayBubbleView::ANCHOR_ALIGNMENT_RIGHT;
}
return views::TrayBubbleView::ANCHOR_ALIGNMENT_BOTTOM;
}
gfx::NativeView WebNotificationTrayWin::GetBubbleWindowContainer() {
return NULL;
}
void WebNotificationTrayWin::UpdateStatusIcon() {
if (!should_update_tray_content_)
return;
should_update_tray_content_ = false;
int total_notifications = message_center()->NotificationCount();
if (total_notifications == 0) {
DestroyStatusIcon();
return;
}
int unread_notifications = message_center()->UnreadNotificationCount();
StatusIcon* status_icon = GetStatusIcon();
if (!status_icon)
return;
status_icon->SetImage(GetIcon(unread_notifications));
string16 product_name(l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME));
if (unread_notifications > 0) {
string16 str_unread_count = base::FormatNumber(unread_notifications);
status_icon->SetToolTip(l10n_util::GetStringFUTF16(
IDS_MESSAGE_CENTER_TOOLTIP_UNREAD, product_name, str_unread_count));
} else {
status_icon->SetToolTip(l10n_util::GetStringFUTF16(
IDS_MESSAGE_CENTER_TOOLTIP, product_name));
}
}
void WebNotificationTrayWin::OnStatusIconClicked() {
// TODO(dewittj): It's possible GetNativeScreen is wrong for win-aura.
gfx::Screen* screen = gfx::Screen::GetNativeScreen();
mouse_click_point_ = screen->GetCursorScreenPoint();
message_center_tray_->ToggleMessageCenterBubble();
}
void WebNotificationTrayWin::HideBubbleWithView(
const views::TrayBubbleView* bubble_view) {
if (message_center_bubble_.get() &&
bubble_view == message_center_bubble_->bubble_view()) {
message_center_tray_->HideMessageCenterBubble();
}
}
StatusIcon* WebNotificationTrayWin::GetStatusIcon() {
if (status_icon_)
return status_icon_;
StatusTray* status_tray = g_browser_process->status_tray();
if (!status_tray)
return NULL;
StatusIcon* status_icon = status_tray->CreateStatusIcon();
if (!status_icon)
return NULL;
status_icon_ = status_icon;
status_icon_->AddObserver(this);
AddQuietModeMenu(status_icon_);
return status_icon_;
}
void WebNotificationTrayWin::DestroyStatusIcon() {
if (!status_icon_)
return;
status_icon_->RemoveObserver(this);
StatusTray* status_tray = g_browser_process->status_tray();
if (status_tray)
status_tray->RemoveStatusIcon(status_icon_);
status_icon_ = NULL;
}
void WebNotificationTrayWin::AddQuietModeMenu(StatusIcon* status_icon) {
DCHECK(status_icon);
status_icon->SetContextMenu(message_center_tray_->CreateQuietModeMenu());
}
message_center::MessageCenterBubble*
WebNotificationTrayWin::GetMessageCenterBubbleForTest() {
if (!message_center_bubble_.get())
return NULL;
return static_cast<message_center::MessageCenterBubble*>(
message_center_bubble_->bubble());
}
} // namespace message_center
<commit_msg>ShowMessageCenter compilation error fixed for Linux compiler <commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/message_center/web_notification_tray_win.h"
#include "base/i18n/number_formatting.h"
#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/status_icons/status_icon.h"
#include "chrome/browser/status_icons/status_tray.h"
#include "chrome/browser/ui/views/message_center/notification_bubble_wrapper_win.h"
#include "chrome/browser/ui/views/status_icons/status_icon_win.h"
#include "content/public/browser/user_metrics.h"
#include "grit/chromium_strings.h"
#include "grit/theme_resources.h"
#include "grit/ui_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/models/simple_menu_model.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/win/hwnd_util.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/image/image_skia_operations.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/screen.h"
#include "ui/gfx/size.h"
#include "ui/message_center/message_center_tray.h"
#include "ui/message_center/message_center_tray_delegate.h"
#include "ui/message_center/views/message_bubble_base.h"
#include "ui/message_center/views/message_center_bubble.h"
#include "ui/message_center/views/message_popup_collection.h"
#include "ui/views/widget/widget.h"
namespace {
// Tray constants
const int kScreenEdgePadding = 2;
const int kSystemTrayWidth = 16;
const int kSystemTrayHeight = 16;
const int kNumberOfSystemTraySprites = 10;
gfx::Rect GetCornerAnchorRect() {
// TODO(dewittj): Use the preference to determine which corner to anchor from.
gfx::Screen* screen = gfx::Screen::GetNativeScreen();
gfx::Rect rect = screen->GetPrimaryDisplay().work_area();
rect.Inset(kScreenEdgePadding, kScreenEdgePadding);
return gfx::Rect(rect.bottom_right(), gfx::Size());
}
gfx::Point GetClosestCorner(gfx::Rect rect, gfx::Point query) {
gfx::Point center_point = rect.CenterPoint();
gfx::Point rv;
if (query.x() > center_point.x())
rv.set_x(rect.right());
else
rv.set_x(rect.x());
if (query.y() > center_point.y())
rv.set_y(rect.bottom());
else
rv.set_y(rect.y());
return rv;
}
// GetMouseAnchorRect returns a rectangle that has one corner where the mouse
// clicked, and the opposite corner at the closest corner of the work area
// (inset by an appropriate margin.)
gfx::Rect GetMouseAnchorRect(gfx::Point cursor) {
// TODO(dewittj): GetNativeScreen could be wrong for Aura.
gfx::Screen* screen = gfx::Screen::GetNativeScreen();
gfx::Rect work_area = screen->GetPrimaryDisplay().work_area();
work_area.Inset(kScreenEdgePadding, kScreenEdgePadding);
gfx::Point corner = GetClosestCorner(work_area, cursor);
gfx::Rect mouse_anchor_rect(gfx::BoundingRect(cursor, corner));
return mouse_anchor_rect;
}
gfx::ImageSkia GetIcon(int unread_count) {
bool has_unread = unread_count > 0;
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
if (!has_unread)
return *rb.GetImageSkiaNamed(IDR_NOTIFICATION_TRAY_EMPTY);
// TODO(dewittj): Use scale factors other than 100P.
scoped_ptr<gfx::Canvas> canvas(new gfx::Canvas(
gfx::Size(kSystemTrayWidth, kSystemTrayHeight),
ui::SCALE_FACTOR_100P,
false));
// Draw the attention-grabbing background image.
canvas->DrawImageInt(
*rb.GetImageSkiaNamed(IDR_NOTIFICATION_TRAY_ATTENTION), 0, 0);
// |numbers| is a sprite map with the image of a number from 1-9 and 9+. They
// are arranged horizontally, and have a transparent background.
gfx::ImageSkia* numbers = rb.GetImageSkiaNamed(IDR_NOTIFICATION_TRAY_NUMBERS);
// Assume that the last sprite is the catch-all for higher numbers of
// notifications.
int effective_unread = std::min(unread_count, kNumberOfSystemTraySprites);
int x_offset = (effective_unread - 1) * kSystemTrayWidth;
canvas->DrawImageInt(*numbers,
x_offset, 0, kSystemTrayWidth, kSystemTrayHeight,
0, 0, kSystemTrayWidth, kSystemTrayHeight,
false);
return gfx::ImageSkia(canvas->ExtractImageRep());
}
} // namespace
using content::UserMetricsAction;
namespace message_center {
MessageCenterTrayDelegate* CreateMessageCenterTray() {
return new WebNotificationTrayWin();
}
WebNotificationTrayWin::WebNotificationTrayWin()
: status_icon_(NULL),
message_center_visible_(false),
should_update_tray_content_(true) {
message_center_tray_.reset(new MessageCenterTray(
this, g_browser_process->message_center()));
UpdateStatusIcon();
}
WebNotificationTrayWin::~WebNotificationTrayWin() {
// Reset this early so that delegated events during destruction don't cause
// problems.
message_center_tray_.reset();
DestroyStatusIcon();
}
message_center::MessageCenter* WebNotificationTrayWin::message_center() {
return message_center_tray_->message_center();
}
bool WebNotificationTrayWin::ShowPopups() {
popup_collection_.reset(
new message_center::MessagePopupCollection(NULL, message_center()));
return true;
}
void WebNotificationTrayWin::HidePopups() {
popup_collection_.reset();
}
bool WebNotificationTrayWin::ShowMessageCenter() {
content::RecordAction(UserMetricsAction("Notifications.ShowMessageCenter"));
// Using MessageBubbleBase instead of MessageCenterBubble to
// remove dependence on implicit type conversion
scoped_ptr<message_center::MessageBubbleBase> bubble(
new message_center::MessageCenterBubble(message_center()));
gfx::Screen* screen = gfx::Screen::GetNativeScreen();
gfx::Rect work_area = screen->GetPrimaryDisplay().work_area();
views::TrayBubbleView::AnchorAlignment alignment = GetAnchorAlignment();
int max_height = work_area.height();
// If the alignment is left- or right-oriented, the bubble can fill up the
// entire vertical height of the screen since the bubble is rendered to the
// side of the clicked icon. Otherwise we have to adjust for the arrow's
// height.
if (alignment == views::TrayBubbleView::ANCHOR_ALIGNMENT_BOTTOM ||
alignment == views::TrayBubbleView::ANCHOR_ALIGNMENT_TOP) {
max_height -= 2*kScreenEdgePadding;
// If the work area contains the click point, then we know that the icon is
// not in the taskbar. Then we need to subtract the distance of the click
// point from the edge of the work area so we can see the whole bubble.
if (work_area.Contains(mouse_click_point_)) {
max_height -= std::min(mouse_click_point_.y() - work_area.y(),
work_area.bottom() - mouse_click_point_.y());
}
}
bubble->SetMaxHeight(max_height);
message_center_bubble_.reset(new internal::NotificationBubbleWrapperWin(
this,
bubble.Pass(),
internal::NotificationBubbleWrapperWin::BUBBLE_TYPE_MESSAGE_CENTER));
return true;
}
void WebNotificationTrayWin::HideMessageCenter() {
message_center_bubble_.reset();
}
void WebNotificationTrayWin::UpdatePopups() {
// |popup_collection_| receives notification add/remove events and updates
// itself, so this method doesn't need to do anything.
// TODO(mukai): remove this method (currently this is used by
// non-rich-notifications in ChromeOS).
};
void WebNotificationTrayWin::OnMessageCenterTrayChanged() {
// See the comments in ash/system/web_notification/web_notification_tray.cc
// for why PostTask.
should_update_tray_content_ = true;
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&WebNotificationTrayWin::UpdateStatusIcon, AsWeakPtr()));
}
gfx::Rect WebNotificationTrayWin::GetMessageCenterAnchor() {
return GetMouseAnchorRect(mouse_click_point_);
}
gfx::Rect WebNotificationTrayWin::GetPopupAnchor() {
return GetCornerAnchorRect();
}
views::TrayBubbleView::AnchorAlignment
WebNotificationTrayWin::GetAnchorAlignment() {
gfx::Screen* screen = gfx::Screen::GetNativeScreen();
// TODO(dewittj): It's possible GetPrimaryDisplay is wrong.
gfx::Rect screen_bounds = screen->GetPrimaryDisplay().bounds();
gfx::Rect work_area = screen->GetPrimaryDisplay().work_area();
// Comparing the work area to the screen bounds gives us the location of the
// taskbar. If the work area is less tall than the screen, assume the taskbar
// is on the bottom, and cause the arrow to be displayed on the bottom of the
// bubble. Otherwise, cause the arrow to be displayed on the side of the
// bubble that the taskbar is on.
if (work_area.width() < screen_bounds.width()) {
if (work_area.x() > screen_bounds.x())
return views::TrayBubbleView::ANCHOR_ALIGNMENT_LEFT;
return views::TrayBubbleView::ANCHOR_ALIGNMENT_RIGHT;
}
return views::TrayBubbleView::ANCHOR_ALIGNMENT_BOTTOM;
}
gfx::NativeView WebNotificationTrayWin::GetBubbleWindowContainer() {
return NULL;
}
void WebNotificationTrayWin::UpdateStatusIcon() {
if (!should_update_tray_content_)
return;
should_update_tray_content_ = false;
int total_notifications = message_center()->NotificationCount();
if (total_notifications == 0) {
DestroyStatusIcon();
return;
}
int unread_notifications = message_center()->UnreadNotificationCount();
StatusIcon* status_icon = GetStatusIcon();
if (!status_icon)
return;
status_icon->SetImage(GetIcon(unread_notifications));
string16 product_name(l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME));
if (unread_notifications > 0) {
string16 str_unread_count = base::FormatNumber(unread_notifications);
status_icon->SetToolTip(l10n_util::GetStringFUTF16(
IDS_MESSAGE_CENTER_TOOLTIP_UNREAD, product_name, str_unread_count));
} else {
status_icon->SetToolTip(l10n_util::GetStringFUTF16(
IDS_MESSAGE_CENTER_TOOLTIP, product_name));
}
}
void WebNotificationTrayWin::OnStatusIconClicked() {
// TODO(dewittj): It's possible GetNativeScreen is wrong for win-aura.
gfx::Screen* screen = gfx::Screen::GetNativeScreen();
mouse_click_point_ = screen->GetCursorScreenPoint();
message_center_tray_->ToggleMessageCenterBubble();
}
void WebNotificationTrayWin::HideBubbleWithView(
const views::TrayBubbleView* bubble_view) {
if (message_center_bubble_.get() &&
bubble_view == message_center_bubble_->bubble_view()) {
message_center_tray_->HideMessageCenterBubble();
}
}
StatusIcon* WebNotificationTrayWin::GetStatusIcon() {
if (status_icon_)
return status_icon_;
StatusTray* status_tray = g_browser_process->status_tray();
if (!status_tray)
return NULL;
StatusIcon* status_icon = status_tray->CreateStatusIcon();
if (!status_icon)
return NULL;
status_icon_ = status_icon;
status_icon_->AddObserver(this);
AddQuietModeMenu(status_icon_);
return status_icon_;
}
void WebNotificationTrayWin::DestroyStatusIcon() {
if (!status_icon_)
return;
status_icon_->RemoveObserver(this);
StatusTray* status_tray = g_browser_process->status_tray();
if (status_tray)
status_tray->RemoveStatusIcon(status_icon_);
status_icon_ = NULL;
}
void WebNotificationTrayWin::AddQuietModeMenu(StatusIcon* status_icon) {
DCHECK(status_icon);
status_icon->SetContextMenu(message_center_tray_->CreateQuietModeMenu());
}
message_center::MessageCenterBubble*
WebNotificationTrayWin::GetMessageCenterBubbleForTest() {
if (!message_center_bubble_.get())
return NULL;
return static_cast<message_center::MessageCenterBubble*>(
message_center_bubble_->bubble());
}
} // namespace message_center
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file EthashGPUMiner.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*
* Determines the PoW algorithm.
*/
#if ETH_ETHASHCL || !ETH_TRUE
#include "EthashGPUMiner.h"
#include <thread>
#include <chrono>
#include <libethash-cl/ethash_cl_miner.h>
using namespace std;
using namespace dev;
using namespace eth;
namespace dev
{
namespace eth
{
class EthashCLHook: public ethash_cl_miner::search_hook
{
public:
EthashCLHook(EthashGPUMiner* _owner): m_owner(_owner) {}
EthashCLHook(EthashCLHook const&) = delete;
void abort()
{
{
UniqueGuard l(x_all);
if (m_aborted)
return;
// cdebug << "Attempting to abort";
m_abort = true;
}
// m_abort is true so now searched()/found() will return true to abort the search.
// we hang around on this thread waiting for them to point out that they have aborted since
// otherwise we may end up deleting this object prior to searched()/found() being called.
m_aborted.wait(true);
// for (unsigned timeout = 0; timeout < 100 && !m_aborted; ++timeout)
// std::this_thread::sleep_for(chrono::milliseconds(30));
// if (!m_aborted)
// cwarn << "Couldn't abort. Abandoning OpenCL process.";
}
void reset()
{
UniqueGuard l(x_all);
m_aborted = m_abort = false;
}
protected:
virtual bool found(uint64_t const* _nonces, uint32_t _count) override
{
// dev::operator <<(std::cerr << "Found nonces: ", vector<uint64_t>(_nonces, _nonces + _count)) << std::endl;
for (uint32_t i = 0; i < _count; ++i)
if (m_owner->report(_nonces[i]))
return (m_aborted = true);
return m_owner->shouldStop();
}
virtual bool searched(uint64_t _startNonce, uint32_t _count) override
{
UniqueGuard l(x_all);
// std::cerr << "Searched " << _count << " from " << _startNonce << std::endl;
m_owner->accumulateHashes(_count);
m_last = _startNonce + _count;
if (m_abort || m_owner->shouldStop())
return (m_aborted = true);
return false;
}
private:
Mutex x_all;
uint64_t m_last;
bool m_abort = false;
Notified<bool> m_aborted = {true};
EthashGPUMiner* m_owner = nullptr;
};
}
}
unsigned EthashGPUMiner::s_platformId = 0;
unsigned EthashGPUMiner::s_deviceId = 0;
unsigned EthashGPUMiner::s_numInstances = 0;
EthashGPUMiner::EthashGPUMiner(ConstructionInfo const& _ci):
GenericMiner<EthashProofOfWork>(_ci),
Worker("gpuminer" + toString(index())),
m_hook(new EthashCLHook(this))
{
}
EthashGPUMiner::~EthashGPUMiner()
{
pause();
delete m_miner;
delete m_hook;
}
bool EthashGPUMiner::report(uint64_t _nonce)
{
Nonce n = (Nonce)(u64)_nonce;
EthashProofOfWork::Result r = EthashAux::eval(work().seedHash, work().headerHash, n);
if (r.value < work().boundary)
return submitProof(Solution{n, r.mixHash});
return false;
}
void EthashGPUMiner::kickOff()
{
m_hook->reset();
startWorking();
}
void EthashGPUMiner::workLoop()
{
// take local copy of work since it may end up being overwritten by kickOff/pause.
try {
WorkPackage w = work();
cnote << "workLoop" << !!m_miner << m_minerSeed << w.seedHash;
if (!m_miner || m_minerSeed != w.seedHash)
{
cnote << "Initialising miner...";
m_minerSeed = w.seedHash;
delete m_miner;
m_miner = new ethash_cl_miner;
unsigned device = instances() > 1 ? index() : s_deviceId;
EthashAux::FullType dag;
while (true)
{
if ((dag = EthashAux::full(w.seedHash, true)))
break;
if (shouldStop())
{
delete m_miner;
m_miner = nullptr;
return;
}
cnote << "Awaiting DAG";
this_thread::sleep_for(chrono::milliseconds(500));
}
bytesConstRef dagData = dag->data();
m_miner->init(dagData.data(), dagData.size(), s_platformId, device);
}
uint64_t upper64OfBoundary = (uint64_t)(u64)((u256)w.boundary >> 192);
m_miner->search(w.headerHash.data(), upper64OfBoundary, *m_hook);
}
catch (cl::Error const& _e)
{
delete m_miner;
m_miner = nullptr;
cwarn << "Error GPU mining: " << _e.what() << "(" << _e.err() << ")";
}
}
void EthashGPUMiner::pause()
{
m_hook->abort();
stopWorking();
}
std::string EthashGPUMiner::platformInfo()
{
return ethash_cl_miner::platform_info(s_platformId, s_deviceId);
}
unsigned EthashGPUMiner::getNumDevices()
{
return ethash_cl_miner::getNumDevices(s_platformId);
}
void EthashGPUMiner::listDevices()
{
return ethash_cl_miner::listDevices();
}
bool EthashGPUMiner::configureGPU(
unsigned _localWorkSize,
unsigned _globalWorkSizeMultiplier,
unsigned _msPerBatch,
unsigned _platformId,
unsigned _deviceId,
bool _allowCPU,
unsigned _extraGPUMemory,
uint64_t _currentBlock
)
{
s_platformId = _platformId;
s_deviceId = _deviceId;
if (_localWorkSize != 32 && _localWorkSize != 64 && _localWorkSize != 128)
{
cout << "Given localWorkSize of " << toString(_localWorkSize) << "is invalid. Must be either 32,64, or 128" << endl;
return false;
}
if (!ethash_cl_miner::configureGPU(
_platformId,
_localWorkSize,
_globalWorkSizeMultiplier * _localWorkSize,
_msPerBatch,
_allowCPU,
_extraGPUMemory,
_currentBlock)
)
{
cout << "No GPU device with sufficient memory was found. Can't GPU mine. Remove the -G argument" << endl;
return false;
}
return true;
}
#endif
<commit_msg>update max workgroup size to allow 256<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file EthashGPUMiner.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*
* Determines the PoW algorithm.
*/
#if ETH_ETHASHCL || !ETH_TRUE
#include "EthashGPUMiner.h"
#include <thread>
#include <chrono>
#include <libethash-cl/ethash_cl_miner.h>
using namespace std;
using namespace dev;
using namespace eth;
namespace dev
{
namespace eth
{
class EthashCLHook: public ethash_cl_miner::search_hook
{
public:
EthashCLHook(EthashGPUMiner* _owner): m_owner(_owner) {}
EthashCLHook(EthashCLHook const&) = delete;
void abort()
{
{
UniqueGuard l(x_all);
if (m_aborted)
return;
// cdebug << "Attempting to abort";
m_abort = true;
}
// m_abort is true so now searched()/found() will return true to abort the search.
// we hang around on this thread waiting for them to point out that they have aborted since
// otherwise we may end up deleting this object prior to searched()/found() being called.
m_aborted.wait(true);
// for (unsigned timeout = 0; timeout < 100 && !m_aborted; ++timeout)
// std::this_thread::sleep_for(chrono::milliseconds(30));
// if (!m_aborted)
// cwarn << "Couldn't abort. Abandoning OpenCL process.";
}
void reset()
{
UniqueGuard l(x_all);
m_aborted = m_abort = false;
}
protected:
virtual bool found(uint64_t const* _nonces, uint32_t _count) override
{
// dev::operator <<(std::cerr << "Found nonces: ", vector<uint64_t>(_nonces, _nonces + _count)) << std::endl;
for (uint32_t i = 0; i < _count; ++i)
if (m_owner->report(_nonces[i]))
return (m_aborted = true);
return m_owner->shouldStop();
}
virtual bool searched(uint64_t _startNonce, uint32_t _count) override
{
UniqueGuard l(x_all);
// std::cerr << "Searched " << _count << " from " << _startNonce << std::endl;
m_owner->accumulateHashes(_count);
m_last = _startNonce + _count;
if (m_abort || m_owner->shouldStop())
return (m_aborted = true);
return false;
}
private:
Mutex x_all;
uint64_t m_last;
bool m_abort = false;
Notified<bool> m_aborted = {true};
EthashGPUMiner* m_owner = nullptr;
};
}
}
unsigned EthashGPUMiner::s_platformId = 0;
unsigned EthashGPUMiner::s_deviceId = 0;
unsigned EthashGPUMiner::s_numInstances = 0;
EthashGPUMiner::EthashGPUMiner(ConstructionInfo const& _ci):
GenericMiner<EthashProofOfWork>(_ci),
Worker("gpuminer" + toString(index())),
m_hook(new EthashCLHook(this))
{
}
EthashGPUMiner::~EthashGPUMiner()
{
pause();
delete m_miner;
delete m_hook;
}
bool EthashGPUMiner::report(uint64_t _nonce)
{
Nonce n = (Nonce)(u64)_nonce;
EthashProofOfWork::Result r = EthashAux::eval(work().seedHash, work().headerHash, n);
if (r.value < work().boundary)
return submitProof(Solution{n, r.mixHash});
return false;
}
void EthashGPUMiner::kickOff()
{
m_hook->reset();
startWorking();
}
void EthashGPUMiner::workLoop()
{
// take local copy of work since it may end up being overwritten by kickOff/pause.
try {
WorkPackage w = work();
cnote << "workLoop" << !!m_miner << m_minerSeed << w.seedHash;
if (!m_miner || m_minerSeed != w.seedHash)
{
cnote << "Initialising miner...";
m_minerSeed = w.seedHash;
delete m_miner;
m_miner = new ethash_cl_miner;
unsigned device = instances() > 1 ? index() : s_deviceId;
EthashAux::FullType dag;
while (true)
{
if ((dag = EthashAux::full(w.seedHash, true)))
break;
if (shouldStop())
{
delete m_miner;
m_miner = nullptr;
return;
}
cnote << "Awaiting DAG";
this_thread::sleep_for(chrono::milliseconds(500));
}
bytesConstRef dagData = dag->data();
m_miner->init(dagData.data(), dagData.size(), s_platformId, device);
}
uint64_t upper64OfBoundary = (uint64_t)(u64)((u256)w.boundary >> 192);
m_miner->search(w.headerHash.data(), upper64OfBoundary, *m_hook);
}
catch (cl::Error const& _e)
{
delete m_miner;
m_miner = nullptr;
cwarn << "Error GPU mining: " << _e.what() << "(" << _e.err() << ")";
}
}
void EthashGPUMiner::pause()
{
m_hook->abort();
stopWorking();
}
std::string EthashGPUMiner::platformInfo()
{
return ethash_cl_miner::platform_info(s_platformId, s_deviceId);
}
unsigned EthashGPUMiner::getNumDevices()
{
return ethash_cl_miner::getNumDevices(s_platformId);
}
void EthashGPUMiner::listDevices()
{
return ethash_cl_miner::listDevices();
}
bool EthashGPUMiner::configureGPU(
unsigned _localWorkSize,
unsigned _globalWorkSizeMultiplier,
unsigned _msPerBatch,
unsigned _platformId,
unsigned _deviceId,
bool _allowCPU,
unsigned _extraGPUMemory,
uint64_t _currentBlock
)
{
s_platformId = _platformId;
s_deviceId = _deviceId;
if (_localWorkSize != 32 && _localWorkSize != 64 && _localWorkSize != 128 && _localWorkSize != 256)
{
cout << "Given localWorkSize of " << toString(_localWorkSize) << "is invalid. Must be either 32,64, or 128" << endl;
return false;
}
if (!ethash_cl_miner::configureGPU(
_platformId,
_localWorkSize,
_globalWorkSizeMultiplier * _localWorkSize,
_msPerBatch,
_allowCPU,
_extraGPUMemory,
_currentBlock)
)
{
cout << "No GPU device with sufficient memory was found. Can't GPU mine. Remove the -G argument" << endl;
return false;
}
return true;
}
#endif
<|endoftext|> |
<commit_before>/*
Title: Multi-Threaded Garbage Collector - Update phase
Copyright (c) 2010 David C. J. Matthews
Based on the original garbage collector code
Copyright 2000-2008
Cambridge University Technical Services Limited
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
This is the third, update, phase of the garbage collector. The previous, copy,
phase will have moved cells in memory. The update phase goes through all cells
that could contain an address of a cell that has been moved and looks for a
tomb-stone that contains its new location.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#elif defined(WIN32)
#include "winconfig.h"
#else
#error "No configuration file"
#endif
#ifdef HAVE_ASSERT_H
#include <assert.h>
#define ASSERT(x) assert(x)
#else
#define ASSERT(x)
#endif
#include "globals.h"
#include "run_time.h"
#include "processes.h"
#include "gc.h"
#include "scanaddrs.h"
#include "check_objects.h"
#include "bitmap.h"
#include "memmgr.h"
#include "gctaskfarm.h"
#include "diagnostics.h"
inline POLYUNSIGNED BITNO(LocalMemSpace *area, PolyWord *pt) { return pt - area->bottom; }
class MTGCProcessUpdate: public ScanAddress
{
public:
virtual POLYUNSIGNED ScanAddressAt(PolyWord *pt);
virtual void ScanRuntimeAddress(PolyObject **pt, RtsStrength weak);
virtual PolyObject *ScanObjectAddress(PolyObject *base);
void UpdateObjectsInArea(LocalMemSpace *area);
};
/*********************************************************************/
/* This function is called in the update phase to update pointers to */
/* objects in the gc area that are in old mutable segments. */
/*********************************************************************/
PolyObject *MTGCProcessUpdate::ScanObjectAddress(PolyObject *obj)
{
PolyWord val = obj;
LocalMemSpace *space = gMem.LocalSpaceForAddress(val.AsStackAddr());
if (space != 0)
{
if (obj->ContainsForwardingPtr())
obj = obj->GetForwardingPtr();
else ASSERT(obj->ContainsNormalLengthWord());
CheckObject (obj);
}
return obj;
}
void MTGCProcessUpdate::ScanRuntimeAddress(PolyObject **pt, RtsStrength/* weak*/)
/* weak is not used, but needed so type of the function is correct */
{
PolyWord w = *pt;
LocalMemSpace *space = gMem.LocalSpaceForAddress(w.AsStackAddr());
if (space != 0)
{
PolyObject *obj = *pt;
if (obj->ContainsForwardingPtr())
*pt = obj->GetForwardingPtr();
else ASSERT(obj->ContainsNormalLengthWord()); /* SPF 24/1/95 */
CheckObject (*pt);
}
}
// Update the addresses in a group of words.
POLYUNSIGNED MTGCProcessUpdate::ScanAddressAt(PolyWord *pt)
{
PolyWord val = *pt;
Check (val);
if (val.IsTagged())
return 0;
// It looked like it would be possible to simplify this code and
// just call ContainsForwardingPtr on any address.
// Profiling shows that it's quite important to avoid calling
// ContainsForwardingPtr unnecessarily. I guess the reason is that
// it actually accesses the memory referenced by the address and it
// is unlikely to be in the cache.
LocalMemSpace *space = gMem.LocalSpaceForAddress(val.AsStackAddr());
if (space == 0)
return 0;
PolyObject *obj = val.AsObjPtr();
if (obj->ContainsForwardingPtr())
{
*pt = obj->GetForwardingPtr();
CheckObject (pt->AsObjPtr());
}
else
{
ASSERT(obj->ContainsNormalLengthWord());
CheckObject(obj);
}
return 0;
}
// Updates the addresses for objects in the area with the "allocated" bit set.
// It processes the area between area->pointer and the bit corresponding to area->highest.
// area->highest corresponds to gen_top i.e. we don't process older generations.
void MTGCProcessUpdate::UpdateObjectsInArea(LocalMemSpace *area)
{
PolyWord *pt = area->upperAllocPtr;
POLYUNSIGNED bitno = BITNO(area, pt);
POLYUNSIGNED highest = BITNO(area, area->top);
for (;;)
{
ASSERT(bitno <= highest); /* SPF */
/* Zero freed space. This is necessary for OpMutableBlock,
which expects the old mutable area to contain only
genuine objects, tombstones and zero words. This is
all rather sad, since zeroing the mutable buffer in
this manner may well be one of the hot-spots of the GC.
At least we only start at area->pointer, so we shouldn't
normally have to zap *too* much store.
SPF 22/10/96
*/
/*
The alternative, of making these dummy byte objects in which
case it is only the length word that needs to be set, didn't
seem to make any difference. The CPU is probably writing back
whole cache lines so setting the length word probably means
the whole cache line has to be written anyway. DCJM 2/6/06.
*/
while (bitno < highest && !area->bitmap.TestBit(bitno))
{
*pt++ = PolyWord::FromUnsigned(0);
bitno++;
}
if (bitno == highest) {
// Have reached the top of the area
ASSERT(pt == area->top);
break;
}
/* first set bit corresponds to the length word */
pt++;
PolyObject *obj = (PolyObject*)pt;
POLYUNSIGNED L = obj->LengthWord();
bitno++;
if (obj->ContainsForwardingPtr()) /* skip over moved object */
{
obj = obj->GetForwardingPtr();
ASSERT(obj->ContainsNormalLengthWord()); // Only one level of forwarding
CheckObject (obj);
POLYUNSIGNED length = obj->Length();
pt += length;
bitno += length;
}
else /* !OBJ_IS_POINTER(L) */
{
CheckObject (obj);
if (OBJ_IS_WORD_OBJECT(L))
{
POLYUNSIGNED length = OBJ_OBJECT_LENGTH(L);
area->updated += length+1;
while (length--)
{
PolyWord val = *pt;
Check (val);
if (! val.IsTagged() && val != PolyWord::FromUnsigned(0))
{
LocalMemSpace *space = gMem.LocalSpaceForAddress(val.AsAddress());
if (space != 0)
{
PolyObject *obj = val.AsObjPtr();
if (obj->ContainsForwardingPtr())
{
*pt = obj->GetForwardingPtr();
CheckObject (pt->AsObjPtr());
}
else
{
ASSERT(obj->ContainsNormalLengthWord());
CheckObject(obj);
}
}
}
pt++;
bitno++;
}
}
else /* !OBJ_IS_WORD_OBJECT(L) */
{
POLYUNSIGNED length = OBJ_OBJECT_LENGTH(L);
area->updated += length+1;
ScanAddressesInObject(obj, L);
pt += length;
bitno += length;
} /* !OBJ_IS_WORD_OBJECT(L) */
} /* !OBJ_IS_POINTER(L) */
} /* for loop */
// Clear the bitmaps ready for the next collection. Doing it now
// means we can avoid clearing more than we really need.
if (area->i_marked != 0 || area->m_marked != 0)
// We've marked something so we may have set a bit below the current pointer
area->bitmap.ClearBits(0, area->top - area->bottom);
else // Otherwise we only need to clear in the area we've newly allocated. This is
// the case when we're doing a partial collection and copying into the
// immutable area.
area->bitmap.ClearBits(area->upperAllocPtr - area->bottom, area->top - area->upperAllocPtr);
}
// Task to update addresses in a local area.
static void updateLocalArea(GCTaskId*, void *arg1, void *arg2)
{
MTGCProcessUpdate *processUpdate = (MTGCProcessUpdate *)arg1;
LocalMemSpace *space = (LocalMemSpace *)arg2;
if (debugOptions & DEBUG_GC)
Log("GC: Update local area %p\n", space);
// Process the current generation for mutable or immutable areas.
processUpdate->UpdateObjectsInArea(space);
if (debugOptions & DEBUG_GC)
Log("GC: Completed local update for %p. %lu words updated\n", space, space->updated);
}
// Task to update addresses in a non-local area.
static void updateNonLocalMutableArea(GCTaskId*, void *arg1, void *arg2)
{
MTGCProcessUpdate *processUpdate = (MTGCProcessUpdate *)arg1;
MemSpace *space = (MemSpace *)arg2;
if (debugOptions & DEBUG_GC)
Log("GC: Update non-local mutable area %p\n", space);
processUpdate->ScanAddressesInRegion(space->bottom, space->top);
if (debugOptions & DEBUG_GC)
Log("GC: Completed non-local mutable update for %p\n", space);
}
// Task to update addresses maintained by the RTS itself.
static void updateGCProcAddresses(GCTaskId*, void *arg1, void *)
{
MTGCProcessUpdate *processUpdate = (MTGCProcessUpdate *)arg1;
GCModules(processUpdate);
}
void GCUpdatePhase()
{
unsigned j;
/* Update phase */
mainThreadPhase = MTP_GCPHASEUPDATE;
/* Invariant: at most the first (gen_top - bottom) bits of each bitmap can be dirty here. */
for(j = 0; j < gMem.nlSpaces; j++)
gMem.lSpaces[j]->updated = 0;
// We can do the updates in parallel since they don't interfere at all.
MTGCProcessUpdate processUpdate;
// Process local areas.
for (j = 0; j < gMem.nlSpaces; j++)
{
LocalMemSpace *space = gMem.lSpaces[j];
// As well as updating the addresses this also clears the bitmaps.
gpTaskFarm->AddWorkOrRunNow(&updateLocalArea, &processUpdate, space);
}
// Scan the permanent mutable areas.
for (j = 0; j < gMem.npSpaces; j++)
{
MemSpace *space = gMem.pSpaces[j];
if (space->isMutable)
gpTaskFarm->AddWorkOrRunNow(&updateNonLocalMutableArea, &processUpdate, space);
}
// Update addresses in RTS modules.
gpTaskFarm->AddWorkOrRunNow(&updateGCProcAddresses, &processUpdate, 0);
// Wait for these to complete before proceeding.
gpTaskFarm->WaitForCompletion();
}
<commit_msg>Allow for the possibility of objects being moved more than once within a GC. This shouldn't really happen but appears to occur in rare circumstances.<commit_after>/*
Title: Multi-Threaded Garbage Collector - Update phase
Copyright (c) 2010, 2011 David C. J. Matthews
Based on the original garbage collector code
Copyright 2000-2008
Cambridge University Technical Services Limited
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
This is the third, update, phase of the garbage collector. The previous, copy,
phase will have moved cells in memory. The update phase goes through all cells
that could contain an address of a cell that has been moved and looks for a
tomb-stone that contains its new location.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#elif defined(WIN32)
#include "winconfig.h"
#else
#error "No configuration file"
#endif
#ifdef HAVE_ASSERT_H
#include <assert.h>
#define ASSERT(x) assert(x)
#else
#define ASSERT(x)
#endif
#include "globals.h"
#include "run_time.h"
#include "processes.h"
#include "gc.h"
#include "scanaddrs.h"
#include "check_objects.h"
#include "bitmap.h"
#include "memmgr.h"
#include "gctaskfarm.h"
#include "diagnostics.h"
inline POLYUNSIGNED BITNO(LocalMemSpace *area, PolyWord *pt) { return pt - area->bottom; }
class MTGCProcessUpdate: public ScanAddress
{
public:
virtual POLYUNSIGNED ScanAddressAt(PolyWord *pt);
virtual void ScanRuntimeAddress(PolyObject **pt, RtsStrength weak);
virtual PolyObject *ScanObjectAddress(PolyObject *base);
void UpdateObjectsInArea(LocalMemSpace *area);
};
/*********************************************************************/
/* This function is called in the update phase to update pointers to */
/* objects in the gc area that are in old mutable segments. */
/*********************************************************************/
PolyObject *MTGCProcessUpdate::ScanObjectAddress(PolyObject *obj)
{
PolyWord val = obj;
LocalMemSpace *space = gMem.LocalSpaceForAddress(val.AsStackAddr());
if (space != 0)
{
if (obj->ContainsForwardingPtr())
obj = obj->GetForwardingPtr();
else ASSERT(obj->ContainsNormalLengthWord());
CheckObject (obj);
}
return obj;
}
void MTGCProcessUpdate::ScanRuntimeAddress(PolyObject **pt, RtsStrength/* weak*/)
/* weak is not used, but needed so type of the function is correct */
{
PolyWord w = *pt;
LocalMemSpace *space = gMem.LocalSpaceForAddress(w.AsStackAddr());
if (space != 0)
{
PolyObject *obj = *pt;
if (obj->ContainsForwardingPtr())
*pt = obj->GetForwardingPtr();
else ASSERT(obj->ContainsNormalLengthWord()); /* SPF 24/1/95 */
CheckObject (*pt);
}
}
// Update the addresses in a group of words.
POLYUNSIGNED MTGCProcessUpdate::ScanAddressAt(PolyWord *pt)
{
PolyWord val = *pt;
Check (val);
if (val.IsTagged())
return 0;
// It looked like it would be possible to simplify this code and
// just call ContainsForwardingPtr on any address.
// Profiling shows that it's quite important to avoid calling
// ContainsForwardingPtr unnecessarily. I guess the reason is that
// it actually accesses the memory referenced by the address and it
// is unlikely to be in the cache.
LocalMemSpace *space = gMem.LocalSpaceForAddress(val.AsStackAddr());
if (space == 0)
return 0;
PolyObject *obj = val.AsObjPtr();
if (obj->ContainsForwardingPtr())
{
*pt = obj->GetForwardingPtr();
CheckObject (pt->AsObjPtr());
}
else
{
ASSERT(obj->ContainsNormalLengthWord());
CheckObject(obj);
}
return 0;
}
// Updates the addresses for objects in the area with the "allocated" bit set.
// It processes the area between area->pointer and the bit corresponding to area->highest.
// area->highest corresponds to gen_top i.e. we don't process older generations.
void MTGCProcessUpdate::UpdateObjectsInArea(LocalMemSpace *area)
{
PolyWord *pt = area->upperAllocPtr;
POLYUNSIGNED bitno = BITNO(area, pt);
POLYUNSIGNED highest = BITNO(area, area->top);
for (;;)
{
ASSERT(bitno <= highest); /* SPF */
/* Zero freed space. This is necessary for OpMutableBlock,
which expects the old mutable area to contain only
genuine objects, tombstones and zero words. This is
all rather sad, since zeroing the mutable buffer in
this manner may well be one of the hot-spots of the GC.
At least we only start at area->pointer, so we shouldn't
normally have to zap *too* much store.
SPF 22/10/96
*/
/*
The alternative, of making these dummy byte objects in which
case it is only the length word that needs to be set, didn't
seem to make any difference. The CPU is probably writing back
whole cache lines so setting the length word probably means
the whole cache line has to be written anyway. DCJM 2/6/06.
*/
while (bitno < highest && !area->bitmap.TestBit(bitno))
{
*pt++ = PolyWord::FromUnsigned(0);
bitno++;
}
if (bitno == highest) {
// Have reached the top of the area
ASSERT(pt == area->top);
break;
}
/* first set bit corresponds to the length word */
pt++;
PolyObject *obj = (PolyObject*)pt;
POLYUNSIGNED L = obj->LengthWord();
bitno++;
if (obj->ContainsForwardingPtr())
{
// Skip over moved objects. We have to find the new location to find
// its length.
// This previously allowed for only one level of forwarding i.e.
// an object will only have been moved once.
// Makarius reported that the assertion to that effect sometimes
// failed with multi-threading enabled so we'll allow for the
// possibility of more than one level.
while (obj->ContainsForwardingPtr())
obj = obj->GetForwardingPtr();
CheckObject (obj);
POLYUNSIGNED length = obj->Length();
pt += length;
bitno += length;
}
else /* !OBJ_IS_POINTER(L) */
{
CheckObject (obj);
if (OBJ_IS_WORD_OBJECT(L))
{
POLYUNSIGNED length = OBJ_OBJECT_LENGTH(L);
area->updated += length+1;
while (length--)
{
PolyWord val = *pt;
Check (val);
if (! val.IsTagged() && val != PolyWord::FromUnsigned(0))
{
LocalMemSpace *space = gMem.LocalSpaceForAddress(val.AsAddress());
if (space != 0)
{
PolyObject *obj = val.AsObjPtr();
if (obj->ContainsForwardingPtr())
{
*pt = obj->GetForwardingPtr();
CheckObject (pt->AsObjPtr());
}
else
{
ASSERT(obj->ContainsNormalLengthWord());
CheckObject(obj);
}
}
}
pt++;
bitno++;
}
}
else /* !OBJ_IS_WORD_OBJECT(L) */
{
POLYUNSIGNED length = OBJ_OBJECT_LENGTH(L);
area->updated += length+1;
ScanAddressesInObject(obj, L);
pt += length;
bitno += length;
} /* !OBJ_IS_WORD_OBJECT(L) */
} /* !OBJ_IS_POINTER(L) */
} /* for loop */
// Clear the bitmaps ready for the next collection. Doing it now
// means we can avoid clearing more than we really need.
if (area->i_marked != 0 || area->m_marked != 0)
// We've marked something so we may have set a bit below the current pointer
area->bitmap.ClearBits(0, area->top - area->bottom);
else // Otherwise we only need to clear in the area we've newly allocated. This is
// the case when we're doing a partial collection and copying into the
// immutable area.
area->bitmap.ClearBits(area->upperAllocPtr - area->bottom, area->top - area->upperAllocPtr);
}
// Task to update addresses in a local area.
static void updateLocalArea(GCTaskId*, void *arg1, void *arg2)
{
MTGCProcessUpdate *processUpdate = (MTGCProcessUpdate *)arg1;
LocalMemSpace *space = (LocalMemSpace *)arg2;
if (debugOptions & DEBUG_GC)
Log("GC: Update local area %p\n", space);
// Process the current generation for mutable or immutable areas.
processUpdate->UpdateObjectsInArea(space);
if (debugOptions & DEBUG_GC)
Log("GC: Completed local update for %p. %lu words updated\n", space, space->updated);
}
// Task to update addresses in a non-local area.
static void updateNonLocalMutableArea(GCTaskId*, void *arg1, void *arg2)
{
MTGCProcessUpdate *processUpdate = (MTGCProcessUpdate *)arg1;
MemSpace *space = (MemSpace *)arg2;
if (debugOptions & DEBUG_GC)
Log("GC: Update non-local mutable area %p\n", space);
processUpdate->ScanAddressesInRegion(space->bottom, space->top);
if (debugOptions & DEBUG_GC)
Log("GC: Completed non-local mutable update for %p\n", space);
}
// Task to update addresses maintained by the RTS itself.
static void updateGCProcAddresses(GCTaskId*, void *arg1, void *)
{
MTGCProcessUpdate *processUpdate = (MTGCProcessUpdate *)arg1;
GCModules(processUpdate);
}
void GCUpdatePhase()
{
unsigned j;
/* Update phase */
mainThreadPhase = MTP_GCPHASEUPDATE;
/* Invariant: at most the first (gen_top - bottom) bits of each bitmap can be dirty here. */
for(j = 0; j < gMem.nlSpaces; j++)
gMem.lSpaces[j]->updated = 0;
// We can do the updates in parallel since they don't interfere at all.
MTGCProcessUpdate processUpdate;
// Process local areas.
for (j = 0; j < gMem.nlSpaces; j++)
{
LocalMemSpace *space = gMem.lSpaces[j];
// As well as updating the addresses this also clears the bitmaps.
gpTaskFarm->AddWorkOrRunNow(&updateLocalArea, &processUpdate, space);
}
// Scan the permanent mutable areas.
for (j = 0; j < gMem.npSpaces; j++)
{
MemSpace *space = gMem.pSpaces[j];
if (space->isMutable)
gpTaskFarm->AddWorkOrRunNow(&updateNonLocalMutableArea, &processUpdate, space);
}
// Update addresses in RTS modules.
gpTaskFarm->AddWorkOrRunNow(&updateGCProcAddresses, &processUpdate, 0);
// Wait for these to complete before proceeding.
gpTaskFarm->WaitForCompletion();
}
<|endoftext|> |
<commit_before>/*
* 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.
*
* Written (W) 2012 Heiko Strathmann
* Copyright (C) 2012 Berlin Institute of Technology and Max-Planck-Society
*/
#include <shogun/evaluation/MeanSquaredLogError.h>
#include <shogun/features/Labels.h>
#include <shogun/mathematics/Math.h>
using namespace shogun;
float64_t CMeanSquaredLogError::evaluate(CLabels* predicted, CLabels* ground_truth)
{
ASSERT(predicted->get_num_labels()==ground_truth->get_num_labels());
int32_t length=predicted->get_num_labels();
float64_t msle=0.0;
for (int32_t i=0; i<length; i++)
{
float64_t prediction=predicted->get_label(i);
float64_t truth=ground_truth->get_label(i);
if (prediction<=-1.0 || truth<=-1.0)
SG_ERROR("Negative label[%d] in %s is not allowed!\n", i, get_name());
float64_t a=CMath::log(prediction+1);
float64_t b=CMath::log(truth+1);
msle+=CMath::sq(a-b);
}
msle /= length;
return CMath::sqrt(msle);
}
<commit_msg>changed error to warning<commit_after>/*
* 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.
*
* Written (W) 2012 Heiko Strathmann
* Copyright (C) 2012 Berlin Institute of Technology and Max-Planck-Society
*/
#include <shogun/evaluation/MeanSquaredLogError.h>
#include <shogun/features/Labels.h>
#include <shogun/mathematics/Math.h>
using namespace shogun;
float64_t CMeanSquaredLogError::evaluate(CLabels* predicted, CLabels* ground_truth)
{
ASSERT(predicted->get_num_labels()==ground_truth->get_num_labels());
int32_t length=predicted->get_num_labels();
float64_t msle=0.0;
for (int32_t i=0; i<length; i++)
{
float64_t prediction=predicted->get_label(i);
float64_t truth=ground_truth->get_label(i);
if (prediction<=-1.0 || truth<=-1.0)
{
SG_WARNING("Negative label[%d] in %s is not allowed, ignoring!\n",
i, get_name());
continue;
}
float64_t a=CMath::log(prediction+1);
float64_t b=CMath::log(truth+1);
msle+=CMath::sq(a-b);
}
msle /= length;
return CMath::sqrt(msle);
}
<|endoftext|> |
<commit_before>/**
* @file ILI9341.cpp
* @version 1.0
*
* @section License
* Copyright (C) 2015, Mikael Patel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* This file is part of the Arduino Che Cosa project.
*/
#include "ILI9341.hh"
const uint8_t ILI9341::script[] __PROGMEM = {
// Software Reset
SWRESET, 0,
// Software Delay
SWDELAY, 250,
// Power Control A
// Vcore = 1.6 V, DDVDH = 5.6 V
PWCTRLA, 5, 0x39, 0x2C, 0x00, 0x34, 0x02,
// Power Control B
// PCEQ enable
PWCTRLB, 3, 0x00, 0xC1, 0x30,
// Driver Timing Control A
// Internal clock -1, EQ -1, CR -1, Pre-Charge -2
DTCTRLA, 3, 0x85, 0x00, 0x78,
// Driver Timing Control B
// External clock 0, EQE -1, CRE -1, Pre-Charge -2
DTCTRLB, 2, 0x00, 0x00,
// Power On Sequence Control
// Soft start keep 1 frame
// 1st frame enable
// DDVHDH enhanced mode enable
PWONCTRL, 4, 0x64, 0x03, 0X12, 0X81,
// Pump Ratio Control
// DDVDH = 2xVCI
PRCTRL, 1, 0x20,
// Power Control 1
// GVDD = 4.60 V
PWCTRL1, 1, 0x23,
// Power Control 2
PWCTRL2, 1, 0x10,
// VCOM Control 1
// VCOMH = 4.250 V
// VCOML = -1.5 V
VMCTRL1, 2, 0x3e, 0x28,
// VCOM Control 2
// VCOMH = VMH - 58
// VCOML = VMH - 58
VMCTRL2, 1, 0x86,
// Memory Data Access Control
// Column Address Order (MX), BGR Order
MADCTL, 1, 0x48,
// Pixel Format Set
// RGB 16-bits, MCU 16-bits
PIXSET, 1, 0x55,
// Frame Rate Control
// Division Ratio = fosc / 1
// Frame Rate = 79 Hz
FRMCTR1, 2, 0x00, 0x18,
// Display Function Control
// Interval scan, V63, V0, VCOML, VCOMH
DISCTRL, 3, 0x08, 0x82, 0x27,
// Disable 3-Gamma
EN3GAM, 1, 0x00,
// Gamma Set
// Gamma curve 1
GAMSET, 1, 0x01,
// Positive Gamma Correction
PGAMCTRL, 15,
0x0F, 0x31, 0x2B, 0x0C, 0x0E,
0x08, 0x4E, 0xF1, 0x37, 0x07,
0x10, 0x03, 0x0E, 0x09, 0x00,
// Negative Gamma Correction
NGAMCTRL, 15,
0x00, 0x0E, 0x14, 0x03, 0x11,
0x07, 0x31, 0xC1, 0x48, 0x08,
0x0F, 0x0C, 0x31, 0x36, 0x0F,
// Exit Sleep Mode
SLPOUT, 0,
// Software Delay
SWDELAY, 120,
// Display On
DISPON, 0,
// END OF SCRIPT
SCRIPTEND
};
ILI9341::ILI9341(Board::DigitalPin cs, Board::DigitalPin dc) :
GDDRAM(SCREEN_WIDTH, SCREEN_HEIGHT, cs, dc)
{
}
<commit_msg>Fixed static init script.<commit_after>/**
* @file ILI9341.cpp
* @version 1.0
*
* @section License
* Copyright (C) 2015, Mikael Patel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* This file is part of the Arduino Che Cosa project.
*/
#include "ILI9341.hh"
const uint8_t ILI9341::s_script[] __PROGMEM = {
// Software Reset
SWRESET, 0,
// Software Delay
SWDELAY, 250,
// Power Control A
// Vcore = 1.6 V, DDVDH = 5.6 V
PWCTRLA, 5, 0x39, 0x2C, 0x00, 0x34, 0x02,
// Power Control B
// PCEQ enable
PWCTRLB, 3, 0x00, 0xC1, 0x30,
// Driver Timing Control A
// Internal clock -1, EQ -1, CR -1, Pre-Charge -2
DTCTRLA, 3, 0x85, 0x00, 0x78,
// Driver Timing Control B
// External clock 0, EQE -1, CRE -1, Pre-Charge -2
DTCTRLB, 2, 0x00, 0x00,
// Power On Sequence Control
// Soft start keep 1 frame
// 1st frame enable
// DDVHDH enhanced mode enable
PWONCTRL, 4, 0x64, 0x03, 0X12, 0X81,
// Pump Ratio Control
// DDVDH = 2xVCI
PRCTRL, 1, 0x20,
// Power Control 1
// GVDD = 4.60 V
PWCTRL1, 1, 0x23,
// Power Control 2
PWCTRL2, 1, 0x10,
// VCOM Control 1
// VCOMH = 4.250 V
// VCOML = -1.5 V
VMCTRL1, 2, 0x3e, 0x28,
// VCOM Control 2
// VCOMH = VMH - 58
// VCOML = VMH - 58
VMCTRL2, 1, 0x86,
// Memory Data Access Control
// Column Address Order (MX), BGR Order
MADCTL, 1, 0x48,
// Pixel Format Set
// RGB 16-bits, MCU 16-bits
PIXSET, 1, 0x55,
// Frame Rate Control
// Division Ratio = fosc / 1
// Frame Rate = 79 Hz
FRMCTR1, 2, 0x00, 0x18,
// Display Function Control
// Interval scan, V63, V0, VCOML, VCOMH
DISCTRL, 3, 0x08, 0x82, 0x27,
// Disable 3-Gamma
EN3GAM, 1, 0x00,
// Gamma Set
// Gamma curve 1
GAMSET, 1, 0x01,
// Positive Gamma Correction
PGAMCTRL, 15,
0x0F, 0x31, 0x2B, 0x0C, 0x0E,
0x08, 0x4E, 0xF1, 0x37, 0x07,
0x10, 0x03, 0x0E, 0x09, 0x00,
// Negative Gamma Correction
NGAMCTRL, 15,
0x00, 0x0E, 0x14, 0x03, 0x11,
0x07, 0x31, 0xC1, 0x48, 0x08,
0x0F, 0x0C, 0x31, 0x36, 0x0F,
// Exit Sleep Mode
SLPOUT, 0,
// Software Delay
SWDELAY, 120,
// Display On
DISPON, 0,
// END OF SCRIPT
SCRIPTEND
};
ILI9341::ILI9341(Board::DigitalPin cs, Board::DigitalPin dc) :
GDDRAM(SCREEN_WIDTH, SCREEN_HEIGHT, cs, dc)
{
}
<|endoftext|> |
<commit_before>#ifndef RDB_PROTOCOL_CONFIGURED_LIMITS_HPP_
#define RDB_PROTOCOL_CONFIGURED_LIMITS_HPP_
#include <map>
#include <string>
namespace ql {
class wire_func_t;
class configured_limits_t {
public:
configured_limits_t() : _array_size_limit(100000) {}
explicit configured_limits_t(const size_t limit) : _array_size_limit(limit) {}
size_t array_size_limit() const { return _array_size_limit; }
private:
const size_t _array_size_limit;
};
configured_limits_t from_optargs(const std::map<std::string, wire_func_t> &optargs);
} // namespace ql
#endif
<commit_msg>Fix otherwise inexplicable compile errors by making this field nonconst<commit_after>#ifndef RDB_PROTOCOL_CONFIGURED_LIMITS_HPP_
#define RDB_PROTOCOL_CONFIGURED_LIMITS_HPP_
#include <map>
#include <string>
namespace ql {
class wire_func_t;
class configured_limits_t {
public:
configured_limits_t() : _array_size_limit(100000) {}
explicit configured_limits_t(const size_t limit) : _array_size_limit(limit) {}
size_t array_size_limit() const { return _array_size_limit; }
private:
size_t _array_size_limit;
};
configured_limits_t from_optargs(const std::map<std::string, wire_func_t> &optargs);
} // namespace ql
#endif
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.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. */
/* -------------------------------------------------------------------------- */
#include "RequestManagerPoolInfoFilter.h"
using namespace std;
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
const int RequestManagerPoolInfoFilter::ALL = -2;
const int RequestManagerPoolInfoFilter::MINE = -3;
const int RequestManagerPoolInfoFilter::MINE_GROUP = -1;
/* ------------------------------------------------------------------------- */
const int VirtualMachinePoolInfo::ALL_VM = -2;
const int VirtualMachinePoolInfo::NOT_DONE = -1;
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
void RequestManagerPoolInfoFilter::request_execute(
xmlrpc_c::paramList const& paramList,
RequestAttributes& att)
{
int filter_flag = xmlrpc_c::value_int(paramList.getInt(1));
int start_id = xmlrpc_c::value_int(paramList.getInt(2));
int end_id = xmlrpc_c::value_int(paramList.getInt(3));
set<int>::iterator it;
ostringstream oss;
bool empty = true;
ostringstream where_string;
ostringstream uid_filter;
ostringstream state_filter;
ostringstream id_filter;
string uid_str;
string state_str;
string id_str;
int rc;
AuthRequest::Operation request_op;
// ------------------------------------------
// User ID filter
// ------------------------------------------
if ( filter_flag < MINE )
{
failure_response(XML_RPC_API,
request_error("Incorrect filter_flag",""),
att);
return;
}
Nebula& nd = Nebula::instance();
AclManager* aclm = nd.get_aclm();
bool all;
vector<int> oids;
vector<int> gids;
switch(filter_flag)
{
case MINE:
uid_filter << "uid = " << att.uid;
request_op = AuthRequest::INFO_POOL_MINE;
break;
case ALL:
request_op = AuthRequest::INFO_POOL;
break;
case MINE_GROUP:
if ( att.uid == 0 || att.gid == 0 )
{
all = true;
}
else
{
aclm->reverse_search(att.uid, att.gid, auth_object,
AuthRequest::INFO, all, oids, gids);
}
if ( !all ) // If all == true, there is not a uid or gid restriction
{
vector<int>::iterator it;
// Default rights: Users can see and use their resources, and
// the public ones in their group
uid_filter << "uid = " << att.uid << " OR ";
// VMs don't have public column
if ( auth_object == AuthRequest::VM )
{
uid_filter << "gid = " << att.gid;
}
else
{
uid_filter << "(gid = " << att.gid << " AND public = 1)";
}
for ( it=oids.begin(); it< oids.end(); it++ )
{
uid_filter << " OR uid = " << *it;
}
for ( it=gids.begin(); it< gids.end(); it++ )
{
uid_filter << " OR gid = " << *it;
}
}
request_op = AuthRequest::INFO_POOL_MINE;
break;
default:
uid_filter << "uid = " << filter_flag;
request_op = AuthRequest::INFO_POOL;
break;
}
uid_str = uid_filter.str();
// ------------------------------------------
// Resource ID filter
// ------------------------------------------
if ( start_id != -1 )
{
id_filter << "oid >= " << start_id;
if ( end_id != -1 )
{
id_filter << " AND oid <= " << end_id;
}
}
id_str = id_filter.str();
// ------------ State filter for VM --------------
if ( auth_object == AuthRequest::VM )
{
int state = xmlrpc_c::value_int(paramList.getInt(4));
if (( state < VirtualMachinePoolInfo::ALL_VM ) ||
( state > VirtualMachine::FAILED ))
{
failure_response(XML_RPC_API,
request_error("Incorrect filter_flag, state",""),
att);
return;
}
switch(state)
{
case VirtualMachinePoolInfo::ALL_VM:
break;
case VirtualMachinePoolInfo::NOT_DONE:
state_filter << "state <> " << VirtualMachine::DONE;
break;
default:
state_filter << "state = " << state;
break;
}
}
state_str = state_filter.str();
// ------------------------------------------
// Compound WHERE clause
// ------------------------------------------
if (!uid_str.empty())
{
where_string << "(" << uid_str << ")" ;
empty = false;
}
if (!id_str.empty())
{
if (!empty)
{
where_string << " AND ";
}
where_string << "(" << id_str << ")";
empty = false;
}
if (!state_str.empty())
{
if (!empty)
{
where_string << " AND ";
}
where_string << "(" << state_str << ")";
}
// ------------------------------------------
// Authorize & get the pool
// ------------------------------------------
if ( basic_authorization(-1, request_op, att) == false )
{
return;
}
rc = pool->dump(oss,where_string.str());
if ( rc != 0 )
{
failure_response(INTERNAL,request_error("Internal Error",""), att);
return;
}
success_response(oss.str(), att);
return;
}
<commit_msg>Feature #862: Make VMs private. VMs from the same group don't show in 'onevm list g' by default. This behaviour can be changed with an ACL rule similar to this one: "@1 VM/@1 INFO"<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.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. */
/* -------------------------------------------------------------------------- */
#include "RequestManagerPoolInfoFilter.h"
using namespace std;
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
const int RequestManagerPoolInfoFilter::ALL = -2;
const int RequestManagerPoolInfoFilter::MINE = -3;
const int RequestManagerPoolInfoFilter::MINE_GROUP = -1;
/* ------------------------------------------------------------------------- */
const int VirtualMachinePoolInfo::ALL_VM = -2;
const int VirtualMachinePoolInfo::NOT_DONE = -1;
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
void RequestManagerPoolInfoFilter::request_execute(
xmlrpc_c::paramList const& paramList,
RequestAttributes& att)
{
int filter_flag = xmlrpc_c::value_int(paramList.getInt(1));
int start_id = xmlrpc_c::value_int(paramList.getInt(2));
int end_id = xmlrpc_c::value_int(paramList.getInt(3));
set<int>::iterator it;
ostringstream oss;
bool empty = true;
ostringstream where_string;
ostringstream uid_filter;
ostringstream state_filter;
ostringstream id_filter;
string uid_str;
string state_str;
string id_str;
int rc;
AuthRequest::Operation request_op;
// ------------------------------------------
// User ID filter
// ------------------------------------------
if ( filter_flag < MINE )
{
failure_response(XML_RPC_API,
request_error("Incorrect filter_flag",""),
att);
return;
}
Nebula& nd = Nebula::instance();
AclManager* aclm = nd.get_aclm();
bool all;
vector<int> oids;
vector<int> gids;
switch(filter_flag)
{
case MINE:
uid_filter << "uid = " << att.uid;
request_op = AuthRequest::INFO_POOL_MINE;
break;
case ALL:
request_op = AuthRequest::INFO_POOL;
break;
case MINE_GROUP:
if ( att.uid == 0 || att.gid == 0 )
{
all = true;
}
else
{
aclm->reverse_search(att.uid, att.gid, auth_object,
AuthRequest::INFO, all, oids, gids);
}
if ( !all ) // If all == true, there is not a uid or gid restriction
{
vector<int>::iterator it;
// Default rights: Users can see and use their resources, and
// the public ones in their group
uid_filter << "uid = " << att.uid;
// VMs don't have public column, are considered private
if ( auth_object != AuthRequest::VM )
{
uid_filter << " OR (gid = " << att.gid << " AND public = 1)";
}
for ( it=oids.begin(); it< oids.end(); it++ )
{
uid_filter << " OR uid = " << *it;
}
for ( it=gids.begin(); it< gids.end(); it++ )
{
uid_filter << " OR gid = " << *it;
}
}
request_op = AuthRequest::INFO_POOL_MINE;
break;
default:
uid_filter << "uid = " << filter_flag;
request_op = AuthRequest::INFO_POOL;
break;
}
uid_str = uid_filter.str();
// ------------------------------------------
// Resource ID filter
// ------------------------------------------
if ( start_id != -1 )
{
id_filter << "oid >= " << start_id;
if ( end_id != -1 )
{
id_filter << " AND oid <= " << end_id;
}
}
id_str = id_filter.str();
// ------------ State filter for VM --------------
if ( auth_object == AuthRequest::VM )
{
int state = xmlrpc_c::value_int(paramList.getInt(4));
if (( state < VirtualMachinePoolInfo::ALL_VM ) ||
( state > VirtualMachine::FAILED ))
{
failure_response(XML_RPC_API,
request_error("Incorrect filter_flag, state",""),
att);
return;
}
switch(state)
{
case VirtualMachinePoolInfo::ALL_VM:
break;
case VirtualMachinePoolInfo::NOT_DONE:
state_filter << "state <> " << VirtualMachine::DONE;
break;
default:
state_filter << "state = " << state;
break;
}
}
state_str = state_filter.str();
// ------------------------------------------
// Compound WHERE clause
// ------------------------------------------
if (!uid_str.empty())
{
where_string << "(" << uid_str << ")" ;
empty = false;
}
if (!id_str.empty())
{
if (!empty)
{
where_string << " AND ";
}
where_string << "(" << id_str << ")";
empty = false;
}
if (!state_str.empty())
{
if (!empty)
{
where_string << " AND ";
}
where_string << "(" << state_str << ")";
}
// ------------------------------------------
// Authorize & get the pool
// ------------------------------------------
if ( basic_authorization(-1, request_op, att) == false )
{
return;
}
rc = pool->dump(oss,where_string.str());
if ( rc != 0 )
{
failure_response(INTERNAL,request_error("Internal Error",""), att);
return;
}
success_response(oss.str(), att);
return;
}
<|endoftext|> |
<commit_before>// This file is part of the AliceVision project and is made available under
// the terms of the MPL2 license (see the COPYING.md file).
#include <aliceVision/feature/imageDescriberCommon.hpp>
#include <aliceVision/sfm/sfm.hpp>
#include <aliceVision/sfm/pipeline/regionsIO.hpp>
#include <aliceVision/system/Timer.hpp>
#include <aliceVision/system/Logger.hpp>
#include <aliceVision/system/cmdline.hpp>
#include <dependencies/stlplus3/filesystemSimplified/file_system.hpp>
#include <boost/program_options.hpp>
#include <cstdlib>
using namespace aliceVision;
using namespace aliceVision::camera;
using namespace aliceVision::sfm;
using namespace aliceVision::feature;
using namespace std;
namespace po = boost::program_options;
/**
* @brief Retrieve the view id in the sfmData from the image filename.
*
* @param[in] sfm_data the SfM scene
* @param[in] initialName the image name to find (filename or path)
* @param[out] out_viewId the id found
* @return if a view is found
*/
bool retrieveViewIdFromImageName(
const SfMData & sfm_data,
const std::string& initialName,
IndexT& out_viewId)
{
out_viewId = UndefinedIndexT;
bool isName = (initialName == stlplus::filename_part(initialName));
/// List views filenames and find the one that correspond to the user ones:
for(Views::const_iterator it = sfm_data.GetViews().begin();
it != sfm_data.GetViews().end(); ++it)
{
const View * v = it->second.get();
std::string filename;
if(isName)
{
filename = stlplus::filename_part(v->getImagePath());
}
else
{
if(stlplus::is_full_path(v->getImagePath()))
{
filename = v->getImagePath();
}
else
{
filename = sfm_data.s_root_path + v->getImagePath();
}
}
if (filename == initialName)
{
if(out_viewId == UndefinedIndexT)
{
out_viewId = v->getViewId();
}
else
{
std::cout<<"Error: Two pictures named :" << initialName << " !" << std::endl;
}
}
}
return out_viewId != UndefinedIndexT;
}
int main(int argc, char **argv)
{
// command-line parameters
std::string verboseLevel = system::EVerboseLevel_enumToString(system::Logger::getDefaultVerboseLevel());
std::string sfmDataFilename;
std::string featuresDirectory;
std::string matchesDirectory;
std::string outDirectory;
// user optional parameters
std::string outSfMDataFilename = "SfmData.json";
std::string describerTypesName = feature::EImageDescriberType_enumToString(feature::EImageDescriberType::SIFT);
std::string outInterFileExtension = ".ply";
std::pair<std::string,std::string> initialPairString("","");
int minInputTrackLength = 2;
int userCameraModel = static_cast<int>(PINHOLE_CAMERA_RADIAL3);
bool refineIntrinsics = true;
bool allowUserInteraction = true;
po::options_description allParams(
"Sequential/Incremental reconstruction\n"
"Perform incremental SfM (Initial Pair Essential + Resection)\n"
"AliceVision incrementalSfM");
po::options_description requiredParams("Required parameters");
requiredParams.add_options()
("input,i", po::value<std::string>(&sfmDataFilename)->required(),
"SfMData file.")
("output,o", po::value<std::string>(&outDirectory)->required(),
"Path of the output directory.")
("featuresDirectory,f", po::value<std::string>(&featuresDirectory)->required(),
"Path to a directory containing the extracted features.")
("matchesDirectory,m", po::value<std::string>(&matchesDirectory)->required(),
"Path to a directory in which computed matches are stored.");
po::options_description optionalParams("Optional parameters");
optionalParams.add_options()
("outSfMDataFilename", po::value<std::string>(&outSfMDataFilename)->default_value(outSfMDataFilename),
"Filename of the output SfMData file.")
("describerTypes,d", po::value<std::string>(&describerTypesName)->default_value(describerTypesName),
feature::EImageDescriberType_informations().c_str())
("interFileExtension", po::value<std::string>(&outInterFileExtension)->default_value(outInterFileExtension),
"Extension of the intermediate file export.")
("minInputTrackLength", po::value<int>(&minInputTrackLength)->default_value(minInputTrackLength),
"Minimum track length in input of SfM")
("cameraModel", po::value<int>(&userCameraModel)->default_value(userCameraModel),
"* 1: Pinhole\n"
"* 2: Pinhole radial 1\n"
"* 3: Pinhole radial 3")
("initialPairA", po::value<std::string>(&initialPairString.first)->default_value(initialPairString.first),
"filename of the first image (without path).")
("initialPairB", po::value<std::string>(&initialPairString.second)->default_value(initialPairString.second),
"filename of the second image (without path).")
("refineIntrinsics", po::bool_switch(&refineIntrinsics)->default_value(refineIntrinsics),
"Refine intrinsic parameters.");
("allowUserInteraction", po::bool_switch(&allowUserInteraction)->default_value(allowUserInteraction),
"Enable/Disable user interactions.\n"
"If the process is done on renderfarm, it doesn't make sense to wait for user inputs");
po::options_description logParams("Log parameters");
logParams.add_options()
("verboseLevel,v", po::value<std::string>(&verboseLevel)->default_value(verboseLevel),
"verbosity level (fatal, error, warning, info, debug, trace).");
allParams.add(requiredParams).add(optionalParams).add(logParams);
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, allParams), vm);
if(vm.count("help") || (argc == 1))
{
ALICEVISION_COUT(allParams);
return EXIT_SUCCESS;
}
po::notify(vm);
}
catch(boost::program_options::required_option& e)
{
ALICEVISION_CERR("ERROR: " << e.what());
ALICEVISION_COUT("Usage:\n\n" << allParams);
return EXIT_FAILURE;
}
catch(boost::program_options::error& e)
{
ALICEVISION_CERR("ERROR: " << e.what());
ALICEVISION_COUT("Usage:\n\n" << allParams);
return EXIT_FAILURE;
}
ALICEVISION_COUT("Program called with the following parameters:");
ALICEVISION_COUT(vm);
// set verbose level
system::Logger::get()->setLogLevel(verboseLevel);
// Load input SfMData scene
SfMData sfmData;
if (!Load(sfmData, sfmDataFilename, ESfMData(ALL))) {
std::cerr << std::endl
<< "The input SfMData file \""<< sfmDataFilename << "\" cannot be read." << std::endl;
return EXIT_FAILURE;
}
if(featuresDirectory.empty()) {
featuresDirectory = matchesDirectory;
}
// Get imageDescriberMethodType
const std::vector<feature::EImageDescriberType> describerTypes = feature::EImageDescriberType_stringToEnums(describerTypesName);
// Features reading
feature::FeaturesPerView featuresPerView;
if(!sfm::loadFeaturesPerView(featuresPerView, sfmData, featuresDirectory, describerTypes))
{
std::cerr << std::endl
<< "Invalid features." << std::endl;
return EXIT_FAILURE;
}
// Matches reading
matching::PairwiseMatches pairwiseMatches;
if(!loadPairwiseMatches(pairwiseMatches, sfmData, matchesDirectory, describerTypes, "f"))
{
std::cerr << std::endl << "Unable to load matches file from: " << matchesDirectory << std::endl;
return EXIT_FAILURE;
}
if (outDirectory.empty())
{
std::cerr << "\nIt is an invalid output directory" << std::endl;
return EXIT_FAILURE;
}
if (!stlplus::folder_exists(outDirectory))
stlplus::folder_create(outDirectory);
//---------------------------------------
// Sequential reconstruction process
//---------------------------------------
aliceVision::system::Timer timer;
ReconstructionEngine_sequentialSfM sfmEngine(
sfmData,
outDirectory,
stlplus::create_filespec(outDirectory, "sfm_log.html"));
// Configure the featuresPerView & the matches_provider
sfmEngine.setFeatures(&featuresPerView);
sfmEngine.setMatches(&pairwiseMatches);
// Configure reconstruction parameters
sfmEngine.Set_bFixedIntrinsics(!refineIntrinsics);
sfmEngine.SetUnknownCameraType(EINTRINSIC(userCameraModel));
sfmEngine.setMinInputTrackLength(minInputTrackLength);
sfmEngine.setSfmdataInterFileExtension(outInterFileExtension);
sfmEngine.setAllowUserInteraction(allowUserInteraction);
// Handle Initial pair parameter
if (!initialPairString.first.empty() && !initialPairString.second.empty())
{
if (initialPairString.first == initialPairString.second)
{
std::cerr << "\nInvalid image names. You cannot use the same image to initialize a pair." << std::endl;
return EXIT_FAILURE;
}
Pair initialPairIndex;
if(!retrieveViewIdFromImageName(sfmData, initialPairString.first, initialPairIndex.first)
|| !retrieveViewIdFromImageName(sfmData, initialPairString.second, initialPairIndex.second))
{
std::cerr << "Could not find the initial pairs <" << initialPairString.first
<< ", " << initialPairString.second << ">!\n";
return EXIT_FAILURE;
}
sfmEngine.setInitialPair(initialPairIndex);
}
if (!sfmEngine.Process())
{
return EXIT_FAILURE;
}
// get the color for the 3D points
if(!sfmEngine.Colorize())
{
std::cerr << "Colorize failed!" << std::endl;
}
sfmEngine.Get_SfMData().setFeatureFolder(featuresDirectory);
sfmEngine.Get_SfMData().setMatchingFolder(matchesDirectory);
std::cout << std::endl << " Total Ac-Sfm took (s): " << timer.elapsed() << std::endl;
std::cout << "...Generating SfM_Report.html" << std::endl;
Generate_SfM_Report(sfmEngine.Get_SfMData(),
stlplus::create_filespec(outDirectory, "sfm_report.html"));
//-- Export to disk computed scene (data & visualizable results)
std::cout << "...Export SfMData to disk:" << std::endl;
std::cout << " " << outSfMDataFilename << std::endl;
Save(sfmEngine.Get_SfMData(), outSfMDataFilename, ESfMData(ALL));
Save(sfmEngine.Get_SfMData(), stlplus::create_filespec(outDirectory, "cloud_and_poses", outInterFileExtension), ESfMData(VIEWS | EXTRINSICS | INTRINSICS | STRUCTURE));
return EXIT_SUCCESS;
}
<commit_msg>[software] incrementalSfM: output is now the output SfMData filepath<commit_after>// This file is part of the AliceVision project and is made available under
// the terms of the MPL2 license (see the COPYING.md file).
#include <aliceVision/feature/imageDescriberCommon.hpp>
#include <aliceVision/sfm/sfm.hpp>
#include <aliceVision/sfm/pipeline/regionsIO.hpp>
#include <aliceVision/system/Timer.hpp>
#include <aliceVision/system/Logger.hpp>
#include <aliceVision/system/cmdline.hpp>
#include <dependencies/stlplus3/filesystemSimplified/file_system.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <cstdlib>
using namespace aliceVision;
using namespace aliceVision::camera;
using namespace aliceVision::sfm;
using namespace aliceVision::feature;
using namespace std;
namespace po = boost::program_options;
/**
* @brief Retrieve the view id in the sfmData from the image filename.
*
* @param[in] sfm_data the SfM scene
* @param[in] initialName the image name to find (filename or path)
* @param[out] out_viewId the id found
* @return if a view is found
*/
bool retrieveViewIdFromImageName(
const SfMData & sfm_data,
const std::string& initialName,
IndexT& out_viewId)
{
out_viewId = UndefinedIndexT;
bool isName = (initialName == stlplus::filename_part(initialName));
/// List views filenames and find the one that correspond to the user ones:
for(Views::const_iterator it = sfm_data.GetViews().begin();
it != sfm_data.GetViews().end(); ++it)
{
const View * v = it->second.get();
std::string filename;
if(isName)
{
filename = stlplus::filename_part(v->getImagePath());
}
else
{
if(stlplus::is_full_path(v->getImagePath()))
{
filename = v->getImagePath();
}
else
{
filename = sfm_data.s_root_path + v->getImagePath();
}
}
if (filename == initialName)
{
if(out_viewId == UndefinedIndexT)
{
out_viewId = v->getViewId();
}
else
{
std::cout<<"Error: Two pictures named :" << initialName << " !" << std::endl;
}
}
}
return out_viewId != UndefinedIndexT;
}
int main(int argc, char **argv)
{
// command-line parameters
std::string verboseLevel = system::EVerboseLevel_enumToString(system::Logger::getDefaultVerboseLevel());
std::string sfmDataFilename;
std::string featuresDirectory;
std::string matchesDirectory;
std::string outputSfM;
// user optional parameters
std::string extraInfoDirectory;
std::string describerTypesName = feature::EImageDescriberType_enumToString(feature::EImageDescriberType::SIFT);
std::string outInterFileExtension = ".ply";
std::pair<std::string,std::string> initialPairString("","");
int minInputTrackLength = 2;
int userCameraModel = static_cast<int>(PINHOLE_CAMERA_RADIAL3);
bool refineIntrinsics = true;
bool allowUserInteraction = true;
po::options_description allParams(
"Sequential/Incremental reconstruction\n"
"Perform incremental SfM (Initial Pair Essential + Resection)\n"
"AliceVision incrementalSfM");
po::options_description requiredParams("Required parameters");
requiredParams.add_options()
("input,i", po::value<std::string>(&sfmDataFilename)->required(),
"SfMData file.")
("output,o", po::value<std::string>(&outputSfM)->required(),
"Path to the output SfMData file.")
("featuresDirectory,f", po::value<std::string>(&featuresDirectory)->required(),
"Path to a directory containing the extracted features.")
("matchesDirectory,m", po::value<std::string>(&matchesDirectory)->required(),
"Path to a directory in which computed matches are stored.");
po::options_description optionalParams("Optional parameters");
optionalParams.add_options()
("extraInfoDirectory", po::value<std::string>(&extraInfoDirectory)->default_value(extraInfoDirectory),
"Directory for intermediate reconstruction files and additional reconstruction information files.")
("describerTypes,d", po::value<std::string>(&describerTypesName)->default_value(describerTypesName),
feature::EImageDescriberType_informations().c_str())
("interFileExtension", po::value<std::string>(&outInterFileExtension)->default_value(outInterFileExtension),
"Extension of the intermediate file export.")
("minInputTrackLength", po::value<int>(&minInputTrackLength)->default_value(minInputTrackLength),
"Minimum track length in input of SfM")
("cameraModel", po::value<int>(&userCameraModel)->default_value(userCameraModel),
"* 1: Pinhole\n"
"* 2: Pinhole radial 1\n"
"* 3: Pinhole radial 3")
("initialPairA", po::value<std::string>(&initialPairString.first)->default_value(initialPairString.first),
"filename of the first image (without path).")
("initialPairB", po::value<std::string>(&initialPairString.second)->default_value(initialPairString.second),
"filename of the second image (without path).")
("refineIntrinsics", po::bool_switch(&refineIntrinsics)->default_value(refineIntrinsics),
"Refine intrinsic parameters.");
("allowUserInteraction", po::bool_switch(&allowUserInteraction)->default_value(allowUserInteraction),
"Enable/Disable user interactions.\n"
"If the process is done on renderfarm, it doesn't make sense to wait for user inputs");
po::options_description logParams("Log parameters");
logParams.add_options()
("verboseLevel,v", po::value<std::string>(&verboseLevel)->default_value(verboseLevel),
"verbosity level (fatal, error, warning, info, debug, trace).");
allParams.add(requiredParams).add(optionalParams).add(logParams);
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, allParams), vm);
if(vm.count("help") || (argc == 1))
{
ALICEVISION_COUT(allParams);
return EXIT_SUCCESS;
}
po::notify(vm);
}
catch(boost::program_options::required_option& e)
{
ALICEVISION_CERR("ERROR: " << e.what());
ALICEVISION_COUT("Usage:\n\n" << allParams);
return EXIT_FAILURE;
}
catch(boost::program_options::error& e)
{
ALICEVISION_CERR("ERROR: " << e.what());
ALICEVISION_COUT("Usage:\n\n" << allParams);
return EXIT_FAILURE;
}
ALICEVISION_COUT("Program called with the following parameters:");
ALICEVISION_COUT(vm);
// set verbose level
system::Logger::get()->setLogLevel(verboseLevel);
// Load input SfMData scene
SfMData sfmData;
if (!Load(sfmData, sfmDataFilename, ESfMData(ALL))) {
std::cerr << std::endl
<< "The input SfMData file \""<< sfmDataFilename << "\" cannot be read." << std::endl;
return EXIT_FAILURE;
}
if(featuresDirectory.empty()) {
featuresDirectory = matchesDirectory;
}
// Get imageDescriberMethodType
const std::vector<feature::EImageDescriberType> describerTypes = feature::EImageDescriberType_stringToEnums(describerTypesName);
// Features reading
feature::FeaturesPerView featuresPerView;
if(!sfm::loadFeaturesPerView(featuresPerView, sfmData, featuresDirectory, describerTypes))
{
std::cerr << std::endl
<< "Invalid features." << std::endl;
return EXIT_FAILURE;
}
// Matches reading
matching::PairwiseMatches pairwiseMatches;
if(!loadPairwiseMatches(pairwiseMatches, sfmData, matchesDirectory, describerTypes, "f"))
{
std::cerr << std::endl << "Unable to load matches file from: " << matchesDirectory << std::endl;
return EXIT_FAILURE;
}
if (outputSfM.empty())
{
std::cerr << "\nIt is an invalid SfMData file path." << std::endl;
return EXIT_FAILURE;
}
if(extraInfoDirectory.empty())
{
namespace bfs = boost::filesystem;
extraInfoDirectory = bfs::path(outputSfM).parent_path().string();
}
if (!stlplus::folder_exists(extraInfoDirectory))
stlplus::folder_create(extraInfoDirectory);
//---------------------------------------
// Sequential reconstruction process
//---------------------------------------
aliceVision::system::Timer timer;
ReconstructionEngine_sequentialSfM sfmEngine(
sfmData,
extraInfoDirectory,
stlplus::create_filespec(extraInfoDirectory, "sfm_log.html"));
// Configure the featuresPerView & the matches_provider
sfmEngine.setFeatures(&featuresPerView);
sfmEngine.setMatches(&pairwiseMatches);
// Configure reconstruction parameters
sfmEngine.Set_bFixedIntrinsics(!refineIntrinsics);
sfmEngine.SetUnknownCameraType(EINTRINSIC(userCameraModel));
sfmEngine.setMinInputTrackLength(minInputTrackLength);
sfmEngine.setSfmdataInterFileExtension(outInterFileExtension);
sfmEngine.setAllowUserInteraction(allowUserInteraction);
// Handle Initial pair parameter
if (!initialPairString.first.empty() && !initialPairString.second.empty())
{
if (initialPairString.first == initialPairString.second)
{
std::cerr << "\nInvalid image names. You cannot use the same image to initialize a pair." << std::endl;
return EXIT_FAILURE;
}
Pair initialPairIndex;
if(!retrieveViewIdFromImageName(sfmData, initialPairString.first, initialPairIndex.first)
|| !retrieveViewIdFromImageName(sfmData, initialPairString.second, initialPairIndex.second))
{
std::cerr << "Could not find the initial pairs <" << initialPairString.first
<< ", " << initialPairString.second << ">!\n";
return EXIT_FAILURE;
}
sfmEngine.setInitialPair(initialPairIndex);
}
if (!sfmEngine.Process())
{
return EXIT_FAILURE;
}
// get the color for the 3D points
if(!sfmEngine.Colorize())
{
std::cerr << "Colorize failed!" << std::endl;
}
sfmEngine.Get_SfMData().setFeatureFolder(featuresDirectory);
sfmEngine.Get_SfMData().setMatchingFolder(matchesDirectory);
std::cout << std::endl << " Total Ac-Sfm took (s): " << timer.elapsed() << std::endl;
std::cout << "...Generating SfM_Report.html" << std::endl;
Generate_SfM_Report(sfmEngine.Get_SfMData(),
stlplus::create_filespec(extraInfoDirectory, "sfm_report.html"));
//-- Export to disk computed scene (data & visualizable results)
std::cout << "...Export SfMData to disk:" << outputSfM << std::endl;
Save(sfmEngine.Get_SfMData(), outputSfM, ESfMData(ALL));
Save(sfmEngine.Get_SfMData(), stlplus::create_filespec(extraInfoDirectory, "cloud_and_poses", outInterFileExtension), ESfMData(VIEWS | EXTRINSICS | INTRINSICS | STRUCTURE));
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* Restructuring Shogun's statistical hypothesis testing framework.
* Copyright (C) 2016 Soumyajit De
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <utility>
#include <vector>
#include <memory>
#include <type_traits>
#include <shogun/kernel/Kernel.h>
#include <shogun/kernel/CustomKernel.h>
#include <shogun/kernel/CombinedKernel.h>
#include <shogun/features/Features.h>
#include <shogun/statistical_testing/MMD.h>
#include <shogun/statistical_testing/QuadraticTimeMMD.h>
#include <shogun/statistical_testing/BTestMMD.h>
#include <shogun/statistical_testing/LinearTimeMMD.h>
#include <shogun/statistical_testing/internals/NextSamples.h>
#include <shogun/statistical_testing/internals/DataManager.h>
#include <shogun/statistical_testing/internals/KernelManager.h>
#include <shogun/statistical_testing/internals/ComputationManager.h>
#include <shogun/statistical_testing/internals/mmd/BiasedFull.h>
#include <shogun/statistical_testing/internals/mmd/UnbiasedFull.h>
#include <shogun/statistical_testing/internals/mmd/UnbiasedIncomplete.h>
#include <shogun/statistical_testing/internals/mmd/WithinBlockDirect.h>
#include <shogun/statistical_testing/internals/mmd/WithinBlockPermutation.h>
using namespace shogun;
using namespace internal;
struct CMMD::Self
{
Self(CMMD& cmmd);
void create_computation_jobs(index_t Bx);
void create_statistic_job(index_t Bx);
void create_variance_job();
void merge_samples(NextSamples&, std::vector<std::shared_ptr<CFeatures>>&) const;
void compute_kernel(ComputationManager&, std::vector<std::shared_ptr<CFeatures>>&, CKernel*) const;
std::pair<float64_t, float64_t> compute_statistic_variance();
SGVector<float64_t> sample_null();
CMMD& owner;
bool use_gpu_for_computation;
index_t num_null_samples;
EStatisticType statistic_type;
EVarianceEstimationMethod variance_estimation_method;
ENullApproximationMethod null_approximation_method;
std::function<float64_t(SGMatrix<float64_t>)> statistic_job;
std::function<float64_t(SGMatrix<float64_t>)> permutation_job;
std::function<float64_t(SGMatrix<float64_t>)> variance_job;
};
CMMD::Self::Self(CMMD& cmmd) : owner(cmmd),
use_gpu_for_computation(false), num_null_samples(250),
statistic_type(EStatisticType::UNBIASED_FULL),
variance_estimation_method(EVarianceEstimationMethod::DIRECT),
null_approximation_method(ENullApproximationMethod::PERMUTATION),
statistic_job(nullptr), variance_job(nullptr)
{
}
void CMMD::Self::create_computation_jobs(index_t Bx)
{
create_statistic_job(Bx);
create_variance_job();
}
void CMMD::Self::create_statistic_job(index_t Bx)
{
switch (statistic_type)
{
case EStatisticType::UNBIASED_FULL:
statistic_job = mmd::UnbiasedFull(Bx);
permutation_job = mmd::WithinBlockPermutation<mmd::UnbiasedFull>(Bx);
break;
case EStatisticType::UNBIASED_INCOMPLETE:
statistic_job = mmd::UnbiasedIncomplete(Bx);
permutation_job = mmd::WithinBlockPermutation<mmd::UnbiasedIncomplete>(Bx);
break;
case EStatisticType::BIASED_FULL:
statistic_job = mmd::BiasedFull(Bx);
permutation_job = mmd::WithinBlockPermutation<mmd::BiasedFull>(Bx);
break;
default : break;
};
}
void CMMD::Self::create_variance_job()
{
switch (variance_estimation_method)
{
case EVarianceEstimationMethod::DIRECT:
variance_job = owner.get_direct_estimation_method();
break;
case EVarianceEstimationMethod::PERMUTATION:
variance_job = permutation_job;
break;
default : break;
};
}
void CMMD::Self::merge_samples(NextSamples& next_burst, std::vector<std::shared_ptr<CFeatures>>& blocks) const
{
blocks.resize(next_burst.num_blocks());
#pragma omp parallel for
for (size_t i = 0; i < blocks.size(); ++i)
{
auto block_p = next_burst[0][i];
auto block_q = next_burst[1][i];
auto block_p_q = block_p->create_merged_copy(block_q.get());
SG_REF(block_p_q);
block_p = nullptr;
block_q = nullptr;
blocks[i] = std::shared_ptr<CFeatures>(block_p_q, [](CFeatures* ptr) { SG_UNREF(ptr); });
}
}
void CMMD::Self::compute_kernel(ComputationManager& cm, std::vector<std::shared_ptr<CFeatures>>& blocks, CKernel* kernel) const
{
cm.num_data(blocks.size());
#pragma omp parallel for
for (size_t i = 0; i < blocks.size(); ++i)
{
try
{
auto kernel_clone = std::unique_ptr<CKernel>(static_cast<CKernel*>(kernel->clone()));
kernel_clone->init(blocks[i].get(), blocks[i].get());
cm.data(i) = std::unique_ptr<CCustomKernel>(new CCustomKernel(kernel_clone.get()))->get_kernel_matrix();
kernel_clone->remove_lhs_and_rhs();
}
catch (ShogunException e)
{
SG_SERROR("%s, Try using less number of blocks per burst!\n", e.get_exception_string());
}
}
}
std::pair<float64_t, float64_t> CMMD::Self::compute_statistic_variance()
{
DataManager& dm = owner.get_data_manager();
const KernelManager& km = owner.get_kernel_manager();
float64_t statistic = 0;
float64_t permuted_samples_statistic = 0;
float64_t variance = 0;
auto kernel = km.kernel_at(0);
REQUIRE(kernel != nullptr, "Kernel is not set!\n");
index_t term_counters = 1;
dm.start();
auto next_burst = dm.next();
create_computation_jobs(owner.get_data_manager().blocksize_at(0));
ComputationManager cm;
// enqueue statistic and variance computation jobs on the computed kernel matrices
cm.enqueue_job(statistic_job);
cm.enqueue_job(variance_job);
std::vector<std::shared_ptr<CFeatures>> blocks;
while (!next_burst.empty())
{
merge_samples(next_burst, blocks);
compute_kernel(cm, blocks, kernel);
if (use_gpu_for_computation)
{
cm.use_gpu().compute();
}
else
{
cm.use_cpu().compute();
}
auto mmds = cm.next_result();
auto vars = cm.next_result();
for (size_t i = 0; i < mmds.size(); ++i)
{
auto delta = mmds[i] - statistic;
statistic += delta / term_counters;
}
if (variance_estimation_method == EVarianceEstimationMethod::DIRECT)
{
for (size_t i = 0; i < mmds.size(); ++i)
{
auto delta = vars[i] - variance;
variance += delta / term_counters;
}
}
else
{
for (size_t i = 0; i < mmds.size(); ++i)
{
auto delta = vars[i] - permuted_samples_statistic;
permuted_samples_statistic += delta / term_counters;
variance += delta * (vars[i] - permuted_samples_statistic);
}
}
term_counters++;
next_burst = dm.next();
}
dm.end();
cm.done();
// normalize statistic and variance
statistic = owner.normalize_statistic(statistic);
if (variance_estimation_method == EVarianceEstimationMethod::PERMUTATION)
{
variance = owner.normalize_variance(variance);
}
return std::make_pair(statistic, variance);
}
SGVector<float64_t> CMMD::Self::sample_null()
{
DataManager& dm = owner.get_data_manager();
const KernelManager& km = owner.get_kernel_manager();
SGVector<float64_t> statistic(num_null_samples);
std::fill(statistic.vector, statistic.vector + statistic.vlen, 0);
auto kernel = km.kernel_at(0);
REQUIRE(kernel != nullptr, "Kernel is not set!\n");
std::vector<index_t> term_counters(num_null_samples);
std::fill(term_counters.data(), term_counters.data() + term_counters.size(), 1);
dm.start();
auto next_burst = dm.next();
create_statistic_job(owner.get_data_manager().blocksize_at(0));
ComputationManager cm;
cm.enqueue_job(permutation_job);
std::vector<std::shared_ptr<CFeatures>> blocks;
while (!next_burst.empty())
{
merge_samples(next_burst, blocks);
compute_kernel(cm, blocks, kernel);
for (auto j = 0; j < num_null_samples; ++j)
{
if (use_gpu_for_computation)
{
cm.use_gpu().compute();
}
else
{
cm.use_cpu().compute();
}
auto mmds = cm.next_result();
for (size_t i = 0; i < mmds.size(); ++i)
{
auto delta = mmds[i] - statistic[j];
statistic[j] += delta / term_counters[j];
}
term_counters[j]++;
}
next_burst = dm.next();
}
dm.end();
cm.done();
// normalize statistic
std::for_each(statistic.vector, statistic.vector + statistic.vlen, [this](float64_t& value)
{
value = owner.normalize_statistic(value);
});
return statistic;
}
CMMD::CMMD() : CTwoSampleTest()
{
self = std::unique_ptr<Self>(new Self(*this));
}
CMMD::~CMMD()
{
}
float64_t CMMD::compute_statistic()
{
return self->compute_statistic_variance().first;
}
float64_t CMMD::compute_variance()
{
return self->compute_statistic_variance().second;
}
SGVector<float64_t> CMMD::sample_null()
{
return self->sample_null();
}
void CMMD::set_num_null_samples(index_t null_samples)
{
self->num_null_samples = null_samples;
}
const index_t CMMD::get_num_null_samples() const
{
return self->num_null_samples;
}
void CMMD::use_gpu(bool gpu)
{
self->use_gpu_for_computation = gpu;
}
void CMMD::set_statistic_type(EStatisticType stype)
{
self->statistic_type = stype;
}
const EStatisticType CMMD::get_statistic_type() const
{
return self->statistic_type;
}
void CMMD::set_variance_estimation_method(EVarianceEstimationMethod vmethod)
{
// TODO overload this
/* if (std::is_same<Derived, CQuadraticTimeMMD>::value && vmethod == EVarianceEstimationMethod::PERMUTATION)
{
std::cerr << "cannot use permutation method for quadratic time MMD" << std::endl;
}*/
self->variance_estimation_method = vmethod;
}
const EVarianceEstimationMethod CMMD::get_variance_estimation_method() const
{
return self->variance_estimation_method;
}
void CMMD::set_null_approximation_method(ENullApproximationMethod nmethod)
{
// TODO overload this
/* if (std::is_same<Derived, CQuadraticTimeMMD>::value && nmethod == ENullApproximationMethod::MMD1_GAUSSIAN)
{
std::cerr << "cannot use gaussian method for quadratic time MMD" << std::endl;
}
else if ((std::is_same<Derived, CBTestMMD>::value || std::is_same<Derived, CLinearTimeMMD>::value) &&
(nmethod == ENullApproximationMethod::MMD2_SPECTRUM || nmethod == ENullApproximationMethod::MMD2_GAMMA))
{
std::cerr << "cannot use spectrum/gamma method for B-test/linear time MMD" << std::endl;
}*/
self->null_approximation_method = nmethod;
}
const ENullApproximationMethod CMMD::get_null_approximation_method() const
{
return self->null_approximation_method;
}
const char* CMMD::get_name() const
{
return "MMD";
}
<commit_msg>added some more readability methods<commit_after>/*
* Restructuring Shogun's statistical hypothesis testing framework.
* Copyright (C) 2016 Soumyajit De
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <utility>
#include <vector>
#include <memory>
#include <type_traits>
#include <shogun/kernel/Kernel.h>
#include <shogun/kernel/CustomKernel.h>
#include <shogun/kernel/CombinedKernel.h>
#include <shogun/features/Features.h>
#include <shogun/statistical_testing/MMD.h>
#include <shogun/statistical_testing/QuadraticTimeMMD.h>
#include <shogun/statistical_testing/BTestMMD.h>
#include <shogun/statistical_testing/LinearTimeMMD.h>
#include <shogun/statistical_testing/internals/NextSamples.h>
#include <shogun/statistical_testing/internals/DataManager.h>
#include <shogun/statistical_testing/internals/KernelManager.h>
#include <shogun/statistical_testing/internals/ComputationManager.h>
#include <shogun/statistical_testing/internals/mmd/BiasedFull.h>
#include <shogun/statistical_testing/internals/mmd/UnbiasedFull.h>
#include <shogun/statistical_testing/internals/mmd/UnbiasedIncomplete.h>
#include <shogun/statistical_testing/internals/mmd/WithinBlockDirect.h>
#include <shogun/statistical_testing/internals/mmd/WithinBlockPermutation.h>
using namespace shogun;
using namespace internal;
struct CMMD::Self
{
Self(CMMD& cmmd);
void create_computation_jobs(index_t Bx);
void create_statistic_job(index_t Bx);
void create_variance_job();
void merge_samples(NextSamples&, std::vector<std::shared_ptr<CFeatures>>&) const;
void compute_kernel(ComputationManager&, std::vector<std::shared_ptr<CFeatures>>&, CKernel*) const;
void compute_jobs(ComputationManager&) const;
std::pair<float64_t, float64_t> compute_statistic_variance();
SGVector<float64_t> sample_null();
CMMD& owner;
bool use_gpu_for_computation;
index_t num_null_samples;
EStatisticType statistic_type;
EVarianceEstimationMethod variance_estimation_method;
ENullApproximationMethod null_approximation_method;
std::function<float64_t(SGMatrix<float64_t>)> statistic_job;
std::function<float64_t(SGMatrix<float64_t>)> permutation_job;
std::function<float64_t(SGMatrix<float64_t>)> variance_job;
};
CMMD::Self::Self(CMMD& cmmd) : owner(cmmd),
use_gpu_for_computation(false), num_null_samples(250),
statistic_type(EStatisticType::UNBIASED_FULL),
variance_estimation_method(EVarianceEstimationMethod::DIRECT),
null_approximation_method(ENullApproximationMethod::PERMUTATION),
statistic_job(nullptr), variance_job(nullptr)
{
}
void CMMD::Self::create_computation_jobs(index_t Bx)
{
create_statistic_job(Bx);
create_variance_job();
}
void CMMD::Self::create_statistic_job(index_t Bx)
{
switch (statistic_type)
{
case EStatisticType::UNBIASED_FULL:
statistic_job = mmd::UnbiasedFull(Bx);
permutation_job = mmd::WithinBlockPermutation<mmd::UnbiasedFull>(Bx);
break;
case EStatisticType::UNBIASED_INCOMPLETE:
statistic_job = mmd::UnbiasedIncomplete(Bx);
permutation_job = mmd::WithinBlockPermutation<mmd::UnbiasedIncomplete>(Bx);
break;
case EStatisticType::BIASED_FULL:
statistic_job = mmd::BiasedFull(Bx);
permutation_job = mmd::WithinBlockPermutation<mmd::BiasedFull>(Bx);
break;
default : break;
};
}
void CMMD::Self::create_variance_job()
{
switch (variance_estimation_method)
{
case EVarianceEstimationMethod::DIRECT:
variance_job = owner.get_direct_estimation_method();
break;
case EVarianceEstimationMethod::PERMUTATION:
variance_job = permutation_job;
break;
default : break;
};
}
#define get_block_p(i) next_burst[0][i]
#define get_block_q(i) next_burst[1][i]
void CMMD::Self::merge_samples(NextSamples& next_burst, std::vector<std::shared_ptr<CFeatures>>& blocks) const
{
blocks.resize(next_burst.num_blocks());
#pragma omp parallel for
for (size_t i = 0; i < blocks.size(); ++i)
{
auto block_p = get_block_p(i);
auto block_q = get_block_q(i);
auto block_p_and_q = block_p->create_merged_copy(block_q.get());
SG_REF(block_p_and_q);
block_p = nullptr;
block_q = nullptr;
blocks[i] = std::shared_ptr<CFeatures>(block_p_and_q, [](CFeatures* ptr) { SG_UNREF(ptr); });
}
}
#undef get_block_p
#undef get_block_q
void CMMD::Self::compute_kernel(ComputationManager& cm, std::vector<std::shared_ptr<CFeatures>>& blocks, CKernel* kernel) const
{
cm.num_data(blocks.size());
#pragma omp parallel for
for (size_t i = 0; i < blocks.size(); ++i)
{
try
{
auto kernel_clone = std::unique_ptr<CKernel>(static_cast<CKernel*>(kernel->clone()));
kernel_clone->init(blocks[i].get(), blocks[i].get());
cm.data(i) = std::unique_ptr<CCustomKernel>(new CCustomKernel(kernel_clone.get()))->get_kernel_matrix();
kernel_clone->remove_lhs_and_rhs();
}
catch (ShogunException e)
{
SG_SERROR("%s, Try using less number of blocks per burst!\n", e.get_exception_string());
}
}
}
void CMMD::Self::compute_jobs(ComputationManager& cm) const
{
if (use_gpu_for_computation)
{
cm.use_gpu().compute();
}
else
{
cm.use_cpu().compute();
}
}
std::pair<float64_t, float64_t> CMMD::Self::compute_statistic_variance()
{
DataManager& dm = owner.get_data_manager();
const KernelManager& km = owner.get_kernel_manager();
float64_t statistic = 0;
float64_t permuted_samples_statistic = 0;
float64_t variance = 0;
auto kernel = km.kernel_at(0);
REQUIRE(kernel != nullptr, "Kernel is not set!\n");
index_t term_counters = 1;
dm.start();
auto next_burst = dm.next();
create_computation_jobs(owner.get_data_manager().blocksize_at(0));
ComputationManager cm;
// enqueue statistic and variance computation jobs on the computed kernel matrices
cm.enqueue_job(statistic_job);
cm.enqueue_job(variance_job);
std::vector<std::shared_ptr<CFeatures>> blocks;
while (!next_burst.empty())
{
merge_samples(next_burst, blocks);
compute_kernel(cm, blocks, kernel);
compute_jobs(cm);
auto mmds = cm.next_result();
auto vars = cm.next_result();
for (size_t i = 0; i < mmds.size(); ++i)
{
auto delta = mmds[i] - statistic;
statistic += delta / term_counters;
}
if (variance_estimation_method == EVarianceEstimationMethod::DIRECT)
{
for (size_t i = 0; i < mmds.size(); ++i)
{
auto delta = vars[i] - variance;
variance += delta / term_counters;
}
}
else
{
for (size_t i = 0; i < mmds.size(); ++i)
{
auto delta = vars[i] - permuted_samples_statistic;
permuted_samples_statistic += delta / term_counters;
variance += delta * (vars[i] - permuted_samples_statistic);
}
}
term_counters++;
next_burst = dm.next();
}
dm.end();
cm.done();
// normalize statistic and variance
statistic = owner.normalize_statistic(statistic);
if (variance_estimation_method == EVarianceEstimationMethod::PERMUTATION)
{
variance = owner.normalize_variance(variance);
}
return std::make_pair(statistic, variance);
}
SGVector<float64_t> CMMD::Self::sample_null()
{
DataManager& dm = owner.get_data_manager();
const KernelManager& km = owner.get_kernel_manager();
SGVector<float64_t> statistic(num_null_samples);
std::fill(statistic.vector, statistic.vector + statistic.vlen, 0);
auto kernel = km.kernel_at(0);
REQUIRE(kernel != nullptr, "Kernel is not set!\n");
std::vector<index_t> term_counters(num_null_samples);
std::fill(term_counters.data(), term_counters.data() + term_counters.size(), 1);
dm.start();
auto next_burst = dm.next();
create_statistic_job(owner.get_data_manager().blocksize_at(0));
ComputationManager cm;
cm.enqueue_job(permutation_job);
std::vector<std::shared_ptr<CFeatures>> blocks;
while (!next_burst.empty())
{
merge_samples(next_burst, blocks);
compute_kernel(cm, blocks, kernel);
for (auto j = 0; j < num_null_samples; ++j)
{
compute_jobs(cm);
auto mmds = cm.next_result();
for (size_t i = 0; i < mmds.size(); ++i)
{
auto delta = mmds[i] - statistic[j];
statistic[j] += delta / term_counters[j];
}
term_counters[j]++;
}
next_burst = dm.next();
}
dm.end();
cm.done();
// normalize statistic
std::for_each(statistic.vector, statistic.vector + statistic.vlen, [this](float64_t& value)
{
value = owner.normalize_statistic(value);
});
return statistic;
}
CMMD::CMMD() : CTwoSampleTest()
{
self = std::unique_ptr<Self>(new Self(*this));
}
CMMD::~CMMD()
{
}
float64_t CMMD::compute_statistic()
{
return self->compute_statistic_variance().first;
}
float64_t CMMD::compute_variance()
{
return self->compute_statistic_variance().second;
}
SGVector<float64_t> CMMD::sample_null()
{
return self->sample_null();
}
void CMMD::set_num_null_samples(index_t null_samples)
{
self->num_null_samples = null_samples;
}
const index_t CMMD::get_num_null_samples() const
{
return self->num_null_samples;
}
void CMMD::use_gpu(bool gpu)
{
self->use_gpu_for_computation = gpu;
}
void CMMD::set_statistic_type(EStatisticType stype)
{
self->statistic_type = stype;
}
const EStatisticType CMMD::get_statistic_type() const
{
return self->statistic_type;
}
void CMMD::set_variance_estimation_method(EVarianceEstimationMethod vmethod)
{
// TODO overload this
/* if (std::is_same<Derived, CQuadraticTimeMMD>::value && vmethod == EVarianceEstimationMethod::PERMUTATION)
{
std::cerr << "cannot use permutation method for quadratic time MMD" << std::endl;
}*/
self->variance_estimation_method = vmethod;
}
const EVarianceEstimationMethod CMMD::get_variance_estimation_method() const
{
return self->variance_estimation_method;
}
void CMMD::set_null_approximation_method(ENullApproximationMethod nmethod)
{
// TODO overload this
/* if (std::is_same<Derived, CQuadraticTimeMMD>::value && nmethod == ENullApproximationMethod::MMD1_GAUSSIAN)
{
std::cerr << "cannot use gaussian method for quadratic time MMD" << std::endl;
}
else if ((std::is_same<Derived, CBTestMMD>::value || std::is_same<Derived, CLinearTimeMMD>::value) &&
(nmethod == ENullApproximationMethod::MMD2_SPECTRUM || nmethod == ENullApproximationMethod::MMD2_GAMMA))
{
std::cerr << "cannot use spectrum/gamma method for B-test/linear time MMD" << std::endl;
}*/
self->null_approximation_method = nmethod;
}
const ENullApproximationMethod CMMD::get_null_approximation_method() const
{
return self->null_approximation_method;
}
const char* CMMD::get_name() const
{
return "MMD";
}
<|endoftext|> |
<commit_before>#include "purchasemodel.h"
#include <QtSql>
#include "dbmanager.h"
using namespace std;
const QString path = "/sqlite3/rest.db";
purchaseModel::purchaseModel()
{
this->vector_size=0;
}
QHash<int, QByteArray> purchaseModel::roleNames() const{
QHash<int, QByteArray> roles;
roles[CategoryRole] = "category";
roles[AmountRole] = "amount";
roles[NoteRole] = "note";
roles[DateRole] = "date";
roles[PeopleRole] = "people";
roles[PaymethodRole] = "payment";
roles[PlaceRole] = "place";
roles[EventRole] = "event";
roles[IdRole]="id";
return roles;
}
int purchaseModel::rowCount(const QModelIndex &parent) const
{
return agores.size();
}
QVariant purchaseModel::data(const QModelIndex &index, int role) const{
int row = index.row();
if (agores.size()>row && row>=0)
{
Purchase i = agores.at(row);
switch (role)
{
case CategoryRole: return i.getCategory();
case AmountRole: return i.getAmount();
case NoteRole: return i.getNote();
case DateRole: return i.getDate();
case PeopleRole: return i.getPeople();
case PaymethodRole: return i.getPaymethod();
case PlaceRole: return i.getPlace();
case EventRole: return i.getEvent();
case IdRole: return i.getID();
default: return QVariant();
}
}
else
{
QVariant qv;
return qv;
}
}
void purchaseModel::insertPurchase(QString categ, double amount, QString note, QDate date,
QString ppl, QString paym, QString place, QString event,DbManager *db)
{
beginResetModel();
if (db->isOpen())
{
Purchase c(0,categ,amount,note,date,ppl,paym,place,event);
db->addPurchase(c);
/*
QSqlRecord record = query.record();
while (query.next())
{
for(int index = 0; index < record.count(); ++index) {
QString key = record.fieldName(index);
QVariant value = record.value(index);
qDebug() << key << "---" << value.toString();
}
}
*/
long int lastid=db->getlastID();
c.setID(lastid);
this->agores.push_back(c);
QVariant id = c.getID();
qDebug()<< id ;
}
endResetModel();
qDebug("InsertPurchase called in Purchase Model\n");
}
void purchaseModel::removePurchase(int id,DbManager *db)
{
beginResetModel();
if (db->isOpen())
{
Purchase p ;
db->removePurchase(id);
for (int i=0;i<this->agores.size();i++)
{
p=this->agores.at(i);
if( p.getID() == id)
{
this->agores.erase(this->agores.begin()+i);
break;
}
}
}
endResetModel();
qDebug("removePurchase called in PurchaseModel");
}
void purchaseModel::loadPurchases(DbManager *db)
{
if(db->isOpen())
{
qDebug("___________________________________________________________");
QSqlQuery query("SELECT * FROM purchase");
while (query.next())
{
QString date=query.value(4).toString();
QDate *dt = new QDate(date.split("-")[0].toInt(),date.split("-")[1].toInt(),date.split("-")[2].toInt());
Purchase c(query.value(0).toLongLong(),query.value(1).toString(),query.value(2).toDouble(),query.value(3).toString(),*dt,query.value(5).toString(),query.value(6).toString(),query.value(7).toString(),query.value(8).toString());
this->agores.push_back(c);
qDebug("___________________________________________________________");
}
}
}
<commit_msg>A working fix<commit_after>#include "purchasemodel.h"
#include <QtSql>
#include "dbmanager.h"
using namespace std;
const QString path = "/sqlite3/rest.db";
purchaseModel::purchaseModel()
{
this->vector_size=0;
}
QHash<int, QByteArray> purchaseModel::roleNames() const{
QHash<int, QByteArray> roles;
roles[CategoryRole] = "category";
roles[AmountRole] = "amount";
roles[NoteRole] = "note";
roles[DateRole] = "date";
roles[PeopleRole] = "people";
roles[PaymethodRole] = "payment";
roles[PlaceRole] = "place";
roles[EventRole] = "event";
roles[IdRole]="id";
return roles;
}
int purchaseModel::rowCount(const QModelIndex &parent) const
{
return agores.size();
}
QVariant purchaseModel::data(const QModelIndex &index, int role) const{
int row = index.row();
if (agores.size()>row && row>=0)
{
Purchase i = agores.at(row);
switch (role)
{
case CategoryRole: return i.getCategory();
case AmountRole: return i.getAmount();
case NoteRole: return i.getNote();
case DateRole: return i.getDate();
case PeopleRole: return i.getPeople();
case PaymethodRole: return i.getPaymethod();
case PlaceRole: return i.getPlace();
case EventRole: return i.getEvent();
case IdRole: return i.getID();
default: return QVariant();
}
}
else
{
QVariant qv;
return qv;
}
}
void purchaseModel::insertPurchase(QString categ, double amount, QString note, QDate date,
QString ppl, QString paym, QString place, QString event,DbManager *db)
{
beginResetModel();
if (db->isOpen())
{
Purchase c(0,categ,amount,note,date,ppl,paym,place,event);
db->addPurchase(c);
/*
QSqlRecord record = query.record();
while (query.next())
{
for(int index = 0; index < record.count(); ++index) {
QString key = record.fieldName(index);
QVariant value = record.value(index);
qDebug() << key << "---" << value.toString();
}
}
long int lastid=db->getlastID();
c.setID(lastid);
this->agores.push_back(c);
QVariant id = c.getID();
qDebug()<< id ;
*/
//reload database because getlastID() doesn't work
loadPurchases(db);
}
endResetModel();
qDebug("InsertPurchase called in Purchase Model\n");
}
void purchaseModel::removePurchase(int id,DbManager *db)
{
beginResetModel();
if (db->isOpen())
{
Purchase p ;
db->removePurchase(id);
for (int i=0;i<this->agores.size();i++)
{
p=this->agores.at(i);
if( p.getID() == id)
{
this->agores.erase(this->agores.begin()+i);
break;
}
}
}
endResetModel();
qDebug("removePurchase called in PurchaseModel");
}
void purchaseModel::loadPurchases(DbManager *db)
{
if(db->isOpen())
{
this->agores.clear();
QSqlQuery query("SELECT * FROM purchase");
while (query.next())
{
QString date=query.value(4).toString();
QDate *dt = new QDate(date.split("-")[0].toInt(),date.split("-")[1].toInt(),date.split("-")[2].toInt());
Purchase c(query.value(0).toLongLong(),query.value(1).toString(),query.value(2).toDouble(),query.value(3).toString(),*dt,query.value(5).toString(),query.value(6).toString(),query.value(7).toString(),query.value(8).toString());
this->agores.push_back(c);
}
}
}
<|endoftext|> |
<commit_before>#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "../base_test.hpp"
#include "gtest/gtest.h"
#include "../../lib/operators/abstract_read_only_operator.hpp"
#include "../../lib/operators/get_table.hpp"
#include "../../lib/operators/print.hpp"
#include "../../lib/operators/projection.hpp"
#include "../../lib/operators/table_scan.hpp"
#include "../../lib/storage/storage_manager.hpp"
#include "../../lib/storage/table.hpp"
#include "../../lib/types.hpp"
using std::string_literals::operator""s;
namespace opossum {
class OperatorsProjectionTest : public BaseTest {
protected:
void SetUp() override {
std::shared_ptr<Table> test_table = load_table("src/test/tables/int_float.tbl", 2);
StorageManager::get().add_table("table_a", std::move(test_table));
_gt = std::make_shared<GetTable>("table_a");
_gt->execute();
std::shared_ptr<Table> test_table_int = load_table("src/test/tables/int_int_int.tbl", 2);
StorageManager::get().add_table("table_b", std::move(test_table_int));
_gt_int = std::make_shared<GetTable>("table_b");
_gt_int->execute();
std::shared_ptr<Table> test_table_dict = load_table("src/test/tables/int_int_int.tbl", 2);
test_table_dict->compress_chunk(0);
test_table_dict->compress_chunk(1);
StorageManager::get().add_table("table_c", std::move(test_table_dict));
_gt_int_dict = std::make_shared<GetTable>("table_c");
_gt_int_dict->execute();
}
std::shared_ptr<GetTable> _gt, _gt_int, _gt_int_dict;
};
TEST_F(OperatorsProjectionTest, SingleColumn) {
std::shared_ptr<Table> expected_result = load_table("src/test/tables/int.tbl", 1);
Projection::ProjectionDefinitions definitions({Projection::ProjectionDefinition{"$a"s, "int"s, "a"s}});
auto projection = std::make_shared<Projection>(_gt, definitions);
projection->execute();
auto out = projection->get_output();
EXPECT_TABLE_EQ(projection->get_output(), expected_result);
}
TEST_F(OperatorsProjectionTest, SingleColumnOldInterface) {
std::shared_ptr<Table> expected_result = load_table("src/test/tables/int.tbl", 1);
std::vector<std::string> columns = {"a"};
auto projection = std::make_shared<Projection>(_gt, columns);
projection->execute();
auto out = projection->get_output();
EXPECT_TABLE_EQ(projection->get_output(), expected_result);
}
TEST_F(OperatorsProjectionTest, DoubleProject) {
std::shared_ptr<Table> expected_result = load_table("src/test/tables/int.tbl", 3);
Projection::ProjectionDefinitions definitions{Projection::ProjectionDefinition{"$a", "int", "a"}};
auto projection1 = std::make_shared<Projection>(_gt, definitions);
projection1->execute();
auto projection2 = std::make_shared<Projection>(projection1, definitions);
projection2->execute();
EXPECT_TABLE_EQ(projection2->get_output(), expected_result);
}
TEST_F(OperatorsProjectionTest, AllColumns) {
std::shared_ptr<Table> expected_result = load_table("src/test/tables/float_int.tbl", 2);
Projection::ProjectionDefinitions definitions{Projection::ProjectionDefinition{"$b", "float", "b"},
Projection::ProjectionDefinition{"$a", "int", "a"}};
auto projection = std::make_shared<Projection>(_gt, definitions);
projection->execute();
EXPECT_TABLE_EQ(projection->get_output(), expected_result);
}
TEST_F(OperatorsProjectionTest, ConstantArithmeticProjection) {
std::shared_ptr<Table> expected_result = load_table("src/test/tables/int_int_int_fix_values.tbl", 2);
Projection::ProjectionDefinitions definitions{Projection::ProjectionDefinition{"2+2", "int", "fix"}};
auto projection = std::make_shared<Projection>(_gt_int, definitions);
projection->execute();
EXPECT_TABLE_EQ(projection->get_output(), expected_result);
}
TEST_F(OperatorsProjectionTest, VariableArithmeticProjection) {
std::shared_ptr<Table> expected_result = load_table("src/test/tables/int_int_int_addition.tbl", 2);
Projection::ProjectionDefinitions definitions{Projection::ProjectionDefinition{"$a+$b+$c", "int", "sum"}};
auto projection = std::make_shared<Projection>(_gt_int, definitions);
projection->execute();
EXPECT_TABLE_EQ(projection->get_output(), expected_result);
}
TEST_F(OperatorsProjectionTest, VariableArithmeticWithDictProjection) {
std::shared_ptr<Table> expected_result = load_table("src/test/tables/int_int_int_addition.tbl", 2);
Projection::ProjectionDefinitions definitions{Projection::ProjectionDefinition{"$a+$b+$c", "int", "sum"}};
auto projection = std::make_shared<Projection>(_gt_int_dict, definitions);
projection->execute();
EXPECT_TABLE_EQ(projection->get_output(), expected_result);
}
TEST_F(OperatorsProjectionTest, VariableArithmeticWithRefProjection) {
std::shared_ptr<Table> expected_result = load_table("src/test/tables/int_int_int_addition.tbl", 2);
// creates ref_columns
auto table_scan = std::make_shared<TableScan>(_gt_int_dict, "a", ">", "0");
table_scan->execute();
Projection::ProjectionDefinitions definitions{Projection::ProjectionDefinition{"$a+$b+$c", "int", "sum"}};
auto projection = std::make_shared<Projection>(table_scan, definitions);
projection->execute();
EXPECT_TABLE_EQ(projection->get_output(), expected_result);
}
TEST_F(OperatorsProjectionTest, ValueColumnCount) {
Projection::ProjectionDefinitions columns{Projection::ProjectionDefinition{"$a", "int", "a"},
Projection::ProjectionDefinition{"$b", "int", "b"}};
auto projection_1 = std::make_shared<opossum::Projection>(_gt, columns);
projection_1->execute();
EXPECT_EQ(projection_1->get_output()->col_count(), (u_int)2);
EXPECT_EQ(projection_1->get_output()->row_count(), (u_int)3);
columns = {Projection::ProjectionDefinition{"$b", "int", "b"}};
auto projection_2 = std::make_shared<opossum::Projection>(_gt, columns);
projection_2->execute();
EXPECT_EQ(projection_2->get_output()->col_count(), (u_int)1);
EXPECT_EQ(projection_2->get_output()->row_count(), (u_int)3);
columns = {Projection::ProjectionDefinition{"$a", "int", "a"}};
auto projection_3 = std::make_shared<opossum::Projection>(_gt, columns);
projection_3->execute();
EXPECT_EQ(projection_3->get_output()->col_count(), (u_int)1);
EXPECT_EQ(projection_3->get_output()->row_count(), (u_int)3);
}
// TODO(anyone): refactor test
TEST_F(OperatorsProjectionTest, ReferenceColumnCount) {
auto scan = std::make_shared<opossum::TableScan>(_gt, "a", "=", 1234);
scan->execute();
Projection::ProjectionDefinitions columns{Projection::ProjectionDefinition{"$a", "int", "a"},
Projection::ProjectionDefinition{"$b", "int", "b"}};
auto projection_1 = std::make_shared<opossum::Projection>(scan, columns);
projection_1->execute();
EXPECT_EQ(projection_1->get_output()->col_count(), (u_int)2);
EXPECT_EQ(projection_1->get_output()->row_count(), (u_int)1);
columns = {Projection::ProjectionDefinition{"$a", "int", "a"}};
auto projection_2 = std::make_shared<opossum::Projection>(scan, columns);
projection_2->execute();
EXPECT_EQ(projection_2->get_output()->col_count(), (u_int)1);
EXPECT_EQ(projection_2->get_output()->row_count(), (u_int)1);
columns = {Projection::ProjectionDefinition{"$b", "int", "b"}};
auto projection_3 = std::make_shared<opossum::Projection>(scan, columns);
projection_3->execute();
EXPECT_EQ(projection_3->get_output()->col_count(), (u_int)1);
EXPECT_EQ(projection_3->get_output()->row_count(), (u_int)1);
}
TEST_F(OperatorsProjectionTest, NumInputTables) {
Projection::ProjectionDefinitions columns = {Projection::ProjectionDefinition{"$a", "int", "a"},
Projection::ProjectionDefinition{"$b", "int", "b"}};
auto projection_1 = std::make_shared<opossum::Projection>(_gt, columns);
EXPECT_EQ(projection_1->num_in_tables(), 1);
}
TEST_F(OperatorsProjectionTest, NumOutputTables) {
Projection::ProjectionDefinitions columns = {Projection::ProjectionDefinition{"$a", "int", "a"},
Projection::ProjectionDefinition{"$b", "int", "b"}};
auto projection_1 = std::make_shared<opossum::Projection>(_gt, columns);
EXPECT_EQ(projection_1->num_out_tables(), 1);
}
TEST_F(OperatorsProjectionTest, OperatorName) {
Projection::ProjectionDefinitions columns = {Projection::ProjectionDefinition{"$a", "int", "a"},
Projection::ProjectionDefinition{"$b", "int", "b"}};
auto projection_1 = std::make_shared<opossum::Projection>(_gt, columns);
EXPECT_EQ(projection_1->name(), "Projection");
}
} // namespace opossum
<commit_msg>Fix build<commit_after>#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "../base_test.hpp"
#include "gtest/gtest.h"
#include "../../lib/operators/abstract_read_only_operator.hpp"
#include "../../lib/operators/get_table.hpp"
#include "../../lib/operators/print.hpp"
#include "../../lib/operators/projection.hpp"
#include "../../lib/operators/table_scan.hpp"
#include "../../lib/storage/storage_manager.hpp"
#include "../../lib/storage/table.hpp"
#include "../../lib/types.hpp"
namespace opossum {
class OperatorsProjectionTest : public BaseTest {
protected:
void SetUp() override {
std::shared_ptr<Table> test_table = load_table("src/test/tables/int_float.tbl", 2);
StorageManager::get().add_table("table_a", std::move(test_table));
_gt = std::make_shared<GetTable>("table_a");
_gt->execute();
std::shared_ptr<Table> test_table_int = load_table("src/test/tables/int_int_int.tbl", 2);
StorageManager::get().add_table("table_b", std::move(test_table_int));
_gt_int = std::make_shared<GetTable>("table_b");
_gt_int->execute();
std::shared_ptr<Table> test_table_dict = load_table("src/test/tables/int_int_int.tbl", 2);
test_table_dict->compress_chunk(0);
test_table_dict->compress_chunk(1);
StorageManager::get().add_table("table_c", std::move(test_table_dict));
_gt_int_dict = std::make_shared<GetTable>("table_c");
_gt_int_dict->execute();
}
std::shared_ptr<GetTable> _gt, _gt_int, _gt_int_dict;
};
TEST_F(OperatorsProjectionTest, SingleColumn) {
std::shared_ptr<Table> expected_result = load_table("src/test/tables/int.tbl", 1);
Projection::ProjectionDefinitions definitions({Projection::ProjectionDefinition{"$a", "int", "a"}});
auto projection = std::make_shared<Projection>(_gt, definitions);
projection->execute();
auto out = projection->get_output();
EXPECT_TABLE_EQ(projection->get_output(), expected_result);
}
TEST_F(OperatorsProjectionTest, SingleColumnOldInterface) {
std::shared_ptr<Table> expected_result = load_table("src/test/tables/int.tbl", 1);
std::vector<std::string> columns = {"a"};
auto projection = std::make_shared<Projection>(_gt, columns);
projection->execute();
auto out = projection->get_output();
EXPECT_TABLE_EQ(projection->get_output(), expected_result);
}
TEST_F(OperatorsProjectionTest, DoubleProject) {
std::shared_ptr<Table> expected_result = load_table("src/test/tables/int.tbl", 3);
Projection::ProjectionDefinitions definitions{Projection::ProjectionDefinition{"$a", "int", "a"}};
auto projection1 = std::make_shared<Projection>(_gt, definitions);
projection1->execute();
auto projection2 = std::make_shared<Projection>(projection1, definitions);
projection2->execute();
EXPECT_TABLE_EQ(projection2->get_output(), expected_result);
}
TEST_F(OperatorsProjectionTest, AllColumns) {
std::shared_ptr<Table> expected_result = load_table("src/test/tables/float_int.tbl", 2);
Projection::ProjectionDefinitions definitions{Projection::ProjectionDefinition{"$b", "float", "b"},
Projection::ProjectionDefinition{"$a", "int", "a"}};
auto projection = std::make_shared<Projection>(_gt, definitions);
projection->execute();
EXPECT_TABLE_EQ(projection->get_output(), expected_result);
}
TEST_F(OperatorsProjectionTest, ConstantArithmeticProjection) {
std::shared_ptr<Table> expected_result = load_table("src/test/tables/int_int_int_fix_values.tbl", 2);
Projection::ProjectionDefinitions definitions{Projection::ProjectionDefinition{"2+2", "int", "fix"}};
auto projection = std::make_shared<Projection>(_gt_int, definitions);
projection->execute();
EXPECT_TABLE_EQ(projection->get_output(), expected_result);
}
TEST_F(OperatorsProjectionTest, VariableArithmeticProjection) {
std::shared_ptr<Table> expected_result = load_table("src/test/tables/int_int_int_addition.tbl", 2);
Projection::ProjectionDefinitions definitions{Projection::ProjectionDefinition{"$a+$b+$c", "int", "sum"}};
auto projection = std::make_shared<Projection>(_gt_int, definitions);
projection->execute();
EXPECT_TABLE_EQ(projection->get_output(), expected_result);
}
TEST_F(OperatorsProjectionTest, VariableArithmeticWithDictProjection) {
std::shared_ptr<Table> expected_result = load_table("src/test/tables/int_int_int_addition.tbl", 2);
Projection::ProjectionDefinitions definitions{Projection::ProjectionDefinition{"$a+$b+$c", "int", "sum"}};
auto projection = std::make_shared<Projection>(_gt_int_dict, definitions);
projection->execute();
EXPECT_TABLE_EQ(projection->get_output(), expected_result);
}
TEST_F(OperatorsProjectionTest, VariableArithmeticWithRefProjection) {
std::shared_ptr<Table> expected_result = load_table("src/test/tables/int_int_int_addition.tbl", 2);
// creates ref_columns
auto table_scan = std::make_shared<TableScan>(_gt_int_dict, "a", ">", "0");
table_scan->execute();
Projection::ProjectionDefinitions definitions{Projection::ProjectionDefinition{"$a+$b+$c", "int", "sum"}};
auto projection = std::make_shared<Projection>(table_scan, definitions);
projection->execute();
EXPECT_TABLE_EQ(projection->get_output(), expected_result);
}
TEST_F(OperatorsProjectionTest, ValueColumnCount) {
Projection::ProjectionDefinitions columns{Projection::ProjectionDefinition{"$a", "int", "a"},
Projection::ProjectionDefinition{"$b", "int", "b"}};
auto projection_1 = std::make_shared<opossum::Projection>(_gt, columns);
projection_1->execute();
EXPECT_EQ(projection_1->get_output()->col_count(), (u_int)2);
EXPECT_EQ(projection_1->get_output()->row_count(), (u_int)3);
columns = {Projection::ProjectionDefinition{"$b", "int", "b"}};
auto projection_2 = std::make_shared<opossum::Projection>(_gt, columns);
projection_2->execute();
EXPECT_EQ(projection_2->get_output()->col_count(), (u_int)1);
EXPECT_EQ(projection_2->get_output()->row_count(), (u_int)3);
columns = {Projection::ProjectionDefinition{"$a", "int", "a"}};
auto projection_3 = std::make_shared<opossum::Projection>(_gt, columns);
projection_3->execute();
EXPECT_EQ(projection_3->get_output()->col_count(), (u_int)1);
EXPECT_EQ(projection_3->get_output()->row_count(), (u_int)3);
}
// TODO(anyone): refactor test
TEST_F(OperatorsProjectionTest, ReferenceColumnCount) {
auto scan = std::make_shared<opossum::TableScan>(_gt, "a", "=", 1234);
scan->execute();
Projection::ProjectionDefinitions columns{Projection::ProjectionDefinition{"$a", "int", "a"},
Projection::ProjectionDefinition{"$b", "int", "b"}};
auto projection_1 = std::make_shared<opossum::Projection>(scan, columns);
projection_1->execute();
EXPECT_EQ(projection_1->get_output()->col_count(), (u_int)2);
EXPECT_EQ(projection_1->get_output()->row_count(), (u_int)1);
columns = {Projection::ProjectionDefinition{"$a", "int", "a"}};
auto projection_2 = std::make_shared<opossum::Projection>(scan, columns);
projection_2->execute();
EXPECT_EQ(projection_2->get_output()->col_count(), (u_int)1);
EXPECT_EQ(projection_2->get_output()->row_count(), (u_int)1);
columns = {Projection::ProjectionDefinition{"$b", "int", "b"}};
auto projection_3 = std::make_shared<opossum::Projection>(scan, columns);
projection_3->execute();
EXPECT_EQ(projection_3->get_output()->col_count(), (u_int)1);
EXPECT_EQ(projection_3->get_output()->row_count(), (u_int)1);
}
TEST_F(OperatorsProjectionTest, NumInputTables) {
Projection::ProjectionDefinitions columns = {Projection::ProjectionDefinition{"$a", "int", "a"},
Projection::ProjectionDefinition{"$b", "int", "b"}};
auto projection_1 = std::make_shared<opossum::Projection>(_gt, columns);
EXPECT_EQ(projection_1->num_in_tables(), 1);
}
TEST_F(OperatorsProjectionTest, NumOutputTables) {
Projection::ProjectionDefinitions columns = {Projection::ProjectionDefinition{"$a", "int", "a"},
Projection::ProjectionDefinition{"$b", "int", "b"}};
auto projection_1 = std::make_shared<opossum::Projection>(_gt, columns);
EXPECT_EQ(projection_1->num_out_tables(), 1);
}
TEST_F(OperatorsProjectionTest, OperatorName) {
Projection::ProjectionDefinitions columns = {Projection::ProjectionDefinition{"$a", "int", "a"},
Projection::ProjectionDefinition{"$b", "int", "b"}};
auto projection_1 = std::make_shared<opossum::Projection>(_gt, columns);
EXPECT_EQ(projection_1->name(), "Projection");
}
} // namespace opossum
<|endoftext|> |
<commit_before>
#include "Filter.h" // Own interface
namespace samson{
namespace system{
SamsonTokenizer::SamsonTokenizer()
{
addSingleCharTokens("()[]{}<> ;&|?:,+-*/'|");
addToken(":[");
addToken("<=");
addToken(">=");
addToken("==");
addToken("!=");
addToken(" -only_key ");
addToken("select");
addToken("parse_words");
addToken("parse");
addToken("emit");
}
// --------------------------------------------------------
// FilterCollection
// --------------------------------------------------------
FilterCollection::~FilterCollection()
{
// Remove defined filters
filters.clearVector();
}
std::string FilterCollection::str()
{
std::ostringstream output;
for( size_t i = 0 ; i < filters.size() ; i++ )
output << filters[i]->str();
return output.str();
}
Filter* FilterCollection::getFilter( au::token::TokenVector *token_vector
, samson::KVWriter *writer
, TXTWriter *txt_writer
, au::ErrorManager* error
)
{
printf("getFilter: %s\n" , token_vector->str().c_str() );
// Check if there are tokens to be read
if( token_vector->eof() )
{
error->set("Filter name not specified");
return NULL;
}
// Get the next token
au::token::Token* token = token_vector->popToken();
if ( token->content == "select" )
{
Source* key_source = getSource(token_vector, error);
if( error->isActivated() )
return NULL;
// Expect a ","
if( !token_vector->popNextTokenIfItIs(",") )
{
error->set( au::str("Expected ',' to separate key and value in a select statment. Found '%s'"
, token_vector->getNextTokenContent().c_str() ));
return NULL;
}
Source* value_source = NULL;
if( !token_vector->eof() )
{
value_source = getSource(token_vector, error);
if( error->isActivated() )
return NULL;
}
else
value_source = new SourceVoid();
return new FilterSelect( key_source , value_source );
}
else if ( token->content == "parse_words" )
{
return new FilterParserWords();
}
else if ( token->content == "parse_chars" )
{
return new FilterParserChars();
}
else if ( token->content == "parse" )
{
// Parse kind of filter
return FilterParser::getFilter( token_vector , error );
}
else if ( token->content == "emit" )
{
if( writer )
{
if( token_vector->eof() )
return new FilterEmit( 0 , writer ); // Default channel "0"
au::token::Token* number = token_vector->popToken();
if( !number->isNumber() )
{
error->set( au::str("Channel '%s' not valid in emit command. It should be a number"
, number->content.c_str() ));
return NULL;
}
int channel = atoi( number->content.c_str() );
return new FilterEmit( channel , writer );
}
else if ( txt_writer )
{
FilterEmitTxt * filter_emit = new FilterEmitTxt( txt_writer , token_vector , error );
if( error->isActivated() )
{
delete filter_emit;
return NULL;
}
return filter_emit;
}
}
else if ( token->content == "filter" )
{
Source* eval_source = getSource(token_vector, error );
if( error->isActivated() )
return NULL;
if( !eval_source )
{
error->set("Not valid condition statment in filter command");
return NULL;
}
return new FilterCondition( eval_source );
}
return NULL;
}
// filter key = 67 | select key:1,value | emit 0 / filter key = 56 | select key:1,value | emit 1
Filter* FilterCollection::getFilterChain( au::token::TokenVector *token_vector
, samson::KVWriter *writer
, TXTWriter *txt_writer
, au::ErrorManager* error )
{
printf("getFilterChain: %s\n" , token_vector->str().c_str() );
// Line of filters for this command...
au::vector<Filter> tmp_filters;
while ( !token_vector->eof() )
{
// Get the "sub" token vector for each line
au::token::TokenVector sub_token_vector = token_vector->getTokensUntil( "|" );
// Get a filter from this token_vector
Filter * filter = getFilter( &sub_token_vector , writer , txt_writer , error );
// If there is an error, just return
if( error->isActivated() )
{
tmp_filters.clearVector();
return NULL;
}
else
{
// Add the new filter
tmp_filters.push_back( filter );
}
}
if( tmp_filters.size() == 0 )
return NULL;
// Link the filters
for ( size_t i = 0 ; i < (tmp_filters.size()-1) ; i++ )
tmp_filters[i]->next = tmp_filters[i+1];
// Add the filter line
return tmp_filters[0];
}
// General command to parse
void FilterCollection::addFilters( std::string command
, samson::KVWriter *writer
, TXTWriter *txt_writer
, au::ErrorManager* error )
{
// Tokenice the entire command
// --------------------------------------------------------------------
SamsonTokenizer tokenizer;
au::token::TokenVector token_vector = tokenizer.parse(command);
printf("Adding filters from '%s'\n" , command.c_str() );
printf("Tokens: %s\n" , token_vector.str().c_str() );
while ( !token_vector.eof() )
{
// Get the "sub" token vector for each line
au::token::TokenVector sub_token_vector = token_vector.getTokensUntil( ";" );
printf("Tokens line: %s\n" , sub_token_vector.str().c_str() );
// Get a filter from this token_vector
Filter * filter = getFilterChain( &sub_token_vector , writer , txt_writer , error );
printf("Filter: %s\n" , filter->str().c_str() );
// If there is an error, just return
if( error->isActivated() )
{
printf("Error: %s\n", error->getMessage().c_str() );
filters.clearVector();
return;
}
else
{
// Add the new filter
filters.push_back( filter );
}
}
printf("Created %lu filters\n" , filters.size() );
}
void FilterCollection::run( KeyValue kv )
{
for( size_t f = 0 ; f < filters.size() ; f++ )
filters[f]->run(kv);
}
size_t FilterCollection::get_num_filters()
{
return filters.size();
}
}
}<commit_msg>Removing old printfs<commit_after>
#include "Filter.h" // Own interface
namespace samson{
namespace system{
SamsonTokenizer::SamsonTokenizer()
{
addSingleCharTokens("()[]{}<> ;&|?:,+-*/'|");
addToken(":[");
addToken("<=");
addToken(">=");
addToken("==");
addToken("!=");
addToken(" -only_key ");
addToken("select");
addToken("parse_words");
addToken("parse");
addToken("emit");
}
// --------------------------------------------------------
// FilterCollection
// --------------------------------------------------------
FilterCollection::~FilterCollection()
{
// Remove defined filters
filters.clearVector();
}
std::string FilterCollection::str()
{
std::ostringstream output;
for( size_t i = 0 ; i < filters.size() ; i++ )
output << filters[i]->str();
return output.str();
}
Filter* FilterCollection::getFilter( au::token::TokenVector *token_vector
, samson::KVWriter *writer
, TXTWriter *txt_writer
, au::ErrorManager* error
)
{
// Check if there are tokens to be read
if( token_vector->eof() )
{
error->set("Filter name not specified");
return NULL;
}
// Get the next token
au::token::Token* token = token_vector->popToken();
if ( token->content == "select" )
{
Source* key_source = getSource(token_vector, error);
if( error->isActivated() )
return NULL;
// Expect a ","
if( !token_vector->popNextTokenIfItIs(",") )
{
error->set( au::str("Expected ',' to separate key and value in a select statment. Found '%s'"
, token_vector->getNextTokenContent().c_str() ));
return NULL;
}
Source* value_source = NULL;
if( !token_vector->eof() )
{
value_source = getSource(token_vector, error);
if( error->isActivated() )
return NULL;
}
else
value_source = new SourceVoid();
return new FilterSelect( key_source , value_source );
}
else if ( token->content == "parse_words" )
{
return new FilterParserWords();
}
else if ( token->content == "parse_chars" )
{
return new FilterParserChars();
}
else if ( token->content == "parse" )
{
// Parse kind of filter
return FilterParser::getFilter( token_vector , error );
}
else if ( token->content == "emit" )
{
if( writer )
{
if( token_vector->eof() )
return new FilterEmit( 0 , writer ); // Default channel "0"
au::token::Token* number = token_vector->popToken();
if( !number->isNumber() )
{
error->set( au::str("Channel '%s' not valid in emit command. It should be a number"
, number->content.c_str() ));
return NULL;
}
int channel = atoi( number->content.c_str() );
return new FilterEmit( channel , writer );
}
else if ( txt_writer )
{
FilterEmitTxt * filter_emit = new FilterEmitTxt( txt_writer , token_vector , error );
if( error->isActivated() )
{
delete filter_emit;
return NULL;
}
return filter_emit;
}
}
else if ( token->content == "filter" )
{
Source* eval_source = getSource(token_vector, error );
if( error->isActivated() )
return NULL;
if( !eval_source )
{
error->set("Not valid condition statment in filter command");
return NULL;
}
return new FilterCondition( eval_source );
}
return NULL;
}
// filter key = 67 | select key:1,value | emit 0 / filter key = 56 | select key:1,value | emit 1
Filter* FilterCollection::getFilterChain( au::token::TokenVector *token_vector
, samson::KVWriter *writer
, TXTWriter *txt_writer
, au::ErrorManager* error )
{
// Line of filters for this command...
au::vector<Filter> tmp_filters;
while ( !token_vector->eof() )
{
// Get the "sub" token vector for each line
au::token::TokenVector sub_token_vector = token_vector->getTokensUntil( "|" );
// Get a filter from this token_vector
Filter * filter = getFilter( &sub_token_vector , writer , txt_writer , error );
// If there is an error, just return
if( error->isActivated() )
{
tmp_filters.clearVector();
return NULL;
}
else
{
// Add the new filter
tmp_filters.push_back( filter );
}
}
if( tmp_filters.size() == 0 )
return NULL;
// Link the filters
for ( size_t i = 0 ; i < (tmp_filters.size()-1) ; i++ )
tmp_filters[i]->next = tmp_filters[i+1];
// Add the filter line
return tmp_filters[0];
}
// General command to parse
void FilterCollection::addFilters( std::string command
, samson::KVWriter *writer
, TXTWriter *txt_writer
, au::ErrorManager* error )
{
// Tokenice the entire command
// --------------------------------------------------------------------
SamsonTokenizer tokenizer;
au::token::TokenVector token_vector = tokenizer.parse(command);
while ( !token_vector.eof() )
{
// Get the "sub" token vector for each line
au::token::TokenVector sub_token_vector = token_vector.getTokensUntil( ";" );
// Get a filter from this token_vector
Filter * filter = getFilterChain( &sub_token_vector , writer , txt_writer , error );
// If there is an error, just return
if( error->isActivated() )
{
filters.clearVector();
return;
}
else
{
// Add the new filter
filters.push_back( filter );
}
}
}
void FilterCollection::run( KeyValue kv )
{
for( size_t f = 0 ; f < filters.size() ; f++ )
filters[f]->run(kv);
}
size_t FilterCollection::get_num_filters()
{
return filters.size();
}
}
}<|endoftext|> |
<commit_before>// Copyright (c) 2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/test/unit_test.hpp>
#include <consensus/validation.h>
#include <primitives/block.h>
#include <scheduler.h>
#include <test/util/setup_common.h>
#include <util/check.h>
#include <validationinterface.h>
BOOST_FIXTURE_TEST_SUITE(validationinterface_tests, TestingSetup)
class TestInterface : public CValidationInterface
{
public:
TestInterface(std::function<void()> on_call = nullptr, std::function<void()> on_destroy = nullptr)
: m_on_call(std::move(on_call)), m_on_destroy(std::move(on_destroy))
{
}
virtual ~TestInterface()
{
if (m_on_destroy) m_on_destroy();
}
void BlockChecked(const CBlock& block, const BlockValidationState& state) override
{
if (m_on_call) m_on_call();
}
static void Call()
{
CBlock block;
BlockValidationState state;
GetMainSignals().BlockChecked(block, state);
}
std::function<void()> m_on_call;
std::function<void()> m_on_destroy;
};
// Regression test to ensure UnregisterAllValidationInterfaces calls don't
// destroy a validation interface while it is being called. Bug:
// https://github.com/bitcoin/bitcoin/pull/18551
BOOST_AUTO_TEST_CASE(unregister_all_during_call)
{
bool destroyed = false;
RegisterSharedValidationInterface(std::make_shared<TestInterface>(
[&] {
// First call should decrements reference count 2 -> 1
UnregisterAllValidationInterfaces();
BOOST_CHECK(!destroyed);
// Second call should not decrement reference count 1 -> 0
UnregisterAllValidationInterfaces();
BOOST_CHECK(!destroyed);
},
[&] { destroyed = true; }));
TestInterface::Call();
BOOST_CHECK(destroyed);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>test: Add unregister_validation_interface_race test<commit_after>// Copyright (c) 2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/test/unit_test.hpp>
#include <consensus/validation.h>
#include <primitives/block.h>
#include <scheduler.h>
#include <test/util/setup_common.h>
#include <util/check.h>
#include <validationinterface.h>
BOOST_FIXTURE_TEST_SUITE(validationinterface_tests, TestingSetup)
/**
struct TestSubscriberNoop final : public CValidationInterface {
void BlockChecked(const CBlock&, const BlockValidationState&) override {}
};
BOOST_AUTO_TEST_CASE(unregister_validation_interface_race)
{
std::atomic<bool> generate{true};
// Start thread to generate notifications
std::thread gen{[&] {
const CBlock block_dummy;
const BlockValidationState state_dummy;
while (generate) {
GetMainSignals().BlockChecked(block_dummy, state_dummy);
}
}};
// Start thread to consume notifications
std::thread sub{[&] {
// keep going for about 1 sec, which is 250k iterations
for (int i = 0; i < 250000; i++) {
TestSubscriberNoop sub{};
RegisterValidationInterface(&sub);
UnregisterValidationInterface(&sub);
}
// tell the other thread we are done
generate = false;
}};
gen.join();
sub.join();
BOOST_CHECK(!generate);
}
*/
class TestInterface : public CValidationInterface
{
public:
TestInterface(std::function<void()> on_call = nullptr, std::function<void()> on_destroy = nullptr)
: m_on_call(std::move(on_call)), m_on_destroy(std::move(on_destroy))
{
}
virtual ~TestInterface()
{
if (m_on_destroy) m_on_destroy();
}
void BlockChecked(const CBlock& block, const BlockValidationState& state) override
{
if (m_on_call) m_on_call();
}
static void Call()
{
CBlock block;
BlockValidationState state;
GetMainSignals().BlockChecked(block, state);
}
std::function<void()> m_on_call;
std::function<void()> m_on_destroy;
};
// Regression test to ensure UnregisterAllValidationInterfaces calls don't
// destroy a validation interface while it is being called. Bug:
// https://github.com/bitcoin/bitcoin/pull/18551
BOOST_AUTO_TEST_CASE(unregister_all_during_call)
{
bool destroyed = false;
RegisterSharedValidationInterface(std::make_shared<TestInterface>(
[&] {
// First call should decrements reference count 2 -> 1
UnregisterAllValidationInterfaces();
BOOST_CHECK(!destroyed);
// Second call should not decrement reference count 1 -> 0
UnregisterAllValidationInterfaces();
BOOST_CHECK(!destroyed);
},
[&] { destroyed = true; }));
TestInterface::Call();
BOOST_CHECK(destroyed);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/*-------------------------------------------------------------------------
*
* database.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /n-store/src/storage/table.cpp
*
*-------------------------------------------------------------------------
*/
#include "backend/storage/database.h"
#include "backend/storage/table_factory.h"
#include "backend/common/logger.h"
#include <sstream>
namespace peloton {
namespace storage {
Database::~Database() {
// Clean up all the tables
for (auto table : tables) delete table;
}
//===--------------------------------------------------------------------===//
// TABLE
//===--------------------------------------------------------------------===//
void Database::AddTable(storage::DataTable* table) {
{
std::lock_guard<std::mutex> lock(database_mutex);
tables.push_back(table);
}
}
storage::DataTable* Database::GetTableWithOid(const oid_t table_oid) const {
for (auto table : tables)
if (table->GetOid() == table_oid) return table;
return nullptr;
}
storage::DataTable* Database::GetTableWithName(
const std::string table_name) const {
for (auto table : tables)
if (table->GetName() == table_name) return table;
return nullptr;
}
void Database::DropTableWithOid(const oid_t table_oid) {
{
std::lock_guard<std::mutex> lock(database_mutex);
oid_t table_offset = 0;
for (auto table : tables) {
if (table->GetOid() == table_oid) break;
table_offset++;
}
assert(table_offset < tables.size());
// Drop the database
tables.erase(tables.begin() + table_offset);
}
}
storage::DataTable* Database::GetTable(const oid_t table_offset) const {
assert(table_offset < tables.size());
auto table = tables.at(table_offset);
return table;
}
oid_t Database::GetTableCount() const { return tables.size(); }
//===--------------------------------------------------------------------===//
// STATS
//===--------------------------------------------------------------------===//
void Database::UpdateStats(Peloton_Status* status){
LOG_INFO("Update All Stats in Database(%u)", database_oid);
// TODO :: need to check whether ... table... is changed or not
std::vector<dirty_table_info*> dirty_tables;
for( int table_offset=0; table_offset<GetTableCount(); table_offset++){
auto table = GetTable(table_offset);
std::vector<dirty_index_info*> dirty_indexes;
for (int index_offset = 0; index_offset < table->GetIndexCount(); index_offset++) {
auto index = table->GetIndex(index_offset);
auto dirty_index = CreateDirtyIndex(index->GetOid(), index->GetNumberOfTuples());
dirty_indexes.push_back(dirty_index);
}
auto dirty_table = CreateDirtyTable(table->GetOid(),
table->GetNumberOfTuples(),
CreateDirtyIndexes(dirty_indexes),
dirty_indexes.size());
dirty_tables.push_back(dirty_table);
}
status->m_dirty_tables = CreateDirtyTables(dirty_tables);
status->m_dirty_count = dirty_tables.size();
}
void Database::UpdateStatsWithOid(const oid_t table_oid){
LOG_INFO("Update table(%u)'s stats in Database(%u)", table_oid, database_oid);
auto table = GetTableWithOid(table_oid);
bridge::Bridge::SetNumberOfTuples(table_oid, table->GetNumberOfTuples());
for (int index_offset = 0; index_offset < table->GetIndexCount();
index_offset++) {
auto index = table->GetIndex(index_offset);
bridge::Bridge::SetNumberOfTuples(index->GetOid(),
index->GetNumberOfTuples());
}
}
//===--------------------------------------------------------------------===//
// UTILITIES
//===--------------------------------------------------------------------===//
dirty_table_info** Database::CreateDirtyTables(std::vector< dirty_table_info*> dirty_tables_vec){
//XXX:: TopSharedMem???
dirty_table_info** dirty_tables = (dirty_table_info**)palloc(sizeof(dirty_table_info*)*dirty_tables_vec.size());
oid_t table_itr=0;
for(auto dirty_table : dirty_tables_vec)
dirty_tables[table_itr] = dirty_table;
return dirty_tables;
}
dirty_index_info** Database::CreateDirtyIndexes(std::vector< dirty_index_info*> dirty_indexes_vec){
dirty_index_info** dirty_indexes = (dirty_index_info**)palloc(sizeof(dirty_index_info*)*dirty_indexes_vec.size());
oid_t index_itr=0;
for(auto dirty_index : dirty_indexes_vec)
dirty_indexes[index_itr] = dirty_index;
return dirty_indexes;
}
dirty_table_info* Database::CreateDirtyTable(oid_t table_oid, float number_of_tuples, dirty_index_info** dirty_indexes, oid_t index_count){
dirty_table_info* dirty_table = (dirty_table_info*)palloc(sizeof(dirty_table_info));
dirty_table->table_oid = table_oid;
dirty_table->number_of_tuples = number_of_tuples;
dirty_table->dirty_indexes = dirty_indexes;
dirty_table->index_count = index_count;
return dirty_table;
}
dirty_index_info* Database::CreateDirtyIndex(oid_t index_oid, float number_of_tuples){
dirty_index_info* dirty_index = (dirty_index_info*)palloc(sizeof(dirty_index_info));
dirty_index->index_oid = index_oid;
dirty_index->number_of_tuples = number_of_tuples;
return dirty_index;
}
std::ostream& operator<<(std::ostream& os, const Database& database) {
os << "=====================================================\n";
os << "DATABASE(" << database.GetOid() << ") : \n";
oid_t table_count = database.GetTableCount();
std::cout << "Table Count : " << table_count << "\n";
oid_t table_itr = 0;
for (auto table : database.tables) {
if (table != nullptr) {
std::cout << "(" << ++table_itr << "/" << table_count << ") "
<< "Table Name(" << table->GetOid() << ") : " << table->GetName() << "\n"
<< *(table->GetSchema()) << std::endl;
oid_t index_count = table->GetIndexCount();
if (index_count > 0) {
std::cout << "Index Count : " << index_count << std::endl;
for (int index_itr = 0; index_itr < index_count; index_itr++) {
index::Index* index = table->GetIndex(index_itr);
switch (index->GetIndexType()) {
case INDEX_CONSTRAINT_TYPE_PRIMARY_KEY:
std::cout << "primary key index \n";
break;
case INDEX_CONSTRAINT_TYPE_UNIQUE:
std::cout << "unique index \n";
break;
default:
std::cout << "default index \n";
break;
}
std::cout << *index << std::endl;
}
}
if (table->HasForeignKeys()) {
std::cout << "foreign tables \n";
oid_t foreign_key_count = table->GetForeignKeyCount();
for (int foreign_key_itr = 0; foreign_key_itr < foreign_key_count;
foreign_key_itr++) {
auto foreign_key = table->GetForeignKey(foreign_key_itr);
auto sink_table_oid = foreign_key->GetSinkTableOid();
auto sink_table = database.GetTableWithOid(sink_table_oid);
auto sink_table_schema = sink_table->GetSchema();
std::cout << "table name : " << sink_table->GetName() << " "
<< *sink_table_schema << std::endl;
}
}
}
}
os << "=====================================================\n";
return os;
}
} // End storage namespace
} // End peloton namespace
<commit_msg>Used shared memory for dirty tables<commit_after>/*-------------------------------------------------------------------------
*
* database.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /n-store/src/storage/table.cpp
*
*-------------------------------------------------------------------------
*/
#include "backend/storage/database.h"
#include "backend/storage/table_factory.h"
#include "backend/common/logger.h"
#include <sstream>
namespace peloton {
namespace storage {
Database::~Database() {
// Clean up all the tables
for (auto table : tables) delete table;
}
//===--------------------------------------------------------------------===//
// TABLE
//===--------------------------------------------------------------------===//
void Database::AddTable(storage::DataTable* table) {
{
std::lock_guard<std::mutex> lock(database_mutex);
tables.push_back(table);
}
}
storage::DataTable* Database::GetTableWithOid(const oid_t table_oid) const {
for (auto table : tables)
if (table->GetOid() == table_oid) return table;
return nullptr;
}
storage::DataTable* Database::GetTableWithName(
const std::string table_name) const {
for (auto table : tables)
if (table->GetName() == table_name) return table;
return nullptr;
}
void Database::DropTableWithOid(const oid_t table_oid) {
{
std::lock_guard<std::mutex> lock(database_mutex);
oid_t table_offset = 0;
for (auto table : tables) {
if (table->GetOid() == table_oid) break;
table_offset++;
}
assert(table_offset < tables.size());
// Drop the database
tables.erase(tables.begin() + table_offset);
}
}
storage::DataTable* Database::GetTable(const oid_t table_offset) const {
assert(table_offset < tables.size());
auto table = tables.at(table_offset);
return table;
}
oid_t Database::GetTableCount() const { return tables.size(); }
//===--------------------------------------------------------------------===//
// STATS
//===--------------------------------------------------------------------===//
void Database::UpdateStats(Peloton_Status* status){
LOG_INFO("Update All Stats in Database(%u)", database_oid);
// TODO :: need to check whether ... table... is changed or not
std::vector<dirty_table_info*> dirty_tables;
for( int table_offset=0; table_offset<GetTableCount(); table_offset++){
auto table = GetTable(table_offset);
std::vector<dirty_index_info*> dirty_indexes;
for (int index_offset = 0; index_offset < table->GetIndexCount(); index_offset++) {
auto index = table->GetIndex(index_offset);
auto dirty_index = CreateDirtyIndex(index->GetOid(), index->GetNumberOfTuples());
dirty_indexes.push_back(dirty_index);
}
auto dirty_table = CreateDirtyTable(table->GetOid(),
table->GetNumberOfTuples(),
CreateDirtyIndexes(dirty_indexes),
dirty_indexes.size());
dirty_tables.push_back(dirty_table);
}
status->m_dirty_tables = CreateDirtyTables(dirty_tables);
status->m_dirty_count = dirty_tables.size();
}
void Database::UpdateStatsWithOid(const oid_t table_oid){
LOG_INFO("Update table(%u)'s stats in Database(%u)", table_oid, database_oid);
auto table = GetTableWithOid(table_oid);
bridge::Bridge::SetNumberOfTuples(table_oid, table->GetNumberOfTuples());
for (int index_offset = 0; index_offset < table->GetIndexCount();
index_offset++) {
auto index = table->GetIndex(index_offset);
bridge::Bridge::SetNumberOfTuples(index->GetOid(),
index->GetNumberOfTuples());
}
}
//===--------------------------------------------------------------------===//
// UTILITIES
//===--------------------------------------------------------------------===//
dirty_table_info** Database::CreateDirtyTables(std::vector< dirty_table_info*> dirty_tables_vec){
//XXX:: TopSharedMem???
MemoryContext oldcxt = MemoryContextSwitchTo(TopSharedMemoryContext);
dirty_table_info** dirty_tables = (dirty_table_info**)palloc(sizeof(dirty_table_info*)*dirty_tables_vec.size());
MemoryContextSwitchTo(oldcxt);
oid_t table_itr=0;
for(auto dirty_table : dirty_tables_vec)
dirty_tables[table_itr] = dirty_table;
return dirty_tables;
}
dirty_index_info** Database::CreateDirtyIndexes(std::vector< dirty_index_info*> dirty_indexes_vec){
MemoryContext oldcxt = MemoryContextSwitchTo(TopSharedMemoryContext);
dirty_index_info** dirty_indexes = (dirty_index_info**)palloc(sizeof(dirty_index_info*)*dirty_indexes_vec.size());
MemoryContextSwitchTo(oldcxt);
oid_t index_itr=0;
for(auto dirty_index : dirty_indexes_vec)
dirty_indexes[index_itr] = dirty_index;
return dirty_indexes;
}
dirty_table_info* Database::CreateDirtyTable(oid_t table_oid, float number_of_tuples, dirty_index_info** dirty_indexes, oid_t index_count){
MemoryContext oldcxt = MemoryContextSwitchTo(TopSharedMemoryContext);
dirty_table_info* dirty_table = (dirty_table_info*)palloc(sizeof(dirty_table_info));
MemoryContextSwitchTo(oldcxt);
dirty_table->table_oid = table_oid;
dirty_table->number_of_tuples = number_of_tuples;
dirty_table->dirty_indexes = dirty_indexes;
dirty_table->index_count = index_count;
return dirty_table;
}
dirty_index_info* Database::CreateDirtyIndex(oid_t index_oid, float number_of_tuples){
MemoryContext oldcxt = MemoryContextSwitchTo(TopSharedMemoryContext);
dirty_index_info* dirty_index = (dirty_index_info*)palloc(sizeof(dirty_index_info));
MemoryContextSwitchTo(oldcxt);
dirty_index->index_oid = index_oid;
dirty_index->number_of_tuples = number_of_tuples;
return dirty_index;
}
std::ostream& operator<<(std::ostream& os, const Database& database) {
os << "=====================================================\n";
os << "DATABASE(" << database.GetOid() << ") : \n";
oid_t table_count = database.GetTableCount();
std::cout << "Table Count : " << table_count << "\n";
oid_t table_itr = 0;
for (auto table : database.tables) {
if (table != nullptr) {
std::cout << "(" << ++table_itr << "/" << table_count << ") "
<< "Table Name(" << table->GetOid() << ") : " << table->GetName() << "\n"
<< *(table->GetSchema()) << std::endl;
oid_t index_count = table->GetIndexCount();
if (index_count > 0) {
std::cout << "Index Count : " << index_count << std::endl;
for (int index_itr = 0; index_itr < index_count; index_itr++) {
index::Index* index = table->GetIndex(index_itr);
switch (index->GetIndexType()) {
case INDEX_CONSTRAINT_TYPE_PRIMARY_KEY:
std::cout << "primary key index \n";
break;
case INDEX_CONSTRAINT_TYPE_UNIQUE:
std::cout << "unique index \n";
break;
default:
std::cout << "default index \n";
break;
}
std::cout << *index << std::endl;
}
}
if (table->HasForeignKeys()) {
std::cout << "foreign tables \n";
oid_t foreign_key_count = table->GetForeignKeyCount();
for (int foreign_key_itr = 0; foreign_key_itr < foreign_key_count;
foreign_key_itr++) {
auto foreign_key = table->GetForeignKey(foreign_key_itr);
auto sink_table_oid = foreign_key->GetSinkTableOid();
auto sink_table = database.GetTableWithOid(sink_table_oid);
auto sink_table_schema = sink_table->GetSchema();
std::cout << "table name : " << sink_table->GetName() << " "
<< *sink_table_schema << std::endl;
}
}
}
}
os << "=====================================================\n";
return os;
}
} // End storage namespace
} // End peloton namespace
<|endoftext|> |
<commit_before>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */
#include "themebusinesslogic.h"
#include "themedescriptor.h"
#include <QDir>
#include <QFile>
#include <QString>
#include <QStringList>
#include <MTheme>
#include <MGConfItem>
#include "../debug.h"
// The directory where all the available themes are installed.
static const QString themeDirName ("/usr/share/themes");
// The GCon key where meegotouch expects us to place the theme name.
static const QString themeGConfKey ("/meegotouch/theme/name");
/*!
* Returns the code name of the current theme. This code name can be used as a
* string ID to the GConf database.
*/
QString
ThemeBusinessLogic::currentThemeCodeName () const
{
MTheme *theme = MTheme::instance();
Q_ASSERT (theme != 0);
return theme->currentTheme();
}
/*!
* Returns the official name of the current theme. This name can be used as a UI
* string.
*/
QString
ThemeBusinessLogic::currentThemeName () const
{
QString codeName = currentThemeCodeName();
QList<ThemeDescriptor *> list = availableThemes ();
QString retval;
foreach (ThemeDescriptor *descr, list) {
if (descr->codeName() == codeName)
retval = descr->name();
delete descr;
}
return retval;
}
/*!
* Returns the official name of the current theme. This name can be used as a UI
* string.
*/
QString
ThemeBusinessLogic::currentThemeIconName () const
{
QString codeName = currentThemeCodeName();
QList<ThemeDescriptor *> list = availableThemes ();
QString retval;
foreach (ThemeDescriptor *descr, list) {
if (descr->codeName() == codeName)
retval = descr->iconName();
delete descr;
}
return retval;
}
/*!
* Returns all the available themes. Please note, that some of these themes
* might be hidden/invisible.
*/
QList<ThemeDescriptor *>
ThemeBusinessLogic::availableThemes () const
{
QList<ThemeDescriptor *> retval;
QDir themeDir (themeDirName);
foreach (QString themeFile, themeDir.entryList (QDir::Dirs)) {
ThemeDescriptor *descr;
if (themeFile == "." ||
themeFile == "..")
continue;
descr = new ThemeDescriptor (
themeDirName + "/" + themeFile,
themeFile);
if (descr->isValid())
retval << descr;
else
delete descr;
}
return retval;
}
/*!
* This function can be used to change the current theme.
*/
void
ThemeBusinessLogic::changeTheme (
QString themeCodeName)
{
SYS_DEBUG ("Activating theme '%s'", SYS_STR(themeCodeName));
MGConfItem gconfItem (themeGConfKey);
gconfItem.set (themeCodeName);
emit themeChanged (themeCodeName);
}
<commit_msg>filter out invisible themes<commit_after>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */
#include "themebusinesslogic.h"
#include "themedescriptor.h"
#include <QDir>
#include <QFile>
#include <QString>
#include <QStringList>
#include <MTheme>
#include <MGConfItem>
#include "../debug.h"
// The directory where all the available themes are installed.
static const QString themeDirName ("/usr/share/themes");
// The GCon key where meegotouch expects us to place the theme name.
static const QString themeGConfKey ("/meegotouch/theme/name");
/*!
* Returns the code name of the current theme. This code name can be used as a
* string ID to the GConf database.
*/
QString
ThemeBusinessLogic::currentThemeCodeName () const
{
MTheme *theme = MTheme::instance();
Q_ASSERT (theme != 0);
return theme->currentTheme();
}
/*!
* Returns the official name of the current theme. This name can be used as a UI
* string.
*/
QString
ThemeBusinessLogic::currentThemeName () const
{
QString codeName = currentThemeCodeName();
QList<ThemeDescriptor *> list = availableThemes ();
QString retval;
foreach (ThemeDescriptor *descr, list) {
if (descr->codeName() == codeName)
retval = descr->name();
delete descr;
}
return retval;
}
/*!
* Returns the official name of the current theme. This name can be used as a UI
* string.
*/
QString
ThemeBusinessLogic::currentThemeIconName () const
{
QString codeName = currentThemeCodeName();
QList<ThemeDescriptor *> list = availableThemes ();
QString retval;
foreach (ThemeDescriptor *descr, list) {
if (descr->codeName() == codeName)
retval = descr->iconName();
delete descr;
}
return retval;
}
/*!
* Returns all the available themes.
* Invisible themes are filtered out.
*/
QList<ThemeDescriptor *>
ThemeBusinessLogic::availableThemes () const
{
QList<ThemeDescriptor *> retval;
QDir themeDir (themeDirName);
foreach (QString themeFile, themeDir.entryList (QDir::Dirs)) {
ThemeDescriptor *descr;
if (themeFile == "." ||
themeFile == "..")
continue;
descr = new ThemeDescriptor (
themeDirName + "/" + themeFile,
themeFile);
if (descr->isValid() && descr->isVisible())
retval << descr;
else
delete descr;
}
return retval;
}
/*!
* This function can be used to change the current theme.
*/
void
ThemeBusinessLogic::changeTheme (
QString themeCodeName)
{
SYS_DEBUG ("Activating theme '%s'", SYS_STR(themeCodeName));
MGConfItem gconfItem (themeGConfKey);
gconfItem.set (themeCodeName);
emit themeChanged (themeCodeName);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/traced/service/builtin_producer.h"
#include <sys/types.h>
#include <unistd.h>
#include "perfetto/base/build_config.h"
#include "perfetto/base/logging.h"
#include "perfetto/ext/base/metatrace.h"
#include "perfetto/ext/base/weak_ptr.h"
#include "perfetto/ext/tracing/core/basic_types.h"
#include "perfetto/ext/tracing/core/trace_writer.h"
#include "perfetto/ext/tracing/core/tracing_service.h"
#include "perfetto/tracing/core/data_source_config.h"
#include "perfetto/tracing/core/data_source_descriptor.h"
#include "src/tracing/core/metatrace_writer.h"
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#include <sys/system_properties.h>
#endif
namespace perfetto {
namespace {
constexpr char kHeapprofdDataSourceName[] = "android.heapprofd";
constexpr char kJavaHprofDataSourceName[] = "android.java_hprof";
constexpr char kLazyHeapprofdPropertyName[] = "traced.lazy.heapprofd";
} // namespace
BuiltinProducer::BuiltinProducer(base::TaskRunner* task_runner,
uint32_t lazy_stop_delay_ms)
: task_runner_(task_runner), weak_factory_(this) {
lazy_heapprofd_.stop_delay_ms = lazy_stop_delay_ms;
}
BuiltinProducer::~BuiltinProducer() {
if (!lazy_heapprofd_.instance_ids.empty())
SetAndroidProperty(kLazyHeapprofdPropertyName, "0");
}
void BuiltinProducer::ConnectInProcess(TracingService* svc) {
endpoint_ = svc->ConnectProducer(this, geteuid(), "traced",
/*shm_hint_kb*/ 16, /*in_process*/ true);
}
void BuiltinProducer::OnConnect() {
DataSourceDescriptor metatrace_dsd;
metatrace_dsd.set_name(MetatraceWriter::kDataSourceName);
metatrace_dsd.set_will_notify_on_stop(true);
endpoint_->RegisterDataSource(metatrace_dsd);
{
DataSourceDescriptor lazy_heapprofd_dsd;
lazy_heapprofd_dsd.set_name(kHeapprofdDataSourceName);
endpoint_->RegisterDataSource(lazy_heapprofd_dsd);
}
{
DataSourceDescriptor lazy_java_hprof_dsd;
lazy_java_hprof_dsd.set_name(kJavaHprofDataSourceName);
endpoint_->RegisterDataSource(lazy_java_hprof_dsd);
}
}
void BuiltinProducer::SetupDataSource(DataSourceInstanceID ds_id,
const DataSourceConfig& ds_config) {
if (ds_config.name() == kHeapprofdDataSourceName ||
ds_config.name() == kJavaHprofDataSourceName) {
SetAndroidProperty(kLazyHeapprofdPropertyName, "1");
lazy_heapprofd_.generation++;
lazy_heapprofd_.instance_ids.emplace(ds_id);
}
}
void BuiltinProducer::StartDataSource(DataSourceInstanceID ds_id,
const DataSourceConfig& ds_config) {
// We slightly rely on the fact that since this producer is in-process for
// enabling metatrace early (relative to producers that are notified via IPC).
if (ds_config.name() == MetatraceWriter::kDataSourceName) {
auto writer = endpoint_->CreateTraceWriter(
static_cast<BufferID>(ds_config.target_buffer()));
auto it_and_inserted = metatrace_.writers.emplace(
std::piecewise_construct, std::make_tuple(ds_id), std::make_tuple());
PERFETTO_DCHECK(it_and_inserted.second);
// Note: only the first concurrent writer will actually be active.
metatrace_.writers[ds_id].Enable(task_runner_, std::move(writer),
metatrace::TAG_ANY);
}
}
void BuiltinProducer::StopDataSource(DataSourceInstanceID ds_id) {
auto meta_it = metatrace_.writers.find(ds_id);
if (meta_it != metatrace_.writers.end()) {
// Synchronously re-flush the metatrace writer to record more of the
// teardown interactions, then ack the stop.
meta_it->second.WriteAllAndFlushTraceWriter([] {});
metatrace_.writers.erase(meta_it);
endpoint_->NotifyDataSourceStopped(ds_id);
}
auto lazy_it = lazy_heapprofd_.instance_ids.find(ds_id);
if (lazy_it != lazy_heapprofd_.instance_ids.end()) {
lazy_heapprofd_.instance_ids.erase(lazy_it);
// if no more sessions - stop heapprofd after a delay
if (lazy_heapprofd_.instance_ids.empty()) {
uint64_t cur_generation = lazy_heapprofd_.generation;
auto weak_this = weak_factory_.GetWeakPtr();
task_runner_->PostDelayedTask(
[weak_this, cur_generation] {
if (!weak_this)
return;
if (weak_this->lazy_heapprofd_.generation == cur_generation)
weak_this->SetAndroidProperty(kLazyHeapprofdPropertyName, "0");
},
lazy_heapprofd_.stop_delay_ms);
}
}
}
void BuiltinProducer::Flush(FlushRequestID flush_id,
const DataSourceInstanceID* ds_ids,
size_t num_ds_ids) {
for (size_t i = 0; i < num_ds_ids; i++) {
auto meta_it = metatrace_.writers.find(ds_ids[i]);
if (meta_it != metatrace_.writers.end()) {
meta_it->second.WriteAllAndFlushTraceWriter([] {});
}
// nothing to be done for lazy heapprofd sources
}
endpoint_->NotifyFlushComplete(flush_id);
}
bool BuiltinProducer::SetAndroidProperty(const std::string& name,
const std::string& value) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
return __system_property_set(name.c_str(), value.c_str()) == 0;
#else
// Allow this to be mocked out for tests on other platforms.
base::ignore_result(name);
base::ignore_result(value);
return true;
#endif
}
} // namespace perfetto
<commit_msg>traced: fix builtin_producer (in-process) shmem sizing am: 2952501a81<commit_after>/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/traced/service/builtin_producer.h"
#include <sys/types.h>
#include <unistd.h>
#include "perfetto/base/build_config.h"
#include "perfetto/base/logging.h"
#include "perfetto/ext/base/metatrace.h"
#include "perfetto/ext/base/weak_ptr.h"
#include "perfetto/ext/tracing/core/basic_types.h"
#include "perfetto/ext/tracing/core/trace_writer.h"
#include "perfetto/ext/tracing/core/tracing_service.h"
#include "perfetto/tracing/core/data_source_config.h"
#include "perfetto/tracing/core/data_source_descriptor.h"
#include "src/tracing/core/metatrace_writer.h"
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#include <sys/system_properties.h>
#endif
namespace perfetto {
namespace {
constexpr char kHeapprofdDataSourceName[] = "android.heapprofd";
constexpr char kJavaHprofDataSourceName[] = "android.java_hprof";
constexpr char kLazyHeapprofdPropertyName[] = "traced.lazy.heapprofd";
} // namespace
BuiltinProducer::BuiltinProducer(base::TaskRunner* task_runner,
uint32_t lazy_stop_delay_ms)
: task_runner_(task_runner), weak_factory_(this) {
lazy_heapprofd_.stop_delay_ms = lazy_stop_delay_ms;
}
BuiltinProducer::~BuiltinProducer() {
if (!lazy_heapprofd_.instance_ids.empty())
SetAndroidProperty(kLazyHeapprofdPropertyName, "0");
}
void BuiltinProducer::ConnectInProcess(TracingService* svc) {
endpoint_ = svc->ConnectProducer(
this, geteuid(), "traced",
/*shared_memory_size_hint_bytes=*/16 * 1024, /*in_process=*/true,
TracingService::ProducerSMBScrapingMode::kDisabled,
/*shmem_page_size_hint_bytes=*/4096);
}
void BuiltinProducer::OnConnect() {
DataSourceDescriptor metatrace_dsd;
metatrace_dsd.set_name(MetatraceWriter::kDataSourceName);
metatrace_dsd.set_will_notify_on_stop(true);
endpoint_->RegisterDataSource(metatrace_dsd);
{
DataSourceDescriptor lazy_heapprofd_dsd;
lazy_heapprofd_dsd.set_name(kHeapprofdDataSourceName);
endpoint_->RegisterDataSource(lazy_heapprofd_dsd);
}
{
DataSourceDescriptor lazy_java_hprof_dsd;
lazy_java_hprof_dsd.set_name(kJavaHprofDataSourceName);
endpoint_->RegisterDataSource(lazy_java_hprof_dsd);
}
}
void BuiltinProducer::SetupDataSource(DataSourceInstanceID ds_id,
const DataSourceConfig& ds_config) {
if (ds_config.name() == kHeapprofdDataSourceName ||
ds_config.name() == kJavaHprofDataSourceName) {
SetAndroidProperty(kLazyHeapprofdPropertyName, "1");
lazy_heapprofd_.generation++;
lazy_heapprofd_.instance_ids.emplace(ds_id);
}
}
void BuiltinProducer::StartDataSource(DataSourceInstanceID ds_id,
const DataSourceConfig& ds_config) {
// We slightly rely on the fact that since this producer is in-process for
// enabling metatrace early (relative to producers that are notified via IPC).
if (ds_config.name() == MetatraceWriter::kDataSourceName) {
auto writer = endpoint_->CreateTraceWriter(
static_cast<BufferID>(ds_config.target_buffer()));
auto it_and_inserted = metatrace_.writers.emplace(
std::piecewise_construct, std::make_tuple(ds_id), std::make_tuple());
PERFETTO_DCHECK(it_and_inserted.second);
// Note: only the first concurrent writer will actually be active.
metatrace_.writers[ds_id].Enable(task_runner_, std::move(writer),
metatrace::TAG_ANY);
}
}
void BuiltinProducer::StopDataSource(DataSourceInstanceID ds_id) {
auto meta_it = metatrace_.writers.find(ds_id);
if (meta_it != metatrace_.writers.end()) {
// Synchronously re-flush the metatrace writer to record more of the
// teardown interactions, then ack the stop.
meta_it->second.WriteAllAndFlushTraceWriter([] {});
metatrace_.writers.erase(meta_it);
endpoint_->NotifyDataSourceStopped(ds_id);
}
auto lazy_it = lazy_heapprofd_.instance_ids.find(ds_id);
if (lazy_it != lazy_heapprofd_.instance_ids.end()) {
lazy_heapprofd_.instance_ids.erase(lazy_it);
// if no more sessions - stop heapprofd after a delay
if (lazy_heapprofd_.instance_ids.empty()) {
uint64_t cur_generation = lazy_heapprofd_.generation;
auto weak_this = weak_factory_.GetWeakPtr();
task_runner_->PostDelayedTask(
[weak_this, cur_generation] {
if (!weak_this)
return;
if (weak_this->lazy_heapprofd_.generation == cur_generation)
weak_this->SetAndroidProperty(kLazyHeapprofdPropertyName, "0");
},
lazy_heapprofd_.stop_delay_ms);
}
}
}
void BuiltinProducer::Flush(FlushRequestID flush_id,
const DataSourceInstanceID* ds_ids,
size_t num_ds_ids) {
for (size_t i = 0; i < num_ds_ids; i++) {
auto meta_it = metatrace_.writers.find(ds_ids[i]);
if (meta_it != metatrace_.writers.end()) {
meta_it->second.WriteAllAndFlushTraceWriter([] {});
}
// nothing to be done for lazy heapprofd sources
}
endpoint_->NotifyFlushComplete(flush_id);
}
bool BuiltinProducer::SetAndroidProperty(const std::string& name,
const std::string& value) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
return __system_property_set(name.c_str(), value.c_str()) == 0;
#else
// Allow this to be mocked out for tests on other platforms.
base::ignore_result(name);
base::ignore_result(value);
return true;
#endif
}
} // namespace perfetto
<|endoftext|> |
<commit_before>#include "error.hh"
#include <iostream>
#include <optional>
#include "serialise.hh"
#include <sstream>
namespace nix {
const std::string nativeSystem = SYSTEM;
BaseError & BaseError::addPrefix(const FormatOrString & fs)
{
prefix_ = fs.s + prefix_;
return *this;
}
const string& BaseError::calcWhat() const
{
if (what_.has_value())
return *what_;
else {
err.name = sname();
std::ostringstream oss;
oss << err;
what_ = oss.str();
return *what_;
}
}
std::optional<string> ErrorInfo::programName = std::nullopt;
std::ostream& operator<<(std::ostream &os, const hintformat &hf)
{
return os << hf.str();
}
string showErrPos(const ErrPos &errPos)
{
if (errPos.line > 0) {
if (errPos.column > 0) {
return fmt("(%1%:%2%)", errPos.line, errPos.column);
} else {
return fmt("(%1%)", errPos.line);
}
}
else {
return "";
}
}
void printCodeLines(std::ostream &out, const string &prefix, const NixCode &nixCode)
{
// previous line of code.
if (nixCode.prevLineOfCode.has_value()) {
out << fmt("%1% %|2$5d|| %3%",
prefix,
(nixCode.errPos.line - 1),
*nixCode.prevLineOfCode)
<< std::endl;
}
if (nixCode.errLineOfCode.has_value()) {
// line of code containing the error.
out << fmt("%1% %|2$5d|| %3%",
prefix,
(nixCode.errPos.line),
*nixCode.errLineOfCode)
<< std::endl;
// error arrows for the column range.
if (nixCode.errPos.column > 0) {
int start = nixCode.errPos.column;
std::string spaces;
for (int i = 0; i < start; ++i) {
spaces.append(" ");
}
std::string arrows("^");
out << fmt("%1% |%2%" ANSI_RED "%3%" ANSI_NORMAL,
prefix,
spaces,
arrows) << std::endl;
}
}
// next line of code.
if (nixCode.nextLineOfCode.has_value()) {
out << fmt("%1% %|2$5d|| %3%",
prefix,
(nixCode.errPos.line + 1),
*nixCode.nextLineOfCode)
<< std::endl;
}
}
std::ostream& operator<<(std::ostream &out, const ErrorInfo &einfo)
{
int errwidth = 80;
string prefix = "";
string levelString;
switch (einfo.level) {
case Verbosity::lvlError: {
levelString = ANSI_RED;
levelString += "error:";
levelString += ANSI_NORMAL;
break;
}
case Verbosity::lvlWarn: {
levelString = ANSI_YELLOW;
levelString += "warning:";
levelString += ANSI_NORMAL;
break;
}
case Verbosity::lvlInfo: {
levelString = ANSI_GREEN;
levelString += "info:";
levelString += ANSI_NORMAL;
break;
}
case Verbosity::lvlTalkative: {
levelString = ANSI_GREEN;
levelString += "talk:";
levelString += ANSI_NORMAL;
break;
}
case Verbosity::lvlChatty: {
levelString = ANSI_GREEN;
levelString += "chat:";
levelString += ANSI_NORMAL;
break;
}
case Verbosity::lvlVomit: {
levelString = ANSI_GREEN;
levelString += "vomit:";
levelString += ANSI_NORMAL;
break;
}
case Verbosity::lvlDebug: {
levelString = ANSI_YELLOW;
levelString += "debug:";
levelString += ANSI_NORMAL;
break;
}
default: {
levelString = fmt("invalid error level: %1%", einfo.level);
break;
}
}
int ndl = prefix.length() + levelString.length() + 3 + einfo.name.length() + einfo.programName.value_or("").length();
int dashwidth = ndl > (errwidth - 3) ? 3 : errwidth - ndl;
string dashes;
for (int i = 0; i < dashwidth; ++i)
dashes.append("-");
// divider.
if (einfo.name != "")
out << fmt("%1%%2%" ANSI_BLUE " --- %3% %4% %5%" ANSI_NORMAL,
prefix,
levelString,
einfo.name,
dashes,
einfo.programName.value_or(""))
<< std::endl;
else
out << fmt("%1%%2%" ANSI_BLUE " -----%3% %4%" ANSI_NORMAL,
prefix,
levelString,
dashes,
einfo.programName.value_or(""))
<< std::endl;
// filename, line, column.
if (einfo.nixCode.has_value()) {
if (einfo.nixCode->errPos.file != "") {
out << fmt("%1%in file: " ANSI_BLUE "%2% %3%" ANSI_NORMAL,
prefix,
einfo.nixCode->errPos.file,
showErrPos(einfo.nixCode->errPos)) << std::endl;
out << prefix << std::endl;
} else {
out << fmt("%1%from command line argument", prefix) << std::endl;
out << prefix << std::endl;
}
}
// description
if (einfo.description != "") {
out << prefix << einfo.description << std::endl;
out << prefix << std::endl;
}
// lines of code.
if (einfo.nixCode.has_value() && einfo.nixCode->errLineOfCode.has_value()) {
printCodeLines(out, prefix, *einfo.nixCode);
out << prefix << std::endl;
}
// hint
if (einfo.hint.has_value()) {
out << prefix << *einfo.hint << std::endl;
out << prefix << std::endl;
}
return out;
}
}
<commit_msg>newline-as-prefix; no final newline in output.<commit_after>#include "error.hh"
#include <iostream>
#include <optional>
#include "serialise.hh"
#include <sstream>
namespace nix {
const std::string nativeSystem = SYSTEM;
BaseError & BaseError::addPrefix(const FormatOrString & fs)
{
prefix_ = fs.s + prefix_;
return *this;
}
const string& BaseError::calcWhat() const
{
if (what_.has_value())
return *what_;
else {
err.name = sname();
std::ostringstream oss;
oss << err;
what_ = oss.str();
return *what_;
}
}
std::optional<string> ErrorInfo::programName = std::nullopt;
std::ostream& operator<<(std::ostream &os, const hintformat &hf)
{
return os << hf.str();
}
string showErrPos(const ErrPos &errPos)
{
if (errPos.line > 0) {
if (errPos.column > 0) {
return fmt("(%1%:%2%)", errPos.line, errPos.column);
} else {
return fmt("(%1%)", errPos.line);
}
}
else {
return "";
}
}
void printCodeLines(std::ostream &out, const string &prefix, const NixCode &nixCode)
{
// previous line of code.
if (nixCode.prevLineOfCode.has_value()) {
out << std::endl
<< fmt("%1% %|2$5d|| %3%",
prefix,
(nixCode.errPos.line - 1),
*nixCode.prevLineOfCode);
}
if (nixCode.errLineOfCode.has_value()) {
// line of code containing the error.
out << std::endl
<< fmt("%1% %|2$5d|| %3%",
prefix,
(nixCode.errPos.line),
*nixCode.errLineOfCode);
// error arrows for the column range.
if (nixCode.errPos.column > 0) {
int start = nixCode.errPos.column;
std::string spaces;
for (int i = 0; i < start; ++i) {
spaces.append(" ");
}
std::string arrows("^");
out << std::endl
<< fmt("%1% |%2%" ANSI_RED "%3%" ANSI_NORMAL,
prefix,
spaces,
arrows);
}
}
// next line of code.
if (nixCode.nextLineOfCode.has_value()) {
out << std::endl
<< fmt("%1% %|2$5d|| %3%",
prefix,
(nixCode.errPos.line + 1),
*nixCode.nextLineOfCode);
}
}
std::ostream& operator<<(std::ostream &out, const ErrorInfo &einfo)
{
int errwidth = 80;
string prefix = "";
string levelString;
switch (einfo.level) {
case Verbosity::lvlError: {
levelString = ANSI_RED;
levelString += "error:";
levelString += ANSI_NORMAL;
break;
}
case Verbosity::lvlWarn: {
levelString = ANSI_YELLOW;
levelString += "warning:";
levelString += ANSI_NORMAL;
break;
}
case Verbosity::lvlInfo: {
levelString = ANSI_GREEN;
levelString += "info:";
levelString += ANSI_NORMAL;
break;
}
case Verbosity::lvlTalkative: {
levelString = ANSI_GREEN;
levelString += "talk:";
levelString += ANSI_NORMAL;
break;
}
case Verbosity::lvlChatty: {
levelString = ANSI_GREEN;
levelString += "chat:";
levelString += ANSI_NORMAL;
break;
}
case Verbosity::lvlVomit: {
levelString = ANSI_GREEN;
levelString += "vomit:";
levelString += ANSI_NORMAL;
break;
}
case Verbosity::lvlDebug: {
levelString = ANSI_YELLOW;
levelString += "debug:";
levelString += ANSI_NORMAL;
break;
}
default: {
levelString = fmt("invalid error level: %1%", einfo.level);
break;
}
}
int ndl = prefix.length() + levelString.length() + 3 + einfo.name.length() + einfo.programName.value_or("").length();
int dashwidth = ndl > (errwidth - 3) ? 3 : errwidth - ndl;
string dashes;
for (int i = 0; i < dashwidth; ++i)
dashes.append("-");
// divider.
if (einfo.name != "")
out << fmt("%1%%2%" ANSI_BLUE " --- %3% %4% %5%" ANSI_NORMAL,
prefix,
levelString,
einfo.name,
dashes,
einfo.programName.value_or(""));
else
out << fmt("%1%%2%" ANSI_BLUE " -----%3% %4%" ANSI_NORMAL,
prefix,
levelString,
dashes,
einfo.programName.value_or(""));
bool nl = false; // intersperse newline between sections.
if (einfo.nixCode.has_value()) {
if (einfo.nixCode->errPos.file != "") {
// filename, line, column.
out << std::endl << fmt("%1%in file: " ANSI_BLUE "%2% %3%" ANSI_NORMAL,
prefix,
einfo.nixCode->errPos.file,
showErrPos(einfo.nixCode->errPos));
} else {
out << std::endl << fmt("%1%from command line argument", prefix);
}
nl = true;
}
// description
if (einfo.description != "") {
if (nl)
out << std::endl << prefix;
out << std::endl << prefix << einfo.description;
nl = true;
}
// lines of code.
if (einfo.nixCode.has_value() && einfo.nixCode->errLineOfCode.has_value()) {
if (nl)
out << std::endl << prefix;
printCodeLines(out, prefix, *einfo.nixCode);
nl = true;
}
// hint
if (einfo.hint.has_value()) {
if (nl)
out << std::endl << prefix;
out << std::endl << prefix << *einfo.hint;
nl = true;
}
return out;
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.