commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
277cc6452e24b955f84438e4f221f53f33ea427f
Lib/Io/PinFactories.hpp
Lib/Io/PinFactories.hpp
/************************************************************************** Copyright 2015 Odin Holmes 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. ****************************************************************************/ #pragma once #include "MPL/Utility.hpp" #include "Utility.hpp" namespace Kvasir { namespace Io{ template<typename TAction, typename TPinLocation> struct MakeAction{ static_assert(MPL::AlwaysFalse<TAction>::value,"could not find this configuration in the included Core"); }; template<typename TAction, typename TPinLocation> using MakeActionT = typename MakeAction<TAction,TPinLocation>::Type; namespace Detail{ template<typename TAction, typename TPortPin> struct MakeActionIfPinLocation{}; template<typename TAction, int Port, int Pin> struct MakeActionIfPinLocation<TAction, PinLocation<Port,Pin>>{ using Type = MakeActionT<TAction, PinLocation<Port,Pin>>; }; template<typename TAction, typename TPinLocation> using MakeActionIfPinLocationT = typename MakeActionIfPinLocation<TAction,TPinLocation>::Type; } template<typename TAction, typename T> constexpr Detail::MakeActionIfPinLocationT<TAction,T> action(TAction,T){ return {}; }; template<typename T> constexpr Detail::MakeActionIfPinLocationT<Action::Input,T> makeInput(T){ return{}; }; template<typename T, typename U, typename... Ts> constexpr decltype(MPL::list(makeInput(T{}),makeInput(U{}),makeInput(Ts{})...)) makeInput(T,U,Ts...){ return {}; } template<typename T> constexpr Detail::MakeActionIfPinLocationT<Action::Output,T> makeOutput(T){ return{}; }; template<typename T, typename U, typename... Ts> constexpr decltype(MPL::list(makeOutput(T{}),makeOutput(U{}),makeOutput(Ts{})...)) makeOutput(T,U,Ts...){ return {}; } template<typename TPortPin> constexpr Detail::MakeActionIfPinLocationT<Action::Set,TPortPin> set(TPortPin){ return{}; }; template<typename TPortPin> constexpr Detail::MakeActionIfPinLocationT<Action::Clear,TPortPin> clear(TPortPin){ return{}; }; template<typename TPortPin> constexpr Detail::MakeActionIfPinLocationT<Action::Toggle,TPortPin> toggle(TPortPin){ return{}; }; template<typename TPortPin> constexpr Detail::MakeActionIfPinLocationT<Action::Read,TPortPin> read(TPortPin){ return{}; }; template<typename TPort, typename TPin> constexpr PinLocation<TPort::value,TPin::value> makePinLocation(TPort,TPin){ return{}; }; } }
/************************************************************************** Copyright 2015 Odin Holmes 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. ****************************************************************************/ #pragma once #include "MPL/Utility.hpp" #include "Utility.hpp" namespace Kvasir { namespace Io{ /// This generic Metafunction which all pin factores resolve to. /// It relies on the user to include a chip file which specializes this template /// with the propper resulting Register::Action template<typename TAction, typename TPinLocation> struct MakeAction{ static_assert(MPL::AlwaysFalse<TAction>::value,"could not find this configuration in the included chip file"); }; template<typename TAction, typename TPinLocation> using MakeActionT = typename MakeAction<TAction,TPinLocation>::Type; namespace Detail{ //make sure we actually got a PinLocation as a parameter template<typename TAction, typename TPortPin> struct MakeActionIfPinLocation{ static_assert(MPL::AlwaysFalse<TAction>::value,"parameter is not a PinLocation"); }; template<typename TAction, int Port, int Pin> struct MakeActionIfPinLocation<TAction, PinLocation<Port,Pin>>{ using Type = MakeActionT<TAction, PinLocation<Port,Pin>>; }; template<typename TAction, typename TPinLocation> using MakeActionIfPinLocationT = typename MakeActionIfPinLocation<TAction,TPinLocation>::Type; } template<typename TAction, typename T> constexpr Detail::MakeActionIfPinLocationT<TAction,T> action(TAction,T){ return {}; }; template<typename T> constexpr Detail::MakeActionIfPinLocationT<Action::Input,T> makeInput(T){ return{}; }; template<typename T, typename U, typename... Ts> constexpr decltype(MPL::list(makeInput(T{}),makeInput(U{}),makeInput(Ts{})...)) makeInput(T,U,Ts...){ return {}; } template<typename T> constexpr Detail::MakeActionIfPinLocationT<Action::Output,T> makeOutput(T){ return{}; }; template<typename T, typename U, typename... Ts> constexpr decltype(MPL::list(makeOutput(T{}),makeOutput(U{}),makeOutput(Ts{})...)) makeOutput(T,U,Ts...){ return {}; } template<typename TPortPin> constexpr Detail::MakeActionIfPinLocationT<Action::Set,TPortPin> set(TPortPin){ return{}; }; template<typename TPortPin> constexpr Detail::MakeActionIfPinLocationT<Action::Clear,TPortPin> clear(TPortPin){ return{}; }; template<typename TPortPin> constexpr Detail::MakeActionIfPinLocationT<Action::Toggle,TPortPin> toggle(TPortPin){ return{}; }; template<typename TPortPin> constexpr Detail::MakeActionIfPinLocationT<Action::Read,TPortPin> read(TPortPin){ return{}; }; template<typename TPort, typename TPin> constexpr PinLocation<TPort::value,TPin::value> makePinLocation(TPort,TPin){ return{}; }; } }
Update PinFactories.hpp
Update PinFactories.hpp
C++
apache-2.0
porkybrain/Kvasir,porkybrain/Kvasir,porkybrain/Kvasir,kvasir-io/Kvasir,kvasir-io/Kvasir,kvasir-io/Kvasir
72798c7c7ed8d4e15216fc5ec473dfb01e0eedcc
chainerx_cc/chainerx/native/native_device/binary.cc
chainerx_cc/chainerx/native/native_device/binary.cc
#include "chainerx/native/native_device.h" #include "chainerx/array.h" #include "chainerx/device.h" #include "chainerx/dtype.h" #include "chainerx/kernels/binary.h" #include "chainerx/native/elementwise.h" #include "chainerx/native/kernel_regist.h" #include "chainerx/routines/binary.h" #include "chainerx/scalar.h" namespace chainerx { namespace native { namespace { CHAINERX_NATIVE_REGISTER_ELTWISE_DTYPE_BINARY_KERNEL(BitwiseAndKernel, { out = x1 & x2; }, VisitIntegralDtype); class NativeBitwiseAndASKernel : public BitwiseAndASKernel { public: void Call(const Array& x1, Scalar x2, const Array& out) override { Device& device = x1.device(); device.CheckDevicesCompatible(x1, out); const Array& x1_cast = x1.dtype() == out.dtype() ? x1 : x1.AsType(out.dtype()); VisitIntegralDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x1, T& out) { out = x1 & x2; } T x2; }; Elementwise<const T, T>(Impl{static_cast<T>(x2)}, x1_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(BitwiseAndASKernel, NativeBitwiseAndASKernel); CHAINERX_NATIVE_REGISTER_ELTWISE_DTYPE_BINARY_KERNEL(BitwiseOrKernel, { out = x1 | x2; }, VisitIntegralDtype); class NativeBitwiseOrASKernel : public BitwiseOrASKernel { public: void Call(const Array& x1, Scalar x2, const Array& out) override { Device& device = x1.device(); device.CheckDevicesCompatible(x1, out); const Array& x1_cast = x1.dtype() == out.dtype() ? x1 : x1.AsType(out.dtype()); VisitIntegralDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x1, T& out) { out = x1 | x2; } T x2; }; Elementwise<const T, T>(Impl{static_cast<T>(x2)}, x1_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(BitwiseOrASKernel, NativeBitwiseOrASKernel); CHAINERX_NATIVE_REGISTER_ELTWISE_DTYPE_BINARY_KERNEL(BitwiseXorKernel, { out = x1 ^ x2; }, VisitIntegralDtype); class NativeBitwiseXorASKernel : public BitwiseXorASKernel { public: void Call(const Array& x1, Scalar x2, const Array& out) override { Device& device = x1.device(); device.CheckDevicesCompatible(x1, out); const Array& x1_cast = x1.dtype() == out.dtype() ? x1 : x1.AsType(out.dtype()); VisitIntegralDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x1, T& out) { out = x1 ^ x2; } T x2; }; Elementwise<const T, T>(Impl{static_cast<T>(x2)}, x1_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(BitwiseXorASKernel, NativeBitwiseXorASKernel); CHAINERX_NATIVE_REGISTER_ELTWISE_DTYPE_BINARY_KERNEL(LeftShiftKernel, { out = x1 << x2; }, VisitShiftDtype); class NativeLeftShiftASKernel : public LeftShiftASKernel { public: void Call(const Array& x1, Scalar x2, const Array& out) override { Device& device = x1.device(); device.CheckDevicesCompatible(x1, out); const Array& x1_cast = x1.dtype() == out.dtype() ? x1 : x1.AsType(out.dtype()); VisitIntegralDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x1, T& out) { out = x1 << x2; } T x2; }; Elementwise<const T, T>(Impl{static_cast<T>(x2)}, x1_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(LeftShiftASKernel, NativeLeftShiftASKernel); class NativeLeftShiftSAKernel : public LeftShiftSAKernel { public: void Call(Scalar x1, const Array& x2, const Array& out) override { Device& device = x2.device(); device.CheckDevicesCompatible(x2, out); const Array& x2_cast = x2.dtype() == out.dtype() ? x2 : x2.AsType(out.dtype()); VisitIntegralDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x2, T& out) { out = x1 << x2; } T x1; }; Elementwise<const T, T>(Impl{static_cast<T>(x1)}, x2_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(LeftShiftSAKernel, NativeLeftShiftSAKernel); CHAINERX_NATIVE_REGISTER_ELTWISE_DTYPE_BINARY_KERNEL(RightShiftKernel, { out = x1 >> x2; }, VisitShiftDtype); class NativeRightShiftASKernel : public RightShiftASKernel { public: void Call(const Array& x1, Scalar x2, const Array& out) override { Device& device = x1.device(); device.CheckDevicesCompatible(x1, out); const Array& x1_cast = x1.dtype() == out.dtype() ? x1 : x1.AsType(out.dtype()); VisitIntegralDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x1, T& out) { out = x1 >> x2; } T x2; }; Elementwise<const T, T>(Impl{static_cast<T>(x2)}, x1_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(RightShiftASKernel, NativeRightShiftASKernel); class NativeRightShiftSAKernel : public RightShiftSAKernel { public: void Call(Scalar x1, const Array& x2, const Array& out) override { Device& device = x2.device(); device.CheckDevicesCompatible(x2, out); const Array& x2_cast = x2.dtype() == out.dtype() ? x2 : x2.AsType(out.dtype()); VisitIntegralDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x2, T& out) { out = x1 << x2; } T x1; }; Elementwise<const T, T>(Impl{static_cast<T>(x1)}, x2_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(RightShiftSAKernel, NativeRightShiftSAKernel); } // namespace } // namespace native } // namespace chainerx
#include "chainerx/native/native_device.h" #include "chainerx/array.h" #include "chainerx/device.h" #include "chainerx/dtype.h" #include "chainerx/kernels/binary.h" #include "chainerx/native/elementwise.h" #include "chainerx/native/kernel_regist.h" #include "chainerx/routines/binary.h" #include "chainerx/scalar.h" namespace chainerx { namespace native { namespace { CHAINERX_NATIVE_REGISTER_ELTWISE_DTYPE_BINARY_KERNEL(BitwiseAndKernel, { out = x1 & x2; }, VisitIntegralDtype); class NativeBitwiseAndASKernel : public BitwiseAndASKernel { public: void Call(const Array& x1, Scalar x2, const Array& out) override { Device& device = x1.device(); device.CheckDevicesCompatible(x1, out); const Array& x1_cast = x1.dtype() == out.dtype() ? x1 : x1.AsType(out.dtype()); VisitIntegralDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x1, T& out) { out = x1 & x2; } T x2; }; Elementwise<const T, T>(Impl{static_cast<T>(x2)}, x1_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(BitwiseAndASKernel, NativeBitwiseAndASKernel); CHAINERX_NATIVE_REGISTER_ELTWISE_DTYPE_BINARY_KERNEL(BitwiseOrKernel, { out = x1 | x2; }, VisitIntegralDtype); class NativeBitwiseOrASKernel : public BitwiseOrASKernel { public: void Call(const Array& x1, Scalar x2, const Array& out) override { Device& device = x1.device(); device.CheckDevicesCompatible(x1, out); const Array& x1_cast = x1.dtype() == out.dtype() ? x1 : x1.AsType(out.dtype()); VisitIntegralDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x1, T& out) { out = x1 | x2; } T x2; }; Elementwise<const T, T>(Impl{static_cast<T>(x2)}, x1_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(BitwiseOrASKernel, NativeBitwiseOrASKernel); CHAINERX_NATIVE_REGISTER_ELTWISE_DTYPE_BINARY_KERNEL(BitwiseXorKernel, { out = x1 ^ x2; }, VisitIntegralDtype); class NativeBitwiseXorASKernel : public BitwiseXorASKernel { public: void Call(const Array& x1, Scalar x2, const Array& out) override { Device& device = x1.device(); device.CheckDevicesCompatible(x1, out); const Array& x1_cast = x1.dtype() == out.dtype() ? x1 : x1.AsType(out.dtype()); VisitIntegralDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x1, T& out) { out = x1 ^ x2; } T x2; }; Elementwise<const T, T>(Impl{static_cast<T>(x2)}, x1_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(BitwiseXorASKernel, NativeBitwiseXorASKernel); CHAINERX_NATIVE_REGISTER_ELTWISE_DTYPE_BINARY_KERNEL(LeftShiftKernel, { out = x1 << x2; }, VisitShiftDtype); class NativeLeftShiftASKernel : public LeftShiftASKernel { public: void Call(const Array& x1, Scalar x2, const Array& out) override { Device& device = x1.device(); device.CheckDevicesCompatible(x1, out); const Array& x1_cast = out.dtype() == Dtype::kBool ? x1.AsType(Dtype::kInt64) : x1.dtype() == out.dtype() ? x1 : x1.AsType(out.dtype()); VisitShiftDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x1, T& out) { out = x1 << x2; } T x2; }; Elementwise<const T, T>(Impl{static_cast<T>(x2)}, x1_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(LeftShiftASKernel, NativeLeftShiftASKernel); class NativeLeftShiftSAKernel : public LeftShiftSAKernel { public: void Call(Scalar x1, const Array& x2, const Array& out) override { Device& device = x2.device(); device.CheckDevicesCompatible(x2, out); const Array& x2_cast = out.dtype() == Dtype::kBool ? x2.AsType(Dtype::kInt64) : x2.dtype() == out.dtype() ? x2 : x2.AsType(out.dtype()); VisitShiftDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x2, T& out) { out = x1 << x2; } T x1; }; Elementwise<const T, T>(Impl{static_cast<T>(x1)}, x2_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(LeftShiftSAKernel, NativeLeftShiftSAKernel); CHAINERX_NATIVE_REGISTER_ELTWISE_DTYPE_BINARY_KERNEL(RightShiftKernel, { out = x1 >> x2; }, VisitShiftDtype); class NativeRightShiftASKernel : public RightShiftASKernel { public: void Call(const Array& x1, Scalar x2, const Array& out) override { Device& device = x1.device(); device.CheckDevicesCompatible(x1, out); const Array& x1_cast = out.dtype() == Dtype::kBool ? x1.AsType(Dtype::kInt64) : x1.dtype() == out.dtype() ? x1 : x1.AsType(out.dtype()); VisitShiftDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x1, T& out) { out = x1 >> x2; } T x2; }; Elementwise<const T, T>(Impl{static_cast<T>(x2)}, x1_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(RightShiftASKernel, NativeRightShiftASKernel); class NativeRightShiftSAKernel : public RightShiftSAKernel { public: void Call(Scalar x1, const Array& x2, const Array& out) override { Device& device = x2.device(); device.CheckDevicesCompatible(x2, out); const Array& x2_cast = out.dtype() == Dtype::kBool ? x2.AsType(Dtype::kInt64) : x2.dtype() == out.dtype() ? x2 : x2.AsType(out.dtype()); VisitShiftDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { void operator()(int64_t /*i*/, T x2, T& out) { out = x1 >> x2; } T x1; }; Elementwise<const T, T>(Impl{static_cast<T>(x1)}, x2_cast, out); }); } }; CHAINERX_NATIVE_REGISTER_KERNEL(RightShiftSAKernel, NativeRightShiftSAKernel); } // namespace } // namespace native } // namespace chainerx
Convert dtype from bool to int
Convert dtype from bool to int
C++
mit
okuta/chainer,niboshi/chainer,wkentaro/chainer,okuta/chainer,hvy/chainer,pfnet/chainer,wkentaro/chainer,wkentaro/chainer,hvy/chainer,niboshi/chainer,hvy/chainer,chainer/chainer,chainer/chainer,wkentaro/chainer,okuta/chainer,chainer/chainer,chainer/chainer,hvy/chainer,niboshi/chainer,okuta/chainer,niboshi/chainer
0062ab1694d4b590eecd28061673e9e7a8aa668d
qNewton/HEqNewton.cc
qNewton/HEqNewton.cc
#include <kv/Heine.hpp> #include <kv/qAiry.hpp> #include <kv/qBessel.hpp> #include <cmath> typedef kv::interval<double> itv; typedef kv::complex< kv::interval<double> > cp; using namespace std; int main() { cout.precision(17); int n=50; itv x,nu,q; q="0.7"; nu=2.5; x=3.5; for(int i=1;i<=n;i++){ x=x-kv::Hahn_Exton(itv(x),itv(nu),itv(q))*(1-q)*x /(kv::Hahn_Exton(itv(x),itv(nu),itv(q))-kv::Hahn_Exton(itv(q*x),itv(nu),itv(q))); cout<<x<<endl; cout<<"value of HE"<<kv::Hahn_Exton(itv(x),itv(nu),itv(q))<<endl; } }
#include <kv/Heine.hpp> #include <kv/qAiry.hpp> #include <kv/qBessel.hpp> #include <cmath> typedef kv::interval<double> itv; typedef kv::complex< kv::interval<double> > cp; using namespace std; int main() { cout.precision(17); int n=50; itv x,nu,q; q="0.7"; nu=2.5; x=3.5; for(int i=1;i<=n;i++){ x=x-kv::Hahn_Exton(itv(x),itv(nu),itv(q))*(1-q)*x /(kv::Hahn_Exton(itv(x),itv(nu),itv(q))-kv::Hahn_Exton(itv(q*x),itv(nu),itv(q))); cout<<x<<endl; cout<<"value of HE inf"<<kv::Hahn_Exton(itv(x.lower()),itv(nu),itv(q))<<endl; cout<<"value of HE sup"<<kv::Hahn_Exton(itv(x.upper()),itv(nu),itv(q))<<endl; cout<<"value of HE mid"<<kv::Hahn_Exton(itv(mid(x)),itv(nu),itv(q))<<endl; } }
Update HEqNewton.cc
Update HEqNewton.cc
C++
mit
Daisuke-Kanaizumi/q-special-functions,Daisuke-Kanaizumi/q-special-functions
8f19dde8b963fecfaad109bd07dc83fa50d24a88
compiler/ifa/sym.cpp
compiler/ifa/sym.cpp
#include "defs.h" #include "ast.h" #include "if1.h" #include "fa.h" #include "builtin.h" char *type_kind_string[] = { "NONE", "UNKNOWN", "LUB", "GLB", "PRODUCT", "RECORD", "VECTOR", "FUN", "REF", "TAGGED", "PRIMITIVE", "APPLICATION", "VARIABLE", "ALIAS"}; BasicSym::BasicSym(void) : name(NULL), in(NULL), type(NULL), aspect(NULL), must_specialize(NULL), must_implement(NULL), ast(NULL), var(NULL), asymbol(NULL), nesting_depth(0), cg_string(NULL), is_builtin(0), is_read_only(0), is_constant(0), is_lvalue(0), is_var(0), is_default_arg(0), is_exact_match(0), is_module(0), is_fun(0), is_symbol(0), is_pattern(0), is_rest(0), is_generic(0), is_external(0), is_this(0), intent(0), is_structure(0), is_meta_type(0), is_value_type(0), is_system_type(0), is_union_type(0), fun_returns_value(0), live(0), incomplete(0), type_kind(0), num_kind(0), num_index(0), clone_for_constants(0) {} Sym * meta_apply(Sym *fn, Sym *arg) { if (fn->type_kind != Type_APPLICATION) return 0; assert(0); return 0; } Sym::Sym() : destruct_name(NULL), arg_name(NULL), constant(NULL), size(0), scope(NULL), labelmap(NULL), fun(NULL), code(NULL), self(NULL), ret(NULL), cont(NULL), instantiates(NULL), match_type(NULL), abstract_type(NULL), alias(NULL), init(NULL), meta_type(NULL), element(NULL), domain(NULL), temp(NULL) {} char * Sym::pathname() { char *p = 0; if (asymbol) p = asymbol->pathname(); if (!p && ast) p = ast->pathname(); if (p) return p; return "<unknown>"; } char * Sym::filename() { char *fn = pathname(); char *r = strrchr(fn, '/'); if (r) return r+1; else return fn; } int Sym::line() { int l = 0; if (asymbol) l = asymbol->line(); if (!l && ast) l = ast->line(); return l; } int Sym::ast_id() { if (asymbol) return asymbol->ast_id(); return id; } int Sym::log_line() { if (asymbol) return asymbol->log_line(); if (strstr(filename(), "prelude")) return 0; return line(); } void Sym::copy_values(Sym *s) { int temp_id = id; *this = *s; id = temp_id; } Sym * Sym::clone(int members) { if (asymbol) return asymbol->clone(members); Sym *new_sym = copy(); return new_sym; } Sym * Sym::copy() { Sym *s = new_Sym(); s->copy_values(this); return s; } int compar_syms(const void *ai, const void *aj) { uint32 i = (*(Sym**)ai)->id; uint32 j = (*(Sym**)aj)->id; return (i > j) ? 1 : ((i < j) ? -1 : 0); } int Sym::imm_int(int *result) { int i = 0; switch (type->num_kind) { default: return -1; case IF1_NUM_KIND_UINT: { switch (type->num_index) { case IF1_INT_TYPE_8: i = imm.v_uint8; break; case IF1_INT_TYPE_16: i = imm.v_uint16; break; case IF1_INT_TYPE_32: i = imm.v_uint32; break; case IF1_INT_TYPE_64: i = imm.v_uint64; break; default: return -1; } break; } case IF1_NUM_KIND_INT: { switch (type->num_index) { case IF1_INT_TYPE_8: i = imm.v_int8; break; case IF1_INT_TYPE_16: i = imm.v_int16; break; case IF1_INT_TYPE_32: i = imm.v_int32; break; case IF1_INT_TYPE_64: i = imm.v_int64; break; default: return -1; } break; } } *result = i; return 0; } Sym * unalias_type(Sym *s) { if (!s) return s; if (s->type_kind == Type_ALIAS) { Vec<Sym *> aliases; do { if (!s->alias) return 0; Sym *ss = s->alias; if (aliases.set_in(ss)) fail("circular type alias"); aliases.set_add(ss); s = ss; } while (s->type_kind == Type_ALIAS); } return s; } void if1_set_int_type(IF1 *p, Sym *t, int signd, int size) { int ss = 0; size >>= 3; while (size) { ss++; size >>= 1; } p->int_types[ss][signd] = t; t->num_kind = signd ? IF1_NUM_KIND_INT : IF1_NUM_KIND_UINT; t->num_index = ss; } void if1_set_float_type(IF1 *p, Sym *t, int size) { int ss = 0; size >>= 4; ss = size - 1; p->float_types[ss] = t; t->num_kind = IF1_NUM_KIND_FLOAT; t->num_index = ss; } void if1_set_complex_type(IF1 *p, Sym *t, int size) { int ss = 0; size >>= 4; ss = size - 1; p->complex_types[ss] = t; t->num_kind = IF1_NUM_KIND_COMPLEX; t->num_index = ss; } int if1_numeric_size(IF1 *p, Sym *t) { switch (t->num_kind) { case IF1_NUM_KIND_NONE: assert(!"bad case"); break; case IF1_NUM_KIND_INT: case IF1_NUM_KIND_UINT: if (!t->num_index) return sizeof(bool); return 1 << (t->num_index ? t->num_index : 1) - 1; case IF1_NUM_KIND_FLOAT: return 2 + (2 * t->num_index); case IF1_NUM_KIND_COMPLEX: return 2 * (2 + (2 * t->num_index)); } return 0; } #define MAKE_ALIGNOF(_t) \ struct AlignOf##_t { \ char a; \ _t b; \ } #define ALIGNOF(_t) ((int)(intptr_t)&(((struct AlignOf##_t *)0)->b)) MAKE_ALIGNOF(bool); MAKE_ALIGNOF(uint8); MAKE_ALIGNOF(uint16); MAKE_ALIGNOF(uint32); MAKE_ALIGNOF(uint64); MAKE_ALIGNOF(float32); MAKE_ALIGNOF(float64); MAKE_ALIGNOF(complex32); MAKE_ALIGNOF(complex64); typedef char *alignstring; MAKE_ALIGNOF(alignstring); int if1_numeric_alignment(IF1 *p, Sym *t) { int res = -1; switch (t->num_kind) { default: assert(!"case"); break; case IF1_NUM_KIND_UINT: case IF1_NUM_KIND_INT: switch (t->num_index) { case IF1_INT_TYPE_1: return ALIGNOF(bool); break; case IF1_INT_TYPE_8: return ALIGNOF(uint8); break; case IF1_INT_TYPE_16: return ALIGNOF(uint16); break; case IF1_INT_TYPE_32: return ALIGNOF(uint32); break; case IF1_INT_TYPE_64: return ALIGNOF(uint64); break; default: assert(!"case"); } break; case IF1_NUM_KIND_FLOAT: switch (t->num_index) { case IF1_FLOAT_TYPE_32: return ALIGNOF(float32); case IF1_FLOAT_TYPE_64: return ALIGNOF(float64); default: assert(!"case"); } break; case IF1_NUM_KIND_COMPLEX: switch (t->num_index) { case IF1_FLOAT_TYPE_32: return ALIGNOF(complex32); case IF1_FLOAT_TYPE_64: return ALIGNOF(complex64); default: assert(!"case"); } break; case IF1_CONST_KIND_STRING: return ALIGNOF(alignstring); } return res; } void Sym::inherits_add(Sym *s) { implements.add(s); specializes.add(s); includes.add(s); } void Sym::must_implement_and_specialize(Sym *s) { assert(!must_implement && !must_specialize); must_implement = s; must_specialize = s; } Sym * Sym::scalar_type() { if (type && type->num_kind) return type; forv_Sym(ss, dispatch_order) if (ss->type && ss->type->num_kind) return ss->type; return 0; } Sym * Sym::coerce_to(Sym *to) { if (this == to) return this; Sym *s1 = this->scalar_type(), *s2 = to->scalar_type(); if (s1 && s2) { Sym *t = coerce_num(s1, s2); if (t == s2) return s2; return NULL; } if (element) { Sym *s1 = element->scalar_type(), *s2 = to->scalar_type(); if (s1 && s2) { Sym *t = coerce_num(s1, s2); if (t == s2) return s2; return NULL; } } if (s1) { if (to == sym_string) return to; } return NULL; } void pp(Sym *s) { printf("(SYM %d ", s->id); if1_dump_sym(stdout, s); printf(")"); }
#include "defs.h" #include "ast.h" #include "if1.h" #include "fa.h" #include "builtin.h" char *type_kind_string[] = { "NONE", "UNKNOWN", "LUB", "GLB", "PRODUCT", "RECORD", "VECTOR", "FUN", "REF", "TAGGED", "PRIMITIVE", "APPLICATION", "VARIABLE", "ALIAS"}; BasicSym::BasicSym(void) : name(NULL), in(NULL), type(NULL), aspect(NULL), must_specialize(NULL), must_implement(NULL), ast(NULL), var(NULL), asymbol(NULL), nesting_depth(0), cg_string(NULL), is_builtin(0), is_read_only(0), is_constant(0), is_lvalue(0), is_var(0), is_default_arg(0), is_exact_match(0), is_module(0), is_fun(0), is_symbol(0), is_pattern(0), is_rest(0), is_generic(0), is_external(0), is_this(0), intent(0), is_structure(0), is_meta_type(0), is_value_type(0), is_system_type(0), is_union_type(0), fun_returns_value(0), live(0), incomplete(0), type_kind(0), num_kind(0), num_index(0), clone_for_constants(0) {} Sym * meta_apply(Sym *fn, Sym *arg) { if (fn->type_kind != Type_APPLICATION) return 0; assert(0); return 0; } Sym::Sym() : destruct_name(NULL), arg_name(NULL), constant(NULL), size(0), scope(NULL), labelmap(NULL), fun(NULL), code(NULL), self(NULL), ret(NULL), cont(NULL), instantiates(NULL), match_type(NULL), abstract_type(NULL), alias(NULL), init(NULL), meta_type(NULL), element(NULL), domain(NULL), temp(NULL) {} char * Sym::pathname() { char *p = 0; if (asymbol) p = asymbol->pathname(); if (!p && ast) p = ast->pathname(); if (p) return p; return "<unknown>"; } char * Sym::filename() { char *fn = pathname(); char *r = strrchr(fn, '/'); if (r) return r+1; else return fn; } int Sym::line() { int l = 0; if (asymbol) l = asymbol->line(); if (!l && ast) l = ast->line(); return l; } int Sym::ast_id() { if (asymbol) return asymbol->ast_id(); return id; } int Sym::log_line() { if (asymbol) return asymbol->log_line(); if (strstr(filename(), "prelude")) return 0; return line(); } void Sym::copy_values(Sym *s) { int temp_id = id; *this = *s; id = temp_id; } Sym * Sym::clone(int members) { if (asymbol) return asymbol->clone(members); Sym *new_sym = copy(); return new_sym; } Sym * Sym::copy() { Sym *s = new_Sym(); s->copy_values(this); return s; } int compar_syms(const void *ai, const void *aj) { uint32 i = (*(Sym**)ai)->id; uint32 j = (*(Sym**)aj)->id; return (i > j) ? 1 : ((i < j) ? -1 : 0); } int Sym::imm_int(int *result) { int i = 0; switch (type->num_kind) { default: return -1; case IF1_NUM_KIND_UINT: { switch (type->num_index) { case IF1_INT_TYPE_8: i = imm.v_uint8; break; case IF1_INT_TYPE_16: i = imm.v_uint16; break; case IF1_INT_TYPE_32: i = imm.v_uint32; break; case IF1_INT_TYPE_64: i = imm.v_uint64; break; default: return -1; } break; } case IF1_NUM_KIND_INT: { switch (type->num_index) { case IF1_INT_TYPE_8: i = imm.v_int8; break; case IF1_INT_TYPE_16: i = imm.v_int16; break; case IF1_INT_TYPE_32: i = imm.v_int32; break; case IF1_INT_TYPE_64: i = imm.v_int64; break; default: return -1; } break; } } *result = i; return 0; } Sym * unalias_type(Sym *s) { if (!s) return s; if (s->type_kind == Type_ALIAS) { Vec<Sym *> aliases; do { if (!s->alias) return 0; Sym *ss = s->alias; if (aliases.set_in(ss)) fail("circular type alias"); aliases.set_add(ss); s = ss; } while (s->type_kind == Type_ALIAS); } return s; } void if1_set_int_type(IF1 *p, Sym *t, int signd, int size) { int ss = 0; size >>= 3; while (size) { ss++; size >>= 1; } p->int_types[ss][signd] = t; t->num_kind = signd ? IF1_NUM_KIND_INT : IF1_NUM_KIND_UINT; t->num_index = ss; } void if1_set_float_type(IF1 *p, Sym *t, int size) { int ss = 0; size >>= 4; ss = size - 1; p->float_types[ss] = t; t->num_kind = IF1_NUM_KIND_FLOAT; t->num_index = ss; } void if1_set_complex_type(IF1 *p, Sym *t, int size) { int ss = 0; size >>= 4; ss = size - 1; p->complex_types[ss] = t; t->num_kind = IF1_NUM_KIND_COMPLEX; t->num_index = ss; } int if1_numeric_size(IF1 *p, Sym *t) { switch (t->num_kind) { case IF1_NUM_KIND_NONE: assert(!"bad case"); break; case IF1_NUM_KIND_INT: case IF1_NUM_KIND_UINT: if (!t->num_index) return sizeof(bool); return 1 << (t->num_index ? t->num_index : 1) - 1; case IF1_NUM_KIND_FLOAT: return 2 + (2 * t->num_index); case IF1_NUM_KIND_COMPLEX: return 2 * (2 + (2 * t->num_index)); } return 0; } #define MAKE_ALIGNOF(_t) \ struct AlignOf##_t { \ char a; \ _t b; \ } #define ALIGNOF(_t) ((int)(intptr_t)&(((struct AlignOf##_t *)0)->b)) MAKE_ALIGNOF(bool); MAKE_ALIGNOF(uint8); MAKE_ALIGNOF(uint16); MAKE_ALIGNOF(uint32); MAKE_ALIGNOF(uint64); MAKE_ALIGNOF(float32); MAKE_ALIGNOF(float64); MAKE_ALIGNOF(complex32); MAKE_ALIGNOF(complex64); typedef char *alignstring; MAKE_ALIGNOF(alignstring); int if1_numeric_alignment(IF1 *p, Sym *t) { int res = -1; switch (t->num_kind) { default: assert(!"case"); break; case IF1_NUM_KIND_UINT: case IF1_NUM_KIND_INT: switch (t->num_index) { case IF1_INT_TYPE_1: return ALIGNOF(bool); break; case IF1_INT_TYPE_8: return ALIGNOF(uint8); break; case IF1_INT_TYPE_16: return ALIGNOF(uint16); break; case IF1_INT_TYPE_32: return ALIGNOF(uint32); break; case IF1_INT_TYPE_64: return ALIGNOF(uint64); break; default: assert(!"case"); } break; case IF1_NUM_KIND_FLOAT: switch (t->num_index) { case IF1_FLOAT_TYPE_32: return ALIGNOF(float32); case IF1_FLOAT_TYPE_64: return ALIGNOF(float64); default: assert(!"case"); } break; case IF1_NUM_KIND_COMPLEX: switch (t->num_index) { case IF1_FLOAT_TYPE_32: return ALIGNOF(complex32); case IF1_FLOAT_TYPE_64: return ALIGNOF(complex64); default: assert(!"case"); } break; case IF1_CONST_KIND_STRING: return ALIGNOF(alignstring); } return res; } void Sym::inherits_add(Sym *s) { implements.add(s); specializes.add(s); includes.add(s); } void Sym::must_implement_and_specialize(Sym *s) { assert(!must_implement && !must_specialize); must_implement = s; must_specialize = s; } Sym * Sym::scalar_type() { if (is_meta_type) return 0; if (this == sym_nil) return type; if (type && type->num_kind) return type; forv_Sym(ss, dispatch_order) if (ss->type && ss->type->num_kind) return ss->type; return 0; } Sym * Sym::coerce_to(Sym *to) { if (this == to) return this; Sym *s1 = this->scalar_type(), *s2 = to->scalar_type(); if (s1 && s2) { Sym *t = coerce_num(s1, s2); if (t == s2) return s2; return NULL; } if (element) { Sym *s1 = element->scalar_type(), *s2 = to->scalar_type(); if (s1 && s2) { Sym *t = coerce_num(s1, s2); if (t == s2) return s2; return NULL; } } if (s1) { if (to == sym_string) return to; } return NULL; } void pp(Sym *s) { printf("(SYM %d ", s->id); if1_dump_sym(stdout, s); printf(")"); }
Patch another performance issue. This time with the "nil" type.
Patch another performance issue. This time with the "nil" type. git-svn-id: 88467cb1fb04b8a755be7e1ee1026be4190196ef@5606 3a8e244f-b0f2-452b-bcba-4c88e055c3ca
C++
apache-2.0
chizarlicious/chapel,hildeth/chapel,chizarlicious/chapel,sungeunchoi/chapel,sungeunchoi/chapel,hildeth/chapel,sungeunchoi/chapel,CoryMcCartan/chapel,hildeth/chapel,hildeth/chapel,sungeunchoi/chapel,CoryMcCartan/chapel,hildeth/chapel,sungeunchoi/chapel,CoryMcCartan/chapel,CoryMcCartan/chapel,chizarlicious/chapel,sungeunchoi/chapel,hildeth/chapel,CoryMcCartan/chapel,CoryMcCartan/chapel,sungeunchoi/chapel,chizarlicious/chapel,CoryMcCartan/chapel,chizarlicious/chapel,sungeunchoi/chapel,chizarlicious/chapel,hildeth/chapel,chizarlicious/chapel
f0c829b67d31b3785636a2ca91aa2fbf5f984c1e
chrome/browser/debugger/devtools_sanity_unittest.cc
chrome/browser/debugger/devtools_sanity_unittest.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "net/test/test_server.h" namespace { // Used to block until a dev tools client window's browser is closed. class BrowserClosedObserver : public NotificationObserver { public: explicit BrowserClosedObserver(Browser* browser) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(browser)); ui_test_utils::RunMessageLoop(); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { MessageLoopForUI::current()->Quit(); } private: NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver); }; // The delay waited in some cases where we don't have a notifications for an // action we take. const int kActionDelayMs = 500; const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html"; const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html"; const char kPauseWhenLoadingDevTools[] = "files/devtools/pause_when_loading_devtools.html"; const char kPauseWhenScriptIsRunning[] = "files/devtools/pause_when_script_is_running.html"; const char kPageWithContentScript[] = "files/devtools/page_with_content_script.html"; class DevToolsSanityTest : public InProcessBrowserTest { public: DevToolsSanityTest() { set_show_window(true); EnableDOMAutomation(); } protected: void RunTest(const std::string& test_name, const std::string& test_page) { OpenDevToolsWindow(test_page); std::string result; // At first check that JavaScript part of the front-end is loaded by // checking that global variable uiTests exists(it's created after all js // files have been loaded) and has runTest method. ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", L"window.domAutomationController.send(" L"'' + (window.uiTests && (typeof uiTests.runTest)));", &result)); if (result == "function") { ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", UTF8ToWide(StringPrintf("uiTests.runTest('%s')", test_name.c_str())), &result)); EXPECT_EQ("[OK]", result); } else { FAIL() << "DevTools front-end is broken."; } CloseDevToolsWindow(); } void OpenDevToolsWindow(const std::string& test_page) { ASSERT_TRUE(test_server()->Start()); GURL url = test_server()->GetURL(test_page); ui_test_utils::NavigateToURL(browser(), url); inspected_rvh_ = GetInspectedTab()->render_view_host(); DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->OpenDevToolsWindow(inspected_rvh_); DevToolsClientHost* client_host = devtools_manager->GetDevToolsClientHostFor(inspected_rvh_); window_ = client_host->AsDevToolsWindow(); RenderViewHost* client_rvh = window_->GetRenderViewHost(); client_contents_ = client_rvh->delegate()->GetAsTabContents(); ui_test_utils::WaitForNavigation(&client_contents_->controller()); } TabContents* GetInspectedTab() { return browser()->GetTabContentsAt(0); } void CloseDevToolsWindow() { DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); // UnregisterDevToolsClientHostFor may destroy window_ so store the browser // first. Browser* browser = window_->browser(); devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_); // Wait only when DevToolsWindow has a browser. For docked DevTools, this // is NULL and we skip the wait. if (browser) BrowserClosedObserver close_observer(browser); } TabContents* client_contents_; DevToolsWindow* window_; RenderViewHost* inspected_rvh_; }; class CancelableQuitTask : public Task { public: explicit CancelableQuitTask(const std::string& timeout_message) : timeout_message_(timeout_message), cancelled_(false) { } void cancel() { cancelled_ = true; } virtual void Run() { if (cancelled_) { return; } FAIL() << timeout_message_; MessageLoop::current()->Quit(); } private: std::string timeout_message_; bool cancelled_; }; // Base class for DevTools tests that test devtools functionality for // extensions and content scripts. class DevToolsExtensionDebugTest : public DevToolsSanityTest, public NotificationObserver { public: DevToolsExtensionDebugTest() : DevToolsSanityTest() { PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_); test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools"); test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions"); } protected: // Load an extention from test\data\devtools\extensions\<extension_name> void LoadExtension(const char* extension_name) { FilePath path = test_extensions_dir_.AppendASCII(extension_name); ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension."; } private: bool LoadExtensionFromPath(const FilePath& path) { ExtensionService* service = browser()->profile()->GetExtensionService(); size_t num_before = service->extensions()->size(); { NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_LOADED, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); service->LoadExtension(path); ui_test_utils::RunMessageLoop(); delayed_quit->cancel(); } size_t num_after = service->extensions()->size(); if (num_after != (num_before + 1)) return false; return WaitForExtensionHostsToLoad(); } bool WaitForExtensionHostsToLoad() { // Wait for all the extension hosts that exist to finish loading. // NOTE: This assumes that the extension host list is not changing while // this method is running. NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension host load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); ExtensionProcessManager* manager = browser()->profile()->GetExtensionProcessManager(); for (ExtensionProcessManager::const_iterator iter = manager->begin(); iter != manager->end();) { if ((*iter)->did_stop_loading()) ++iter; else ui_test_utils::RunMessageLoop(); } delayed_quit->cancel(); return true; } void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::EXTENSION_LOADED: case NotificationType::EXTENSION_HOST_DID_STOP_LOADING: MessageLoopForUI::current()->Quit(); break; default: NOTREACHED(); break; } } FilePath test_extensions_dir_; }; // Tests heap profiler. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) { RunTest("testHeapProfiler", kHeapProfilerPage); } // Tests scripts panel showing. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) { RunTest("testShowScriptsTab", kDebuggerTestPage); } // Tests that scripts tab is populated with inspected scripts even if it // hadn't been shown by the moment inspected paged refreshed. // @see http://crbug.com/26312 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestScriptsTabIsPopulatedOnInspectedPageRefresh) { // Clear inspector settings to ensure that Elements will be // current panel when DevTools window is open. GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings(); RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh", kDebuggerTestPage); } // Tests that a content script is in the scripts list. // This test is disabled, see bug 28961. IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest, TestContentScriptIsPresent) { LoadExtension("simple_content_script"); RunTest("testContentScriptIsPresent", kPageWithContentScript); } // Tests that scripts are not duplicated after Scripts Panel switch. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNoScriptDuplicatesOnPanelSwitch) { RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage); } // Tests that debugger works correctly if pause event occurs when DevTools // frontend is being loaded. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) { RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools); } // Tests that pressing 'Pause' will pause script execution if the script // is already running. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) { RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning); } } // namespace
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "net/test/test_server.h" namespace { // Used to block until a dev tools client window's browser is closed. class BrowserClosedObserver : public NotificationObserver { public: explicit BrowserClosedObserver(Browser* browser) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(browser)); ui_test_utils::RunMessageLoop(); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { MessageLoopForUI::current()->Quit(); } private: NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver); }; // The delay waited in some cases where we don't have a notifications for an // action we take. const int kActionDelayMs = 500; const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html"; const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html"; const char kPauseWhenLoadingDevTools[] = "files/devtools/pause_when_loading_devtools.html"; const char kPauseWhenScriptIsRunning[] = "files/devtools/pause_when_script_is_running.html"; const char kPageWithContentScript[] = "files/devtools/page_with_content_script.html"; class DevToolsSanityTest : public InProcessBrowserTest { public: DevToolsSanityTest() { set_show_window(true); EnableDOMAutomation(); } protected: void RunTest(const std::string& test_name, const std::string& test_page) { OpenDevToolsWindow(test_page); std::string result; // At first check that JavaScript part of the front-end is loaded by // checking that global variable uiTests exists(it's created after all js // files have been loaded) and has runTest method. ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", L"window.domAutomationController.send(" L"'' + (window.uiTests && (typeof uiTests.runTest)));", &result)); if (result == "function") { ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", UTF8ToWide(StringPrintf("uiTests.runTest('%s')", test_name.c_str())), &result)); EXPECT_EQ("[OK]", result); } else { FAIL() << "DevTools front-end is broken."; } CloseDevToolsWindow(); } void OpenDevToolsWindow(const std::string& test_page) { ASSERT_TRUE(test_server()->Start()); GURL url = test_server()->GetURL(test_page); ui_test_utils::NavigateToURL(browser(), url); inspected_rvh_ = GetInspectedTab()->render_view_host(); DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->OpenDevToolsWindow(inspected_rvh_); DevToolsClientHost* client_host = devtools_manager->GetDevToolsClientHostFor(inspected_rvh_); window_ = client_host->AsDevToolsWindow(); RenderViewHost* client_rvh = window_->GetRenderViewHost(); client_contents_ = client_rvh->delegate()->GetAsTabContents(); ui_test_utils::WaitForNavigation(&client_contents_->controller()); } TabContents* GetInspectedTab() { return browser()->GetTabContentsAt(0); } void CloseDevToolsWindow() { DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); // UnregisterDevToolsClientHostFor may destroy window_ so store the browser // first. Browser* browser = window_->browser(); devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_); // Wait only when DevToolsWindow has a browser. For docked DevTools, this // is NULL and we skip the wait. if (browser) BrowserClosedObserver close_observer(browser); } TabContents* client_contents_; DevToolsWindow* window_; RenderViewHost* inspected_rvh_; }; class CancelableQuitTask : public Task { public: explicit CancelableQuitTask(const std::string& timeout_message) : timeout_message_(timeout_message), cancelled_(false) { } void cancel() { cancelled_ = true; } virtual void Run() { if (cancelled_) { return; } FAIL() << timeout_message_; MessageLoop::current()->Quit(); } private: std::string timeout_message_; bool cancelled_; }; // Base class for DevTools tests that test devtools functionality for // extensions and content scripts. class DevToolsExtensionDebugTest : public DevToolsSanityTest, public NotificationObserver { public: DevToolsExtensionDebugTest() : DevToolsSanityTest() { PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_); test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools"); test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions"); } protected: // Load an extention from test\data\devtools\extensions\<extension_name> void LoadExtension(const char* extension_name) { FilePath path = test_extensions_dir_.AppendASCII(extension_name); ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension."; } private: bool LoadExtensionFromPath(const FilePath& path) { ExtensionService* service = browser()->profile()->GetExtensionService(); size_t num_before = service->extensions()->size(); { NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_LOADED, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); service->LoadExtension(path); ui_test_utils::RunMessageLoop(); delayed_quit->cancel(); } size_t num_after = service->extensions()->size(); if (num_after != (num_before + 1)) return false; return WaitForExtensionHostsToLoad(); } bool WaitForExtensionHostsToLoad() { // Wait for all the extension hosts that exist to finish loading. // NOTE: This assumes that the extension host list is not changing while // this method is running. NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension host load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); ExtensionProcessManager* manager = browser()->profile()->GetExtensionProcessManager(); for (ExtensionProcessManager::const_iterator iter = manager->begin(); iter != manager->end();) { if ((*iter)->did_stop_loading()) ++iter; else ui_test_utils::RunMessageLoop(); } delayed_quit->cancel(); return true; } void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::EXTENSION_LOADED: case NotificationType::EXTENSION_HOST_DID_STOP_LOADING: MessageLoopForUI::current()->Quit(); break; default: NOTREACHED(); break; } } FilePath test_extensions_dir_; }; // Tests heap profiler. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) { RunTest("testHeapProfiler", kHeapProfilerPage); } // Tests scripts panel showing. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) { RunTest("testShowScriptsTab", kDebuggerTestPage); } // Tests that scripts tab is populated with inspected scripts even if it // hadn't been shown by the moment inspected paged refreshed. // @see http://crbug.com/26312 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestScriptsTabIsPopulatedOnInspectedPageRefresh) { // Clear inspector settings to ensure that Elements will be // current panel when DevTools window is open. GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings(); RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh", kDebuggerTestPage); } // Tests that a content script is in the scripts list. // This test is disabled, see bug 28961. IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest, TestContentScriptIsPresent) { LoadExtension("simple_content_script"); RunTest("testContentScriptIsPresent", kPageWithContentScript); } // Tests that scripts are not duplicated after Scripts Panel switch. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNoScriptDuplicatesOnPanelSwitch) { RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage); } // Tests that debugger works correctly if pause event occurs when DevTools // frontend is being loaded. // Disabled in http://crbug.com/70639 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseWhenLoadingDevTools) { RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools); } // Tests that pressing 'Pause' will pause script execution if the script // is already running. // Disabled in http://crbug.com/70639 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseWhenScriptIsRunning) { RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning); } } // namespace
Disable DevToolsSanityTest.TestPauseWhenLoadingDevTools and DevToolsSanityTest.TestPauseWhenScriptIsRunning. They started failing after a webkit roll on Linux.
Disable DevToolsSanityTest.TestPauseWhenLoadingDevTools and DevToolsSanityTest.TestPauseWhenScriptIsRunning. They started failing after a webkit roll on Linux. BUG=70639 Review URL: http://codereview.chromium.org/6266019 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@72357 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
C++
bsd-3-clause
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
2a92f0b12ca433c1166a6b560e7f4e7f36950e3a
chrome/browser/debugger/devtools_sanity_unittest.cc
chrome/browser/debugger/devtools_sanity_unittest.cc
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/browser.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" namespace { // Used to block until a dev tools client window's browser is closed. class BrowserClosedObserver : public NotificationObserver { public: explicit BrowserClosedObserver(Browser* browser) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(browser)); ui_test_utils::RunMessageLoop(); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { MessageLoopForUI::current()->Quit(); } private: NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver); }; // The delay waited in some cases where we don't have a notifications for an // action we take. const int kActionDelayMs = 500; const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html"; const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html"; const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html"; const wchar_t kJsPage[] = L"files/devtools/js_page.html"; const wchar_t kPauseOnExceptionTestPage[] = L"files/devtools/pause_on_exception.html"; const wchar_t kPauseWhenLoadingDevTools[] = L"files/devtools/pause_when_loading_devtools.html"; const wchar_t kPauseWhenScriptIsRunning[] = L"files/devtools/pause_when_script_is_running.html"; const wchar_t kResourceContentLengthTestPage[] = L"files/devtools/image.html"; const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html"; const wchar_t kSimplePage[] = L"files/devtools/simple_page.html"; const wchar_t kSyntaxErrorTestPage[] = L"files/devtools/script_syntax_error.html"; const wchar_t kDebuggerStepTestPage[] = L"files/devtools/debugger_step.html"; const wchar_t kDebuggerClosurePage[] = L"files/devtools/debugger_closure.html"; const wchar_t kDebuggerIntrinsicPropertiesPage[] = L"files/devtools/debugger_intrinsic_properties.html"; const wchar_t kCompletionOnPause[] = L"files/devtools/completion_on_pause.html"; const wchar_t kPageWithContentScript[] = L"files/devtools/page_with_content_script.html"; class DevToolsSanityTest : public InProcessBrowserTest { public: DevToolsSanityTest() { set_show_window(true); EnableDOMAutomation(); } protected: void RunTest(const std::string& test_name, const std::wstring& test_page) { OpenDevToolsWindow(test_page); std::string result; // At first check that JavaScript part of the front-end is loaded by // checking that global variable uiTests exists(it's created after all js // files have been loaded) and has runTest method. ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", L"window.domAutomationController.send(" L"'' + (window.uiTests && (typeof uiTests.runTest)));", &result)); if (result == "function") { ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", UTF8ToWide(StringPrintf("uiTests.runTest('%s')", test_name.c_str())), &result)); EXPECT_EQ("[OK]", result); } else { FAIL() << "DevTools front-end is broken."; } CloseDevToolsWindow(); } void OpenDevToolsWindow(const std::wstring& test_page) { HTTPTestServer* server = StartHTTPServer(); GURL url = server->TestServerPageW(test_page); ui_test_utils::NavigateToURL(browser(), url); inspected_rvh_ = GetInspectedTab()->render_view_host(); DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->OpenDevToolsWindow(inspected_rvh_); DevToolsClientHost* client_host = devtools_manager->GetDevToolsClientHostFor(inspected_rvh_); window_ = client_host->AsDevToolsWindow(); RenderViewHost* client_rvh = window_->GetRenderViewHost(); client_contents_ = client_rvh->delegate()->GetAsTabContents(); ui_test_utils::WaitForNavigation(&client_contents_->controller()); } TabContents* GetInspectedTab() { return browser()->GetTabContentsAt(0); } void CloseDevToolsWindow() { DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); // UnregisterDevToolsClientHostFor may destroy window_ so store the browser // first. Browser* browser = window_->browser(); devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_); BrowserClosedObserver close_observer(browser); } TabContents* client_contents_; DevToolsWindow* window_; RenderViewHost* inspected_rvh_; }; class CancelableQuitTask : public Task { public: explicit CancelableQuitTask(const std::string& timeout_message) : timeout_message_(timeout_message), cancelled_(false) { } void cancel() { cancelled_ = true; } virtual void Run() { if (cancelled_) { return; } FAIL() << timeout_message_; MessageLoop::current()->Quit(); } private: std::string timeout_message_; bool cancelled_; }; // Base class for DevTools tests that test devtools functionality for // extensions and content scripts. class DevToolsExtensionDebugTest : public DevToolsSanityTest, public NotificationObserver { public: DevToolsExtensionDebugTest() : DevToolsSanityTest() { PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_); test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools"); test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions"); } protected: // Load an extention from test\data\devtools\extensions\<extension_name> void LoadExtension(const char* extension_name) { FilePath path = test_extensions_dir_.AppendASCII(extension_name); ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension."; } private: bool LoadExtensionFromPath(const FilePath& path) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); size_t num_before = service->extensions()->size(); { NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_LOADED, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); service->LoadExtension(path); ui_test_utils::RunMessageLoop(); delayed_quit->cancel(); } size_t num_after = service->extensions()->size(); if (num_after != (num_before + 1)) return false; return WaitForExtensionHostsToLoad(); } bool WaitForExtensionHostsToLoad() { // Wait for all the extension hosts that exist to finish loading. // NOTE: This assumes that the extension host list is not changing while // this method is running. NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension host load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); ExtensionProcessManager* manager = browser()->profile()->GetExtensionProcessManager(); for (ExtensionProcessManager::const_iterator iter = manager->begin(); iter != manager->end();) { if ((*iter)->did_stop_loading()) ++iter; else ui_test_utils::RunMessageLoop(); } delayed_quit->cancel(); return true; } void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::EXTENSION_LOADED: case NotificationType::EXTENSION_HOST_DID_STOP_LOADING: MessageLoopForUI::current()->Quit(); break; default: NOTREACHED(); break; } } FilePath test_extensions_dir_; }; // WebInspector opens. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) { RunTest("testHostIsPresent", kSimplePage); } // Tests elements panel basics. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) { RunTest("testElementsTreeRoot", kSimplePage); } // Tests main resource load. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) { RunTest("testMainResource", kSimplePage); } // Tests resources panel enabling. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) { RunTest("testEnableResourcesTab", kSimplePage); } // Tests resources have correct sizes. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestResourceContentLength) { RunTest("testResourceContentLength", kResourceContentLengthTestPage); } // Tests resource headers. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) { RunTest("testResourceHeaders", kResourceTestPage); } // Tests cached resource mime type. // @see http://crbug.com/27364 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestCachedResourceMimeType) { RunTest("testCachedResourceMimeType", kResourceTestPage); } // Tests profiler panel. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) { RunTest("testProfilerTab", kJsPage); } // Tests scripts panel showing. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) { RunTest("testShowScriptsTab", kDebuggerTestPage); } // Tests that scripts tab is populated with inspected scripts even if it // hadn't been shown by the moment inspected paged refreshed. // @see http://crbug.com/26312 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestScriptsTabIsPopulatedOnInspectedPageRefresh) { // Reset inspector settings to defaults to ensure that Elements will be // current panel when DevTools window is open. GetInspectedTab()->render_view_host()->delegate()->UpdateInspectorSettings( WebPreferences().inspector_settings); RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh", kDebuggerTestPage); } // Tests that a content script is in the scripts list. // This test is disabled, see bug 28961. IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest, DISABLED_TestContentScriptIsPresent) { LoadExtension("simple_content_script"); RunTest("testContentScriptIsPresent", kPageWithContentScript); } // Tests that scripts are not duplicated after Scripts Panel switch. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNoScriptDuplicatesOnPanelSwitch) { RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage); } // Tests set breakpoint. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) { RunTest("testSetBreakpoint", kDebuggerTestPage); } // Tests pause on exception. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseOnException) { RunTest("testPauseOnException", kPauseOnExceptionTestPage); } // Tests that debugger works correctly if pause event occurs when DevTools // frontend is being loaded. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) { RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools); } // Tests that pressing 'Pause' will pause script execution if the script // is already running. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseWhenScriptIsRunning) { RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning); } // Tests eval on call frame. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalOnCallFrame) { RunTest("testEvalOnCallFrame", kDebuggerTestPage); } // Tests step over functionality in the debugger. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestStepOver) { RunTest("testStepOver", kDebuggerStepTestPage); } // Tests step out functionality in the debugger. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestStepOut) { RunTest("testStepOut", kDebuggerStepTestPage); } // Tests step in functionality in the debugger. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestStepIn) { RunTest("testStepIn", kDebuggerStepTestPage); } // Tests that scope can be expanded and contains expected variables. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestExpandScope) { RunTest("testExpandScope", kDebuggerClosurePage); } // Tests that intrinsic properties(__proto__, prototype, constructor) are // present. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestDebugIntrinsicProperties) { RunTest("testDebugIntrinsicProperties", kDebuggerIntrinsicPropertiesPage); } // Tests that execution continues automatically when there is a syntax error in // script and DevTools are open. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestAutoContinueOnSyntaxError) { RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage); } IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestCompletionOnPause) { RunTest("testCompletionOnPause", kCompletionOnPause); } // Tests that 'Pause' button works for eval. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) { RunTest("testPauseInEval", kDebuggerTestPage); } // Tests console eval. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleEval) { RunTest("testConsoleEval", kConsoleTestPage); } // Tests console log. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) { RunTest("testConsoleLog", kConsoleTestPage); } // Tests eval global values. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEvalGlobal) { RunTest("testEvalGlobal", kEvalTestPage); } // Test that Storage panel can be shown. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestShowStoragePanel) { RunTest("testShowStoragePanel", kDebuggerTestPage); } } // namespace
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/browser.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" namespace { // Used to block until a dev tools client window's browser is closed. class BrowserClosedObserver : public NotificationObserver { public: explicit BrowserClosedObserver(Browser* browser) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(browser)); ui_test_utils::RunMessageLoop(); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { MessageLoopForUI::current()->Quit(); } private: NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver); }; // The delay waited in some cases where we don't have a notifications for an // action we take. const int kActionDelayMs = 500; const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html"; const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html"; const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html"; const wchar_t kJsPage[] = L"files/devtools/js_page.html"; const wchar_t kPauseOnExceptionTestPage[] = L"files/devtools/pause_on_exception.html"; const wchar_t kPauseWhenLoadingDevTools[] = L"files/devtools/pause_when_loading_devtools.html"; const wchar_t kPauseWhenScriptIsRunning[] = L"files/devtools/pause_when_script_is_running.html"; const wchar_t kResourceContentLengthTestPage[] = L"files/devtools/image.html"; const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html"; const wchar_t kSimplePage[] = L"files/devtools/simple_page.html"; const wchar_t kSyntaxErrorTestPage[] = L"files/devtools/script_syntax_error.html"; const wchar_t kDebuggerStepTestPage[] = L"files/devtools/debugger_step.html"; const wchar_t kDebuggerClosurePage[] = L"files/devtools/debugger_closure.html"; const wchar_t kDebuggerIntrinsicPropertiesPage[] = L"files/devtools/debugger_intrinsic_properties.html"; const wchar_t kCompletionOnPause[] = L"files/devtools/completion_on_pause.html"; const wchar_t kPageWithContentScript[] = L"files/devtools/page_with_content_script.html"; class DevToolsSanityTest : public InProcessBrowserTest { public: DevToolsSanityTest() { set_show_window(true); EnableDOMAutomation(); } protected: void RunTest(const std::string& test_name, const std::wstring& test_page) { OpenDevToolsWindow(test_page); std::string result; // At first check that JavaScript part of the front-end is loaded by // checking that global variable uiTests exists(it's created after all js // files have been loaded) and has runTest method. ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", L"window.domAutomationController.send(" L"'' + (window.uiTests && (typeof uiTests.runTest)));", &result)); if (result == "function") { ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_->render_view_host(), L"", UTF8ToWide(StringPrintf("uiTests.runTest('%s')", test_name.c_str())), &result)); EXPECT_EQ("[OK]", result); } else { FAIL() << "DevTools front-end is broken."; } CloseDevToolsWindow(); } void OpenDevToolsWindow(const std::wstring& test_page) { HTTPTestServer* server = StartHTTPServer(); GURL url = server->TestServerPageW(test_page); ui_test_utils::NavigateToURL(browser(), url); inspected_rvh_ = GetInspectedTab()->render_view_host(); DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->OpenDevToolsWindow(inspected_rvh_); DevToolsClientHost* client_host = devtools_manager->GetDevToolsClientHostFor(inspected_rvh_); window_ = client_host->AsDevToolsWindow(); RenderViewHost* client_rvh = window_->GetRenderViewHost(); client_contents_ = client_rvh->delegate()->GetAsTabContents(); ui_test_utils::WaitForNavigation(&client_contents_->controller()); } TabContents* GetInspectedTab() { return browser()->GetTabContentsAt(0); } void CloseDevToolsWindow() { DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); // UnregisterDevToolsClientHostFor may destroy window_ so store the browser // first. Browser* browser = window_->browser(); devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_); BrowserClosedObserver close_observer(browser); } TabContents* client_contents_; DevToolsWindow* window_; RenderViewHost* inspected_rvh_; }; class CancelableQuitTask : public Task { public: explicit CancelableQuitTask(const std::string& timeout_message) : timeout_message_(timeout_message), cancelled_(false) { } void cancel() { cancelled_ = true; } virtual void Run() { if (cancelled_) { return; } FAIL() << timeout_message_; MessageLoop::current()->Quit(); } private: std::string timeout_message_; bool cancelled_; }; // Base class for DevTools tests that test devtools functionality for // extensions and content scripts. class DevToolsExtensionDebugTest : public DevToolsSanityTest, public NotificationObserver { public: DevToolsExtensionDebugTest() : DevToolsSanityTest() { PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_); test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools"); test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions"); } protected: // Load an extention from test\data\devtools\extensions\<extension_name> void LoadExtension(const char* extension_name) { FilePath path = test_extensions_dir_.AppendASCII(extension_name); ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension."; } private: bool LoadExtensionFromPath(const FilePath& path) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); size_t num_before = service->extensions()->size(); { NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_LOADED, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); service->LoadExtension(path); ui_test_utils::RunMessageLoop(); delayed_quit->cancel(); } size_t num_after = service->extensions()->size(); if (num_after != (num_before + 1)) return false; return WaitForExtensionHostsToLoad(); } bool WaitForExtensionHostsToLoad() { // Wait for all the extension hosts that exist to finish loading. // NOTE: This assumes that the extension host list is not changing while // this method is running. NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension host load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); ExtensionProcessManager* manager = browser()->profile()->GetExtensionProcessManager(); for (ExtensionProcessManager::const_iterator iter = manager->begin(); iter != manager->end();) { if ((*iter)->did_stop_loading()) ++iter; else ui_test_utils::RunMessageLoop(); } delayed_quit->cancel(); return true; } void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::EXTENSION_LOADED: case NotificationType::EXTENSION_HOST_DID_STOP_LOADING: MessageLoopForUI::current()->Quit(); break; default: NOTREACHED(); break; } } FilePath test_extensions_dir_; }; // WebInspector opens. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) { RunTest("testHostIsPresent", kSimplePage); } // Tests elements panel basics. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) { RunTest("testElementsTreeRoot", kSimplePage); } // Tests main resource load. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) { RunTest("testMainResource", kSimplePage); } // Tests resources panel enabling. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) { RunTest("testEnableResourcesTab", kSimplePage); } // Tests resources have correct sizes. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestResourceContentLength) { RunTest("testResourceContentLength", kResourceContentLengthTestPage); } // Tests resource headers. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) { RunTest("testResourceHeaders", kResourceTestPage); } // Tests cached resource mime type. // @see http://crbug.com/27364 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestCachedResourceMimeType) { RunTest("testCachedResourceMimeType", kResourceTestPage); } // Tests profiler panel. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) { RunTest("testProfilerTab", kJsPage); } // Tests scripts panel showing. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) { RunTest("testShowScriptsTab", kDebuggerTestPage); } // Tests that scripts tab is populated with inspected scripts even if it // hadn't been shown by the moment inspected paged refreshed. // @see http://crbug.com/26312 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestScriptsTabIsPopulatedOnInspectedPageRefresh) { // Reset inspector settings to defaults to ensure that Elements will be // current panel when DevTools window is open. GetInspectedTab()->render_view_host()->delegate()->UpdateInspectorSettings( WebPreferences().inspector_settings); RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh", kDebuggerTestPage); } // Tests that a content script is in the scripts list. // This test is disabled, see bug 28961. IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest, DISABLED_TestContentScriptIsPresent) { LoadExtension("simple_content_script"); RunTest("testContentScriptIsPresent", kPageWithContentScript); } // Tests that scripts are not duplicated after Scripts Panel switch. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNoScriptDuplicatesOnPanelSwitch) { RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage); } // Tests set breakpoint. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) { RunTest("testSetBreakpoint", kDebuggerTestPage); } // Tests pause on exception. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseOnException) { RunTest("testPauseOnException", kPauseOnExceptionTestPage); } // Tests that debugger works correctly if pause event occurs when DevTools // frontend is being loaded. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) { RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools); } // Tests that pressing 'Pause' will pause script execution if the script // is already running. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseWhenScriptIsRunning) { RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning); } // Tests eval on call frame. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEvalOnCallFrame) { RunTest("testEvalOnCallFrame", kDebuggerTestPage); } // Tests step over functionality in the debugger. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestStepOver) { RunTest("testStepOver", kDebuggerStepTestPage); } // Tests step out functionality in the debugger. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestStepOut) { RunTest("testStepOut", kDebuggerStepTestPage); } // Tests step in functionality in the debugger. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestStepIn) { RunTest("testStepIn", kDebuggerStepTestPage); } // Tests that scope can be expanded and contains expected variables. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestExpandScope) { RunTest("testExpandScope", kDebuggerClosurePage); } // Tests that intrinsic properties(__proto__, prototype, constructor) are // present. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestDebugIntrinsicProperties) { RunTest("testDebugIntrinsicProperties", kDebuggerIntrinsicPropertiesPage); } // Tests that execution continues automatically when there is a syntax error in // script and DevTools are open. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestAutoContinueOnSyntaxError) { RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage); } IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestCompletionOnPause) { RunTest("testCompletionOnPause", kCompletionOnPause); } // Tests that 'Pause' button works for eval. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) { RunTest("testPauseInEval", kDebuggerTestPage); } // Tests console eval. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleEval) { RunTest("testConsoleEval", kConsoleTestPage); } // Tests console log. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) { RunTest("testConsoleLog", kConsoleTestPage); } // Tests eval global values. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEvalGlobal) { RunTest("testEvalGlobal", kEvalTestPage); } // Test that Storage panel can be shown. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestShowStoragePanel) { RunTest("testShowStoragePanel", kDebuggerTestPage); } } // namespace
Disable anther DevTools sanity test that was missed in r34516.
Disable anther DevTools sanity test that was missed in r34516. BUG=30418 TBR=pfeldman Review URL: http://codereview.chromium.org/500007 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@34522 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
ropik/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,ropik/chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium
936e9f2a72d8026d8fc8a3d7ed306442ea8cb429
chrome/browser/views/options/user_data_page_view.cc
chrome/browser/views/options/user_data_page_view.cc
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifdef CHROME_PERSONALIZATION #include "chrome/browser/views/user_data_page_view.h" #include "app/l10n_util.h" #include "base/path_service.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profile.h" #include "chrome/browser/profile_manager.h" #include "chrome/browser/sync/auth_error_state.h" #include "chrome/browser/sync/personalization_strings.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/sync_status_ui_helper.h" #include "chrome/browser/views/clear_browsing_data.h" #include "chrome/browser/views/importer_view.h" #include "chrome/browser/views/options/options_group_view.h" #include "chrome/browser/views/options/options_page_view.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_member.h" #include "chrome/common/pref_service.h" #include "grit/generated_resources.h" #include "third_party/skia/include/core/SkColor.h" #include "views/background.h" #include "views/controls/button/native_button.h" #include "views/controls/label.h" #include "views/controls/link.h" #include "views/controls/table/table_view.h" #include "views/grid_layout.h" #include "views/standard_layout.h" #include "views/view.h" #include "views/widget/widget.h" #include "views/window/window.h" // Background color for the status label when it's showing an error. static const SkColor kSyncLabelErrorBgColor = SkColorSetRGB(0xff, 0x9a, 0x9a); static views::Background* CreateErrorBackground() { return views::Background::CreateSolidBackground(kSyncLabelErrorBgColor); } UserDataPageView::UserDataPageView(Profile* profile) : OptionsPageView(profile), sync_group_(NULL), sync_status_label_(NULL), sync_action_link_(NULL), sync_start_stop_button_(NULL), sync_service_(profile->GetProfilePersonalization()->sync_service()) { DCHECK(sync_service_); sync_service_->AddObserver(this); } UserDataPageView::~UserDataPageView() { sync_service_->RemoveObserver(this); } void UserDataPageView::ButtonPressed(views::Button* sender) { DCHECK(sender == sync_start_stop_button_); if (!sync_service_->IsSyncEnabledByUser()) { // Sync has not been enabled yet. sync_service_->EnableForUser(); } else { sync_service_->DisableForUser(); } } void UserDataPageView::LinkActivated(views::Link* source, int event_flags) { DCHECK_EQ(source, sync_action_link_); sync_service_->ShowLoginDialog(); } void UserDataPageView::InitControlLayout() { using views::GridLayout; using views::ColumnSet; GridLayout* layout = new GridLayout(this); layout->SetInsets(5, 5, 5, 5); SetLayoutManager(layout); const int single_column_view_set_id = 0; ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, single_column_view_set_id); InitSyncGroup(); layout->AddView(sync_group_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } void UserDataPageView::NotifyPrefChanged(const std::wstring* pref_name) { } void UserDataPageView::OnStateChanged() { // If the UI controls are not yet initialized, then don't do anything. This // can happen if the Options dialog is up, but the User Data tab is not yet // clicked. if (IsInitialized()) Layout(); } void UserDataPageView::HighlightGroup(OptionsGroup highlight_group) { } void UserDataPageView::Layout() { UpdateControls(); // We need to Layout twice - once to get the width of the contents box... View::Layout(); int sync_group_width = sync_group_->GetContentsWidth(); sync_status_label_->SetBounds(0, 0, sync_group_width, 0); // ... and twice to get the height of multi-line items correct. View::Layout(); } void UserDataPageView::InitSyncGroup() { sync_status_label_ = new views::Label; sync_status_label_->SetMultiLine(true); sync_status_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); sync_action_link_ = new views::Link(); sync_action_link_->set_collapse_when_hidden(true); sync_action_link_->SetController(this); sync_start_stop_button_ = new views::NativeButton(this, std::wstring()); using views::GridLayout; using views::ColumnSet; views::View* contents = new views::View; GridLayout* layout = new GridLayout(contents); contents->SetLayoutManager(layout); const int single_column_view_set_id = 0; ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1, GridLayout::USE_PREF, 0, 0); // Currently we add the status label and the link in two rows. This is not // the same as the mocks. If we add label and the link in two columns to make // it look like the mocks then we can have a UI layout issue. If the label // has text that fits in one line, the appearance is fine. But if the label // has text with multiple lines, the appearance can be a bit detached. See // bug 1648522 for details. // TODO(munjal): Change the layout after we fix bug 1648522. layout->StartRow(0, single_column_view_set_id); layout->AddView(sync_status_label_); layout->StartRow(0, single_column_view_set_id); layout->AddView(sync_action_link_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_view_set_id); layout->AddView(sync_start_stop_button_); sync_group_ = new OptionsGroupView(contents, kSyncGroupName, std::wstring(), true); } void UserDataPageView::UpdateControls() { std::wstring status_label; std::wstring link_label; std::wstring button_label; bool sync_enabled = sync_service_->IsSyncEnabledByUser(); bool status_has_error = SyncStatusUIHelper::GetLabels(sync_service_, &status_label, &link_label) == SyncStatusUIHelper::SYNC_ERROR; button_label = sync_enabled ? kStopSyncButtonLabel : sync_service_->SetupInProgress() ? UTF8ToWide(kSettingUpText) : kStartSyncButtonLabel; sync_status_label_->SetText(status_label); sync_start_stop_button_->SetEnabled(!sync_service_->WizardIsVisible()); sync_start_stop_button_->SetLabel(button_label); sync_action_link_->SetText(link_label); sync_action_link_->SetVisible(!link_label.empty()); if (status_has_error) { sync_status_label_->set_background(CreateErrorBackground()); sync_action_link_->set_background(CreateErrorBackground()); } else { sync_status_label_->set_background(NULL); sync_action_link_->set_background(NULL); } } #endif // CHROME_PERSONALIZATION
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifdef CHROME_PERSONALIZATION #include "chrome/browser/views/options/user_data_page_view.h" #include "app/l10n_util.h" #include "base/path_service.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profile.h" #include "chrome/browser/profile_manager.h" #include "chrome/browser/sync/auth_error_state.h" #include "chrome/browser/sync/personalization_strings.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/sync_status_ui_helper.h" #include "chrome/browser/views/clear_browsing_data.h" #include "chrome/browser/views/importer_view.h" #include "chrome/browser/views/options/options_group_view.h" #include "chrome/browser/views/options/options_page_view.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_member.h" #include "chrome/common/pref_service.h" #include "grit/generated_resources.h" #include "third_party/skia/include/core/SkColor.h" #include "views/background.h" #include "views/controls/button/native_button.h" #include "views/controls/label.h" #include "views/controls/link.h" #include "views/controls/table/table_view.h" #include "views/grid_layout.h" #include "views/standard_layout.h" #include "views/view.h" #include "views/widget/widget.h" #include "views/window/window.h" // Background color for the status label when it's showing an error. static const SkColor kSyncLabelErrorBgColor = SkColorSetRGB(0xff, 0x9a, 0x9a); static views::Background* CreateErrorBackground() { return views::Background::CreateSolidBackground(kSyncLabelErrorBgColor); } UserDataPageView::UserDataPageView(Profile* profile) : OptionsPageView(profile), sync_group_(NULL), sync_status_label_(NULL), sync_action_link_(NULL), sync_start_stop_button_(NULL), sync_service_(profile->GetProfilePersonalization()->sync_service()) { DCHECK(sync_service_); sync_service_->AddObserver(this); } UserDataPageView::~UserDataPageView() { sync_service_->RemoveObserver(this); } void UserDataPageView::ButtonPressed(views::Button* sender) { DCHECK(sender == sync_start_stop_button_); if (!sync_service_->IsSyncEnabledByUser()) { // Sync has not been enabled yet. sync_service_->EnableForUser(); } else { sync_service_->DisableForUser(); } } void UserDataPageView::LinkActivated(views::Link* source, int event_flags) { DCHECK_EQ(source, sync_action_link_); sync_service_->ShowLoginDialog(); } void UserDataPageView::InitControlLayout() { using views::GridLayout; using views::ColumnSet; GridLayout* layout = new GridLayout(this); layout->SetInsets(5, 5, 5, 5); SetLayoutManager(layout); const int single_column_view_set_id = 0; ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, single_column_view_set_id); InitSyncGroup(); layout->AddView(sync_group_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } void UserDataPageView::NotifyPrefChanged(const std::wstring* pref_name) { } void UserDataPageView::OnStateChanged() { // If the UI controls are not yet initialized, then don't do anything. This // can happen if the Options dialog is up, but the User Data tab is not yet // clicked. if (IsInitialized()) Layout(); } void UserDataPageView::HighlightGroup(OptionsGroup highlight_group) { } void UserDataPageView::Layout() { UpdateControls(); // We need to Layout twice - once to get the width of the contents box... View::Layout(); int sync_group_width = sync_group_->GetContentsWidth(); sync_status_label_->SetBounds(0, 0, sync_group_width, 0); // ... and twice to get the height of multi-line items correct. View::Layout(); } void UserDataPageView::InitSyncGroup() { sync_status_label_ = new views::Label; sync_status_label_->SetMultiLine(true); sync_status_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); sync_action_link_ = new views::Link(); sync_action_link_->set_collapse_when_hidden(true); sync_action_link_->SetController(this); sync_start_stop_button_ = new views::NativeButton(this, std::wstring()); using views::GridLayout; using views::ColumnSet; views::View* contents = new views::View; GridLayout* layout = new GridLayout(contents); contents->SetLayoutManager(layout); const int single_column_view_set_id = 0; ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1, GridLayout::USE_PREF, 0, 0); // Currently we add the status label and the link in two rows. This is not // the same as the mocks. If we add label and the link in two columns to make // it look like the mocks then we can have a UI layout issue. If the label // has text that fits in one line, the appearance is fine. But if the label // has text with multiple lines, the appearance can be a bit detached. See // bug 1648522 for details. // TODO(munjal): Change the layout after we fix bug 1648522. layout->StartRow(0, single_column_view_set_id); layout->AddView(sync_status_label_); layout->StartRow(0, single_column_view_set_id); layout->AddView(sync_action_link_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_view_set_id); layout->AddView(sync_start_stop_button_); sync_group_ = new OptionsGroupView(contents, kSyncGroupName, std::wstring(), true); } void UserDataPageView::UpdateControls() { std::wstring status_label; std::wstring link_label; std::wstring button_label; bool sync_enabled = sync_service_->IsSyncEnabledByUser(); bool status_has_error = SyncStatusUIHelper::GetLabels(sync_service_, &status_label, &link_label) == SyncStatusUIHelper::SYNC_ERROR; button_label = sync_enabled ? kStopSyncButtonLabel : sync_service_->SetupInProgress() ? UTF8ToWide(kSettingUpText) : kStartSyncButtonLabel; sync_status_label_->SetText(status_label); sync_start_stop_button_->SetEnabled(!sync_service_->WizardIsVisible()); sync_start_stop_button_->SetLabel(button_label); sync_action_link_->SetText(link_label); sync_action_link_->SetVisible(!link_label.empty()); if (status_has_error) { sync_status_label_->set_background(CreateErrorBackground()); sync_action_link_->set_background(CreateErrorBackground()); } else { sync_status_label_->set_background(NULL); sync_action_link_->set_background(NULL); } } #endif // CHROME_PERSONALIZATION
Fix include path for header file to fix sync build. I'll hold off committing until Idan lets me know I didn't butcher anything else, too :) Review URL: http://codereview.chromium.org/165004
Fix include path for header file to fix sync build. I'll hold off committing until Idan lets me know I didn't butcher anything else, too :) Review URL: http://codereview.chromium.org/165004 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@22546 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
Jonekee/chromium.src,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,robclark/chromium,Jonekee/chromium.src,patrickm/chromium.src,littlstar/chromium.src,mogoweb/chromium-crosswalk,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,markYoungH/chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,rogerwang/chromium,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,Fireblend/chromium-crosswalk,keishi/chromium,dednal/chromium.src,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,keishi/chromium,ltilve/chromium,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,patrickm/chromium.src,dushu1203/chromium.src,nacl-webkit/chrome_deps,Chilledheart/chromium,dednal/chromium.src,jaruba/chromium.src,chuan9/chromium-crosswalk,ltilve/chromium,ChromiumWebApps/chromium,dushu1203/chromium.src,hujiajie/pa-chromium,zcbenz/cefode-chromium,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,dednal/chromium.src,keishi/chromium,krieger-od/nwjs_chromium.src,dednal/chromium.src,robclark/chromium,littlstar/chromium.src,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,timopulkkinen/BubbleFish,M4sse/chromium.src,dednal/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,keishi/chromium,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,mogoweb/chromium-crosswalk,jaruba/chromium.src,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,keishi/chromium,anirudhSK/chromium,Jonekee/chromium.src,dushu1203/chromium.src,robclark/chromium,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,ChromiumWebApps/chromium,rogerwang/chromium,keishi/chromium,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,zcbenz/cefode-chromium,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,anirudhSK/chromium,mogoweb/chromium-crosswalk,littlstar/chromium.src,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,hgl888/chromium-crosswalk,ltilve/chromium,markYoungH/chromium.src,Just-D/chromium-1,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,anirudhSK/chromium,markYoungH/chromium.src,jaruba/chromium.src,patrickm/chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,ltilve/chromium,Jonekee/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,zcbenz/cefode-chromium,robclark/chromium,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,markYoungH/chromium.src,jaruba/chromium.src,dushu1203/chromium.src,rogerwang/chromium,patrickm/chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,rogerwang/chromium,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,jaruba/chromium.src,dednal/chromium.src,mogoweb/chromium-crosswalk,dednal/chromium.src,rogerwang/chromium,keishi/chromium,rogerwang/chromium,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,robclark/chromium,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,robclark/chromium,ChromiumWebApps/chromium,axinging/chromium-crosswalk,Chilledheart/chromium,hgl888/chromium-crosswalk,littlstar/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,ondra-novak/chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,hujiajie/pa-chromium,timopulkkinen/BubbleFish,M4sse/chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,patrickm/chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,axinging/chromium-crosswalk,rogerwang/chromium,Chilledheart/chromium,Just-D/chromium-1,hujiajie/pa-chromium,anirudhSK/chromium,ltilve/chromium,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,keishi/chromium,jaruba/chromium.src,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,keishi/chromium,Chilledheart/chromium,markYoungH/chromium.src,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,markYoungH/chromium.src,chuan9/chromium-crosswalk,dushu1203/chromium.src,robclark/chromium,ltilve/chromium,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,zcbenz/cefode-chromium,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,anirudhSK/chromium,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,robclark/chromium,markYoungH/chromium.src,Jonekee/chromium.src,dednal/chromium.src,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,M4sse/chromium.src,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,markYoungH/chromium.src,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,littlstar/chromium.src,krieger-od/nwjs_chromium.src,ltilve/chromium,M4sse/chromium.src,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,patrickm/chromium.src,rogerwang/chromium,Pluto-tv/chromium-crosswalk,dednal/chromium.src,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,axinging/chromium-crosswalk,keishi/chromium,anirudhSK/chromium,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,rogerwang/chromium,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,dushu1203/chromium.src,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ltilve/chromium,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,Jonekee/chromium.src,robclark/chromium,littlstar/chromium.src,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,robclark/chromium,Pluto-tv/chromium-crosswalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,jaruba/chromium.src,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,keishi/chromium,fujunwei/chromium-crosswalk,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,rogerwang/chromium,nacl-webkit/chrome_deps
2ddd6d0fd3bb72d00eac051d58b1b28876fd5a57
dune/stuff/common/parallel/threadmanager.cc
dune/stuff/common/parallel/threadmanager.cc
// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #include "config.h" #include "threadmanager.hh" #if HAVE_DUNE_FEM #include <dune/fem/misc/threadmanager.hh> unsigned int Dune::Stuff::ThreadManager::max_threads() { return Dune::Fem::ThreadManager::maxThreads(); } unsigned int Dune::Stuff::ThreadManager::current_threads() { return Dune::Fem::ThreadManager::currentThreads(); } unsigned int Dune::Stuff::ThreadManager::thread() { return Dune::Fem::ThreadManager::thread(); } void Dune::Stuff::ThreadManager::set_max_threads(const unsigned int count) { Dune::Fem::ThreadManager::setMaxNumberThreads(count); } #else // if HAVE_DUNE_FEM unsigned int Dune::Stuff::ThreadManager::max_threads() { return 1; } unsigned int Dune::Stuff::ThreadManager::current_threads() { return 1; } unsigned int Dune::Stuff::ThreadManager::thread() { return 1; } void Dune::Stuff::ThreadManager::set_max_threads(const unsigned int /*count*/) {} #endif // HAVE_DUNE_FEM
// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #include "config.h" #include "threadmanager.hh" #if HAVE_DUNE_FEM #include <dune/fem/misc/threads/threadmanager.hh> unsigned int Dune::Stuff::ThreadManager::max_threads() { return Dune::Fem::ThreadManager::maxThreads(); } unsigned int Dune::Stuff::ThreadManager::current_threads() { return Dune::Fem::ThreadManager::currentThreads(); } unsigned int Dune::Stuff::ThreadManager::thread() { return Dune::Fem::ThreadManager::thread(); } void Dune::Stuff::ThreadManager::set_max_threads(const unsigned int count) { Dune::Fem::ThreadManager::setMaxNumberThreads(count); } #else // if HAVE_DUNE_FEM unsigned int Dune::Stuff::ThreadManager::max_threads() { return 1; } unsigned int Dune::Stuff::ThreadManager::current_threads() { return 1; } unsigned int Dune::Stuff::ThreadManager::thread() { return 1; } void Dune::Stuff::ThreadManager::set_max_threads(const unsigned int /*count*/) {} #endif // HAVE_DUNE_FEM
replace deprecated include
[common.parallel.threadmanager] replace deprecated include
C++
bsd-2-clause
renemilk/DUNE-Stuff,renemilk/DUNE-Stuff,renemilk/DUNE-Stuff
e31a197b7415042e6a87af0baacf2de95d3585b0
ecmd-core/ext/fapi2/capi/target_types.H
ecmd-core/ext/fapi2/capi/target_types.H
/* IBM_PROLOG_BEGIN_TAG */ /* * Copyright 2019 IBM International Business Machines Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* IBM_PROLOG_END_TAG */ /** * @file target_types.H * @brief definitions for fapi2 target types */ #ifndef __FAPI2_TARGET_TYPES__ #define __FAPI2_TARGET_TYPES__ #include <stdint.h> /// FAPI namespace namespace fapi2 { /// /// @enum fapi::TargetType /// @brief Types, kinds, of targets /// @note TYPE_NONE is used to represent empty/NULL targets in lists /// or tables. TYPE_ALL is used to pass targets to methods which /// can act generally on any type of target /// /// Target Kind enum TargetType : uint64_t { TARGET_TYPE_NONE = 0x0000000000000000, ///< No type TARGET_TYPE_SYSTEM = 0x0000000000000001, ///< System type TARGET_TYPE_DIMM = 0x0000000000000002, ///< DIMM type TARGET_TYPE_PROC_CHIP = 0x0000000000000004, ///< Processor type TARGET_TYPE_MEMBUF_CHIP = 0x0000000000000008, ///< Membuf type TARGET_TYPE_EX = 0x0000000000000010, ///< EX - 2x Core, L2, L3 - can be deconfigured TARGET_TYPE_MBA = 0x0000000000000020, ///< MBA type TARGET_TYPE_MCS = 0x0000000000000040, ///< MCS type TARGET_TYPE_XBUS = 0x0000000000000080, ///< XBUS type TARGET_TYPE_ABUS = 0x0000000000000100, ///< ABUS type TARGET_TYPE_L4 = 0x0000000000000200, ///< L4 type TARGET_TYPE_CORE = 0x0000000000000400, ///< Core TARGET_TYPE_EQ = 0x0000000000000800, ///< EQ - 4x core, 2x L2, 2x L3 - can be deconfigured TARGET_TYPE_MCA = 0x0000000000001000, ///< MCA type TARGET_TYPE_MCBIST = 0x0000000000002000, ///< MCBIST type TARGET_TYPE_MI = 0x0000000000004000, ///< MI Memory Interface (Cumulus) TARGET_TYPE_CAPP = 0x0000000000008000, ///< CAPP target TARGET_TYPE_DMI = 0x0000000000010000, ///< DMI type TARGET_TYPE_OBUS = 0x0000000000020000, ///< OBUS type TARGET_TYPE_OBUS_BRICK = 0x0000000000040000, ///< OBUS BRICK type TARGET_TYPE_SBE = 0x0000000000080000, ///< SBE type TARGET_TYPE_PPE = 0x0000000000100000, ///< PPE type TARGET_TYPE_PERV = 0x0000000000200000, ///< Pervasive type TARGET_TYPE_PEC = 0x0000000000400000, ///< PEC type TARGET_TYPE_PHB = 0x0000000000800000, ///< PHB type TARGET_TYPE_MC = 0x0000000001000000, ///< MC type TARGET_TYPE_OMI = 0x0000000002000000, ///< OMI type TARGET_TYPE_OMIC = 0x0000000004000000, ///< OMIC type TARGET_TYPE_MCC = 0x0000000008000000, ///< MCC type TARGET_TYPE_OCMB_CHIP = 0x0000000010000000, ///< OCMB type TARGET_TYPE_MEM_PORT = 0x0000000020000000, ///< MEM_PORT type TARGET_TYPE_NMMU = 0x0000000040000000, ///< NEST MMU type #ifdef FAPI_2_Z TARGET_TYPE_SC_CHIP = 0x0000000080000000, ///< Z SC type #else TARGET_TYPE_RESERVED = 0x0000000080000000, ///< Reserved for Cronus (Z) #endif TARGET_TYPE_PAU = 0x0000000100000000, ///< PAU type TARGET_TYPE_IOHS = 0x0000000200000000, ///< IOHS type TARGET_TYPE_FC = 0x0000000400000000, ///< Fused Core type TARGET_TYPE_PMIC = 0x0000000800000000, ///< PMIC type TARGET_TYPE_PAUC = 0x0000001000000000, ///< PAUC type TARGET_TYPE_MULTICAST = 0x8000000000000000, ///< MULTICAST type TARGET_TYPE_ALL = 0x7FFFFFFFFFFFFFFF, ///< Any/All types TARGET_TYPE_ALL_MC = 0xFFFFFFFFFFFFFFFF, ///< Any/All types + Multicast // Compound target types TARGET_TYPE_CHIPS = TARGET_TYPE_PROC_CHIP | #ifdef FAPI_2_Z TARGET_TYPE_SC_CHIP | #endif TARGET_TYPE_MEMBUF_CHIP | TARGET_TYPE_OCMB_CHIP, TARGET_TYPE_CHIPLETS = TARGET_TYPE_EX | TARGET_TYPE_MBA | TARGET_TYPE_MCS | TARGET_TYPE_XBUS | TARGET_TYPE_ABUS | TARGET_TYPE_L4 | TARGET_TYPE_CORE | TARGET_TYPE_EQ | TARGET_TYPE_MCA | TARGET_TYPE_MCBIST | TARGET_TYPE_MI | TARGET_TYPE_DMI | TARGET_TYPE_OBUS | TARGET_TYPE_OBUS_BRICK | TARGET_TYPE_SBE | TARGET_TYPE_PPE | TARGET_TYPE_PERV | TARGET_TYPE_PEC | TARGET_TYPE_PHB | TARGET_TYPE_MC | TARGET_TYPE_OMI | TARGET_TYPE_OMIC | TARGET_TYPE_MCC | TARGET_TYPE_MEM_PORT | TARGET_TYPE_NMMU | TARGET_TYPE_PAU | TARGET_TYPE_IOHS | TARGET_TYPE_FC | TARGET_TYPE_PAUC, TARGET_TYPE_MULTICASTABLE = TARGET_TYPE_CORE | TARGET_TYPE_EQ | TARGET_TYPE_MCBIST | TARGET_TYPE_OBUS | TARGET_TYPE_PERV | TARGET_TYPE_PEC, // Mappings to target types found in the error xml files TARGET_TYPE_EX_CHIPLET = TARGET_TYPE_EX, TARGET_TYPE_MBA_CHIPLET = TARGET_TYPE_MBA, TARGET_TYPE_MCS_CHIPLET = TARGET_TYPE_MCS, TARGET_TYPE_XBUS_ENDPOINT = TARGET_TYPE_XBUS, TARGET_TYPE_ABUS_ENDPOINT = TARGET_TYPE_ABUS, #ifdef FAPI_2_Z // Z mappings TARGET_TYPE_EP_CHIP = TARGET_TYPE_PROC_CHIP, TARGET_TYPE_XBUS0 = TARGET_TYPE_XBUS, TARGET_TYPE_XBUS1 = TARGET_TYPE_OBUS, TARGET_TYPE_NEST = TARGET_TYPE_CAPP, TARGET_TYPE_PCIE = TARGET_TYPE_PEC, TARGET_TYPE_GXA = TARGET_TYPE_PHB, #endif }; /// /// Target filter 64-bit /// Declare the enumeration size so that target.H will compile without chip specific filter. /// When users want to use an enumeration value then they can include the chip specific /// target_filters.H, which would have the enumerator list of values. /// enum TargetFilter : uint64_t; // attributeOverride tool requires x86.nfp compile #ifndef CONTEXT_x86_nfp /// @cond constexpr TargetType operator|(TargetType x, TargetType y) { return static_cast<TargetType>(static_cast<uint64_t>(x) | static_cast<uint64_t>(y)); } #endif template<uint64_t V> class bitCount { public: // Don't use enums, too hard to compare static const uint8_t count = bitCount < (V >> 1) >::count + (V & 1); }; template<> class bitCount<0> { public: static const uint8_t count = 0; }; /// @endcond } #endif
/* IBM_PROLOG_BEGIN_TAG */ /* * Copyright 2019 IBM International Business Machines Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* IBM_PROLOG_END_TAG */ /** * @file target_types.H * @brief definitions for fapi2 target types */ #ifndef __FAPI2_TARGET_TYPES__ #define __FAPI2_TARGET_TYPES__ #include <stdint.h> /// FAPI namespace namespace fapi2 { /// /// @enum fapi::TargetType /// @brief Types, kinds, of targets /// @note TYPE_NONE is used to represent empty/NULL targets in lists /// or tables. TYPE_ALL is used to pass targets to methods which /// can act generally on any type of target /// /// Target Kind enum TargetType : uint64_t { TARGET_TYPE_NONE = 0x0000000000000000, ///< No type TARGET_TYPE_SYSTEM = 0x0000000000000001, ///< System type TARGET_TYPE_DIMM = 0x0000000000000002, ///< DIMM type TARGET_TYPE_PROC_CHIP = 0x0000000000000004, ///< Processor type TARGET_TYPE_MEMBUF_CHIP = 0x0000000000000008, ///< Membuf type TARGET_TYPE_EX = 0x0000000000000010, ///< EX - 2x Core, L2, L3 - can be deconfigured TARGET_TYPE_MBA = 0x0000000000000020, ///< MBA type TARGET_TYPE_MCS = 0x0000000000000040, ///< MCS type TARGET_TYPE_XBUS = 0x0000000000000080, ///< XBUS type TARGET_TYPE_ABUS = 0x0000000000000100, ///< ABUS type TARGET_TYPE_L4 = 0x0000000000000200, ///< L4 type TARGET_TYPE_CORE = 0x0000000000000400, ///< Core TARGET_TYPE_EQ = 0x0000000000000800, ///< EQ - 4x core, 2x L2, 2x L3 - can be deconfigured TARGET_TYPE_MCA = 0x0000000000001000, ///< MCA type TARGET_TYPE_MCBIST = 0x0000000000002000, ///< MCBIST type TARGET_TYPE_MI = 0x0000000000004000, ///< MI Memory Interface (Cumulus) TARGET_TYPE_CAPP = 0x0000000000008000, ///< CAPP target TARGET_TYPE_DMI = 0x0000000000010000, ///< DMI type TARGET_TYPE_OBUS = 0x0000000000020000, ///< OBUS type TARGET_TYPE_OBUS_BRICK = 0x0000000000040000, ///< OBUS BRICK type TARGET_TYPE_SBE = 0x0000000000080000, ///< SBE type TARGET_TYPE_PPE = 0x0000000000100000, ///< PPE type TARGET_TYPE_PERV = 0x0000000000200000, ///< Pervasive type TARGET_TYPE_PEC = 0x0000000000400000, ///< PEC type TARGET_TYPE_PHB = 0x0000000000800000, ///< PHB type TARGET_TYPE_MC = 0x0000000001000000, ///< MC type TARGET_TYPE_OMI = 0x0000000002000000, ///< OMI type TARGET_TYPE_OMIC = 0x0000000004000000, ///< OMIC type TARGET_TYPE_MCC = 0x0000000008000000, ///< MCC type TARGET_TYPE_OCMB_CHIP = 0x0000000010000000, ///< OCMB type TARGET_TYPE_MEM_PORT = 0x0000000020000000, ///< MEM_PORT type TARGET_TYPE_NMMU = 0x0000000040000000, ///< NEST MMU type #ifdef FAPI_2_Z TARGET_TYPE_SC_CHIP = 0x0000000080000000, ///< Z SC type #else TARGET_TYPE_RESERVED = 0x0000000080000000, ///< Reserved for Cronus (Z) #endif TARGET_TYPE_PAU = 0x0000000100000000, ///< PAU type TARGET_TYPE_IOHS = 0x0000000200000000, ///< IOHS type TARGET_TYPE_FC = 0x0000000400000000, ///< Fused Core type TARGET_TYPE_PMIC = 0x0000000800000000, ///< PMIC type TARGET_TYPE_PAUC = 0x0000001000000000, ///< PAUC type TARGET_TYPE_MULTICAST = 0x8000000000000000, ///< MULTICAST type TARGET_TYPE_ALL = 0x7FFFFFFFFFFFFFFF, ///< Any/All types TARGET_TYPE_ALL_MC = 0xFFFFFFFFFFFFFFFF, ///< Any/All types + Multicast // Compound target types TARGET_TYPE_CHIPS = TARGET_TYPE_PROC_CHIP | #ifdef FAPI_2_Z TARGET_TYPE_SC_CHIP | #endif TARGET_TYPE_MEMBUF_CHIP | TARGET_TYPE_OCMB_CHIP, TARGET_TYPE_CHIPLETS = TARGET_TYPE_EX | TARGET_TYPE_MBA | TARGET_TYPE_MCS | TARGET_TYPE_XBUS | TARGET_TYPE_ABUS | TARGET_TYPE_L4 | TARGET_TYPE_CORE | TARGET_TYPE_EQ | TARGET_TYPE_MCA | TARGET_TYPE_MCBIST | TARGET_TYPE_MI | TARGET_TYPE_DMI | TARGET_TYPE_OBUS | TARGET_TYPE_OBUS_BRICK | TARGET_TYPE_SBE | TARGET_TYPE_PPE | TARGET_TYPE_PERV | TARGET_TYPE_PEC | TARGET_TYPE_PHB | TARGET_TYPE_MC | TARGET_TYPE_OMI | TARGET_TYPE_OMIC | TARGET_TYPE_MCC | TARGET_TYPE_MEM_PORT | TARGET_TYPE_NMMU | TARGET_TYPE_PAU | TARGET_TYPE_IOHS | TARGET_TYPE_FC | TARGET_TYPE_PAUC, TARGET_TYPE_MULTICASTABLE = TARGET_TYPE_CORE | TARGET_TYPE_EQ | TARGET_TYPE_IOHS | TARGET_TYPE_MC | TARGET_TYPE_PAUC | TARGET_TYPE_PEC | TARGET_TYPE_PERV, // Mappings to target types found in the error xml files TARGET_TYPE_EX_CHIPLET = TARGET_TYPE_EX, TARGET_TYPE_MBA_CHIPLET = TARGET_TYPE_MBA, TARGET_TYPE_MCS_CHIPLET = TARGET_TYPE_MCS, TARGET_TYPE_XBUS_ENDPOINT = TARGET_TYPE_XBUS, TARGET_TYPE_ABUS_ENDPOINT = TARGET_TYPE_ABUS, #ifdef FAPI_2_Z // Z mappings TARGET_TYPE_EP_CHIP = TARGET_TYPE_PROC_CHIP, TARGET_TYPE_XBUS0 = TARGET_TYPE_XBUS, TARGET_TYPE_XBUS1 = TARGET_TYPE_OBUS, TARGET_TYPE_NEST = TARGET_TYPE_CAPP, TARGET_TYPE_PCIE = TARGET_TYPE_PEC, TARGET_TYPE_GXA = TARGET_TYPE_PHB, #endif }; /// /// Target filter 64-bit /// Declare the enumeration size so that target.H will compile without chip specific filter. /// When users want to use an enumeration value then they can include the chip specific /// target_filters.H, which would have the enumerator list of values. /// enum TargetFilter : uint64_t; // attributeOverride tool requires x86.nfp compile #ifndef CONTEXT_x86_nfp /// @cond constexpr TargetType operator|(TargetType x, TargetType y) { return static_cast<TargetType>(static_cast<uint64_t>(x) | static_cast<uint64_t>(y)); } #endif template<uint64_t V> class bitCount { public: // Don't use enums, too hard to compare static const uint8_t count = bitCount < (V >> 1) >::count + (V & 1); }; template<> class bitCount<0> { public: static const uint8_t count = 0; }; /// @endcond } #endif
update fapi2 multicastable type Signed-off-by: Kahn Evans <[email protected]>
update fapi2 multicastable type Signed-off-by: Kahn Evans <[email protected]>
C++
apache-2.0
open-power/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD
08212db733f886143b8d5f4daec18902e70fb247
python/brotlimodule.cc
python/brotlimodule.cc
#define PY_SSIZE_T_CLEAN 1 #include <Python.h> #include <bytesobject.h> #include "../enc/encode.h" #include "../dec/decode.h" #if PY_MAJOR_VERSION >= 3 #define PyInt_Check PyLong_Check #define PyInt_AsLong PyLong_AsLong #endif using namespace brotli; static PyObject *BrotliError; static int mode_convertor(PyObject *o, BrotliParams::Mode *mode) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid mode"); return 0; } *mode = (BrotliParams::Mode) PyInt_AsLong(o); if (*mode != BrotliParams::Mode::MODE_GENERIC && *mode != BrotliParams::Mode::MODE_TEXT && *mode != BrotliParams::Mode::MODE_FONT) { PyErr_SetString(BrotliError, "Invalid mode"); return 0; } return 1; } static int quality_convertor(PyObject *o, int *quality) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid quality"); return 0; } *quality = PyInt_AsLong(o); if (*quality < 0 || *quality > 11) { PyErr_SetString(BrotliError, "Invalid quality. Range is 0 to 11."); return 0; } return 1; } static int lgwin_convertor(PyObject *o, int *lgwin) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid lgwin"); return 0; } *lgwin = PyInt_AsLong(o); if (*lgwin < 16 || *lgwin > 24) { PyErr_SetString(BrotliError, "Invalid lgwin. Range is 16 to 24."); return 0; } return 1; } static int lgblock_convertor(PyObject *o, int *lgblock) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid lgblock"); return 0; } *lgblock = PyInt_AsLong(o); if ((*lgblock != 0 && *lgblock < 16) || *lgblock > 24) { PyErr_SetString(BrotliError, "Invalid lgblock. Can be 0 or in range 16 to 24."); return 0; } return 1; } PyDoc_STRVAR(compress__doc__, "Compress a byte string.\n" "\n" "Signature:\n" " compress(string, mode=MODE_GENERIC, quality=11, lgwin=22, lgblock=0)\n" "\n" "Args:\n" " string (bytes): The input data.\n" " mode (int, optional): The compression mode can be MODE_GENERIC (default),\n" " MODE_TEXT (for UTF-8 format text input) or MODE_FONT (for WOFF 2.0). \n" " quality (int, optional): Controls the compression-speed vs compression-\n" " density tradeoff. The higher the quality, the slower the compression.\n" " Range is 0 to 11. Defaults to 11.\n" " lgwin (int, optional): Base 2 logarithm of the sliding window size. Range\n" " is 16 to 24. Defaults to 22.\n" " lgblock (int, optional): Base 2 logarithm of the maximum input block size.\n" " Range is 16 to 24. If set to 0, the value will be set based on the\n" " quality. Defaults to 0.\n" "\n" "Returns:\n" " The compressed byte string.\n" "\n" "Raises:\n" " brotli.error: If arguments are invalid, or compressor fails.\n"); static PyObject* brotli_compress(PyObject *self, PyObject *args, PyObject *keywds) { PyObject *ret = NULL; uint8_t *input, *output; size_t length, output_length; BrotliParams::Mode mode = (BrotliParams::Mode) -1; int quality = -1; int lgwin = -1; int lgblock = -1; int ok; static char *kwlist[] = {"string", "mode", "quality", "lgwin", "lgblock"}; ok = PyArg_ParseTupleAndKeywords(args, keywds, "s#|O&O&O&O&:compress", kwlist, &input, &length, &mode_convertor, &mode, &quality_convertor, &quality, &lgwin_convertor, &lgwin, &lgblock_convertor, &lgblock); if (!ok) return NULL; output_length = 1.2 * length + 10240; output = new uint8_t[output_length]; BrotliParams params; if (mode != -1) params.mode = mode; if (quality != -1) params.quality = quality; if (lgwin != -1) params.lgwin = lgwin; if (lgblock != -1) params.lgblock = lgblock; ok = BrotliCompressBuffer(params, length, input, &output_length, output); if (ok) { ret = PyBytes_FromStringAndSize((char*)output, output_length); } else { PyErr_SetString(BrotliError, "BrotliCompressBuffer failed"); } delete[] output; return ret; } int output_callback(void* data, const uint8_t* buf, size_t count) { std::vector<uint8_t> *output = (std::vector<uint8_t> *)data; output->insert(output->end(), buf, buf + count); return (int)count; } PyDoc_STRVAR(decompress__doc__, "Decompress a compressed byte string.\n" "\n" "Signature:\n" " decompress(string)\n" "\n" "Args:\n" " string (bytes): The compressed input data.\n" "\n" "Returns:\n" " The decompressed byte string.\n" "\n" "Raises:\n" " brotli.error: If decompressor fails.\n"); static PyObject* brotli_decompress(PyObject *self, PyObject *args) { PyObject *ret = NULL; uint8_t *input; size_t length; int ok; ok = PyArg_ParseTuple(args, "s#:decompress", &input, &length); if (!ok) return NULL; BrotliMemInput memin; BrotliInput in = BrotliInitMemInput(input, length, &memin); BrotliOutput out; std::vector<uint8_t> output; out.cb_ = &output_callback; out.data_ = &output; ok = BrotliDecompress(in, out); if (ok) { ret = PyBytes_FromStringAndSize((char*)output.data(), output.size()); } else { PyErr_SetString(BrotliError, "BrotliDecompress failed"); } return ret; } static PyMethodDef brotli_methods[] = { {"compress", (PyCFunction)brotli_compress, METH_VARARGS | METH_KEYWORDS, compress__doc__}, {"decompress", brotli_decompress, METH_VARARGS, decompress__doc__}, {NULL, NULL, 0, NULL} }; PyDoc_STRVAR(brotli__doc__, "The functions in this module allow compression and decompression using the\n" "Brotli library.\n\n"); #if PY_MAJOR_VERSION >= 3 #define INIT_BROTLI PyInit_brotli #define CREATE_BROTLI PyModule_Create(&brotli_module) #define RETURN_BROTLI return m static struct PyModuleDef brotli_module = { PyModuleDef_HEAD_INIT, "brotli", brotli__doc__, 0, brotli_methods, NULL, NULL, NULL }; #else #define INIT_BROTLI initbrotli #define CREATE_BROTLI Py_InitModule3("brotli", brotli_methods, brotli__doc__) #define RETURN_BROTLI return #endif PyMODINIT_FUNC INIT_BROTLI(void) { PyObject *m = CREATE_BROTLI; BrotliError = PyErr_NewException((char*) "brotli.error", NULL, NULL); if (BrotliError != NULL) { Py_INCREF(BrotliError); PyModule_AddObject(m, "error", BrotliError); } PyModule_AddIntConstant(m, "MODE_GENERIC", (int) BrotliParams::Mode::MODE_GENERIC); PyModule_AddIntConstant(m, "MODE_TEXT", (int) BrotliParams::Mode::MODE_TEXT); PyModule_AddIntConstant(m, "MODE_FONT", (int) BrotliParams::Mode::MODE_FONT); RETURN_BROTLI; }
#define PY_SSIZE_T_CLEAN 1 #include <Python.h> #include <bytesobject.h> #include "../enc/encode.h" #include "../dec/decode.h" #if PY_MAJOR_VERSION >= 3 #define PyInt_Check PyLong_Check #define PyInt_AsLong PyLong_AsLong #endif using namespace brotli; static PyObject *BrotliError; static int mode_convertor(PyObject *o, BrotliParams::Mode *mode) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid mode"); return 0; } *mode = (BrotliParams::Mode) PyInt_AsLong(o); if (*mode != BrotliParams::Mode::MODE_GENERIC && *mode != BrotliParams::Mode::MODE_TEXT && *mode != BrotliParams::Mode::MODE_FONT) { PyErr_SetString(BrotliError, "Invalid mode"); return 0; } return 1; } static int quality_convertor(PyObject *o, int *quality) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid quality"); return 0; } *quality = PyInt_AsLong(o); if (*quality < 0 || *quality > 11) { PyErr_SetString(BrotliError, "Invalid quality. Range is 0 to 11."); return 0; } return 1; } static int lgwin_convertor(PyObject *o, int *lgwin) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid lgwin"); return 0; } *lgwin = PyInt_AsLong(o); if (*lgwin < 16 || *lgwin > 24) { PyErr_SetString(BrotliError, "Invalid lgwin. Range is 16 to 24."); return 0; } return 1; } static int lgblock_convertor(PyObject *o, int *lgblock) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid lgblock"); return 0; } *lgblock = PyInt_AsLong(o); if ((*lgblock != 0 && *lgblock < 16) || *lgblock > 24) { PyErr_SetString(BrotliError, "Invalid lgblock. Can be 0 or in range 16 to 24."); return 0; } return 1; } PyDoc_STRVAR(compress__doc__, "Compress a byte string.\n" "\n" "Signature:\n" " compress(string, mode=MODE_GENERIC, quality=11, lgwin=22, lgblock=0)\n" "\n" "Args:\n" " string (bytes): The input data.\n" " mode (int, optional): The compression mode can be MODE_GENERIC (default),\n" " MODE_TEXT (for UTF-8 format text input) or MODE_FONT (for WOFF 2.0). \n" " quality (int, optional): Controls the compression-speed vs compression-\n" " density tradeoff. The higher the quality, the slower the compression.\n" " Range is 0 to 11. Defaults to 11.\n" " lgwin (int, optional): Base 2 logarithm of the sliding window size. Range\n" " is 16 to 24. Defaults to 22.\n" " lgblock (int, optional): Base 2 logarithm of the maximum input block size.\n" " Range is 16 to 24. If set to 0, the value will be set based on the\n" " quality. Defaults to 0.\n" "\n" "Returns:\n" " The compressed byte string.\n" "\n" "Raises:\n" " brotli.error: If arguments are invalid, or compressor fails.\n"); static PyObject* brotli_compress(PyObject *self, PyObject *args, PyObject *keywds) { PyObject *ret = NULL; uint8_t *input, *output; size_t length, output_length; BrotliParams::Mode mode = (BrotliParams::Mode) -1; int quality = -1; int lgwin = -1; int lgblock = -1; int ok; static const char *kwlist[] = {"string", "mode", "quality", "lgwin", "lgblock"}; ok = PyArg_ParseTupleAndKeywords(args, keywds, "s#|O&O&O&O&:compress", const_cast<char **>(kwlist), &input, &length, &mode_convertor, &mode, &quality_convertor, &quality, &lgwin_convertor, &lgwin, &lgblock_convertor, &lgblock); if (!ok) return NULL; output_length = 1.2 * length + 10240; output = new uint8_t[output_length]; BrotliParams params; if (mode != -1) params.mode = mode; if (quality != -1) params.quality = quality; if (lgwin != -1) params.lgwin = lgwin; if (lgblock != -1) params.lgblock = lgblock; ok = BrotliCompressBuffer(params, length, input, &output_length, output); if (ok) { ret = PyBytes_FromStringAndSize((char*)output, output_length); } else { PyErr_SetString(BrotliError, "BrotliCompressBuffer failed"); } delete[] output; return ret; } int output_callback(void* data, const uint8_t* buf, size_t count) { std::vector<uint8_t> *output = (std::vector<uint8_t> *)data; output->insert(output->end(), buf, buf + count); return (int)count; } PyDoc_STRVAR(decompress__doc__, "Decompress a compressed byte string.\n" "\n" "Signature:\n" " decompress(string)\n" "\n" "Args:\n" " string (bytes): The compressed input data.\n" "\n" "Returns:\n" " The decompressed byte string.\n" "\n" "Raises:\n" " brotli.error: If decompressor fails.\n"); static PyObject* brotli_decompress(PyObject *self, PyObject *args) { PyObject *ret = NULL; uint8_t *input; size_t length; int ok; ok = PyArg_ParseTuple(args, "s#:decompress", &input, &length); if (!ok) return NULL; BrotliMemInput memin; BrotliInput in = BrotliInitMemInput(input, length, &memin); BrotliOutput out; std::vector<uint8_t> output; out.cb_ = &output_callback; out.data_ = &output; ok = BrotliDecompress(in, out); if (ok) { ret = PyBytes_FromStringAndSize((char*)output.data(), output.size()); } else { PyErr_SetString(BrotliError, "BrotliDecompress failed"); } return ret; } static PyMethodDef brotli_methods[] = { {"compress", (PyCFunction)brotli_compress, METH_VARARGS | METH_KEYWORDS, compress__doc__}, {"decompress", brotli_decompress, METH_VARARGS, decompress__doc__}, {NULL, NULL, 0, NULL} }; PyDoc_STRVAR(brotli__doc__, "The functions in this module allow compression and decompression using the\n" "Brotli library.\n\n"); #if PY_MAJOR_VERSION >= 3 #define INIT_BROTLI PyInit_brotli #define CREATE_BROTLI PyModule_Create(&brotli_module) #define RETURN_BROTLI return m static struct PyModuleDef brotli_module = { PyModuleDef_HEAD_INIT, "brotli", brotli__doc__, 0, brotli_methods, NULL, NULL, NULL }; #else #define INIT_BROTLI initbrotli #define CREATE_BROTLI Py_InitModule3("brotli", brotli_methods, brotli__doc__) #define RETURN_BROTLI return #endif PyMODINIT_FUNC INIT_BROTLI(void) { PyObject *m = CREATE_BROTLI; BrotliError = PyErr_NewException((char*) "brotli.error", NULL, NULL); if (BrotliError != NULL) { Py_INCREF(BrotliError); PyModule_AddObject(m, "error", BrotliError); } PyModule_AddIntConstant(m, "MODE_GENERIC", (int) BrotliParams::Mode::MODE_GENERIC); PyModule_AddIntConstant(m, "MODE_TEXT", (int) BrotliParams::Mode::MODE_TEXT); PyModule_AddIntConstant(m, "MODE_FONT", (int) BrotliParams::Mode::MODE_FONT); RETURN_BROTLI; }
fix C++11 warning about conversion from string literal to 'char *'
[brotlimodule.cc] fix C++11 warning about conversion from string literal to 'char *'
C++
mit
dragon788/brotli,smourier/brotli,fouzelddin/brotli,rayning0/brotli,Bulat-Ziganshin/brotli,fouzelddin/brotli,lukw00/brotli,IIoTeP9HuY/brotli,rafaelbc/brotli,leo237/brotli,carlhuting/brotli,rajathkumarmp/brotli,google/brotli,Abhikos/brotli,lzq8272587/brotli,jqk6/brotli,madhudskumar/brotli,cosmicwomp/brotli,ebiggers/brotli,zofuthan/brotli,erichub/brotli,google/brotli,karpinski/brotli,iamjbn/brotli,letup/brotli,emil-io/brotli,king-jw/brotli,windhorn/brotli,gk23/brotli,W3SS/brotli,rgordeev/brotli,silky/brotli,datachand/brotli,andrebellafronte/brotli,jqk6/brotli,koolhazz/brotli,erichub/brotli,abhishekgahlot/brotli,noname007/brotli,dwdm/brotli,fxfactorial/brotli,emil-io/brotli,zofuthan/brotli,daltonmaag/brotli,chrislucas/brotli,carlhuting/brotli,fouzelddin/brotli,iamjbn/brotli,anthrotype/brotli,fllsouto/brotli,fouzelddin/brotli,rajat1994/brotli,daltonmaag/brotli,zhaohuaw/brotli,hemel-cse/brotli,anthrotype/brotli,letup/brotli,karpinski/brotli,daltonmaag/brotli,sajith4u/brotli,CedarLogic/brotli,kaushik94/brotli,mk525/Code,ruo91/brotli,koolhazz/brotli,Abhikos/brotli,jacklicn/brotli,lzq8272587/brotli,smourier/brotli,josl/brotli,shilpi230/brotli,tml/brotli,samtechie/brotli,s0ne0me/brotli,ebiggers/brotli,panaroma/brotli,ya7lelkom/brotli,luzhongtong/brotli,mark2007081021/brotli,WenyuDeng/brotli,yonchev/brotli,gk23/brotli,stamhe/brotli,merckhung/brotli,Endika/brotli,FarhanHaque/brotli,rafaelbc/brotli,samtechie/brotli,caidongyun/brotli,johnnycastilho/brotli,google/brotli,datachand/brotli,archiveds/brotli,PritiKumr/brotli,lzq8272587/brotli,abhishekgahlot/brotli,rayning0/brotli,leo237/brotli,PritiKumr/brotli,mark2007081021/brotli,Mojang/brotli,Bulat-Ziganshin/brotli,rafaelbc/brotli,Endika/brotli,ebiggers/brotli,dragon788/brotli,koolhazz/brotli,king-jw/brotli,lukw00/brotli,madhudskumar/brotli,dwdm/brotli,hemel-cse/brotli,thurday/brotli,leo237/brotli,silky/brotli,zofuthan/brotli,datachand/brotli,luzhongtong/brotli,king-jw/brotli,thurday/brotli,archiveds/brotli,andrebellafronte/brotli,archiveds/brotli,rgordeev/brotli,letup/brotli,WenyuDeng/brotli,matsprea/brotli,anthrotype/brotli,erichub/brotli,fllsouto/brotli,CedarLogic/brotli,hemel-cse/brotli,ya7lelkom/brotli,mcanthony/brotli,madhudskumar/brotli,PritiKumr/brotli,bunnyblue/brotli,rasata/brotli,kaushik94/brotli,sonivaibhv/brotli,dwdm/brotli,anthrotype/brotli,szabadka/brotli,rajathkumarmp/brotli,panaroma/brotli,ruo91/brotli,mark2007081021/brotli,rajat1994/brotli,IIoTeP9HuY/brotli,shaunstanislaus/brotli,jqk6/brotli,abhishekgahlot/brotli,rajathkumarmp/brotli,eric-seekas/brotli,noname007/brotli,google/brotli,minhlongdo/brotli,shaunstanislaus/brotli,rasata/brotli,dwdm/brotli,rasata/brotli,Abhikos/brotli,rajat1994/brotli,josl/brotli,zhaohuaw/brotli,mcanthony/brotli,josl/brotli,shadowkun/brotli,yiliaofan/brotli,noname007/brotli,bunnyblue/brotli,IIoTeP9HuY/brotli,jqk6/brotli,eric-seekas/brotli,cosmicwomp/brotli,Bulat-Ziganshin/brotli,yonchev/brotli,fxfactorial/brotli,szabadka/brotli,lvandeve/brotli,silky/brotli,ruo91/brotli,merckhung/brotli,erichub/brotli,gk23/brotli,lvandeve/brotli,zofuthan/brotli,QuantumFractal/brotli,chrislucas/brotli,jacklicn/brotli,mark2007081021/brotli,chinanjjohn2012/brotli,kaushik94/brotli,luzhongtong/brotli,Endika/brotli,daltonmaag/brotli,kaushik94/brotli,hemel-cse/brotli,Merterm/brotli,Merterm/brotli,rajat1994/brotli,Merterm/brotli,lzq8272587/brotli,madhudskumar/brotli,minhlongdo/brotli,shilpi230/brotli,agordon/brotli,fxfactorial/brotli,rgordeev/brotli,fxfactorial/brotli,rafaelbc/brotli,luzhongtong/brotli,dragon788/brotli,shadowkun/brotli,ruo91/brotli,CedarLogic/brotli,nicksay/brotli,fllsouto/brotli,CedarLogic/brotli,rajathkumarmp/brotli,panaroma/brotli,cosmicwomp/brotli,thurday/brotli,lvandeve/brotli,tml/brotli,dragon788/brotli,shilpi230/brotli,caidongyun/brotli,hcxiong/brotli,iamjbn/brotli,shadowkun/brotli,chrislucas/brotli,archiveds/brotli,josl/brotli,nicksay/brotli,szabadka/brotli,jacklicn/brotli,google/brotli,W3SS/brotli,Mojang/brotli,sonivaibhv/brotli,carlhuting/brotli,anthrotype/brotli,nicksay/brotli,king-jw/brotli,rasata/brotli,sonivaibhv/brotli,sajith4u/brotli,hcxiong/brotli,Mojang/brotli,bunnyblue/brotli,Merterm/brotli,lvandeve/brotli,shadowkun/brotli,mk525/Code,zhaohuaw/brotli,letup/brotli,eric-seekas/brotli,QuantumFractal/brotli,chrislucas/brotli,yiliaofan/brotli,eric-seekas/brotli,Mojang/brotli,BuildAPE/brotli,fllsouto/brotli,ebiggers/brotli,nicksay/brotli,mk525/Code,yiliaofan/brotli,Abhikos/brotli,WenyuDeng/brotli,smourier/brotli,google/brotli,W3SS/brotli,silky/brotli,chinanjjohn2012/brotli,lukw00/brotli,BuildAPE/brotli,rayning0/brotli,matsprea/brotli,stamhe/brotli,merckhung/brotli,IIoTeP9HuY/brotli,abhishekgahlot/brotli,mk525/Code,sajith4u/brotli,szabadka/brotli,BuildAPE/brotli,WenyuDeng/brotli,noname007/brotli,caidongyun/brotli,Bulat-Ziganshin/brotli,gk23/brotli,stamhe/brotli,mcanthony/brotli,samtechie/brotli,ya7lelkom/brotli,chinanjjohn2012/brotli,QuantumFractal/brotli,nicksay/brotli,cosmicwomp/brotli,tml/brotli,QuantumFractal/brotli,andrebellafronte/brotli,emil-io/brotli,nicksay/brotli,carlhuting/brotli,agordon/brotli,shilpi230/brotli,smourier/brotli,lukw00/brotli,yonchev/brotli,bunnyblue/brotli,johnnycastilho/brotli,windhorn/brotli,mcanthony/brotli,shaunstanislaus/brotli,s0ne0me/brotli,tml/brotli,agordon/brotli,minhlongdo/brotli,nicksay/brotli,andrebellafronte/brotli,FarhanHaque/brotli,Endika/brotli,karpinski/brotli,emil-io/brotli,BuildAPE/brotli,jacklicn/brotli,FarhanHaque/brotli,FarhanHaque/brotli,samtechie/brotli,matsprea/brotli,johnnycastilho/brotli,s0ne0me/brotli,yiliaofan/brotli,panaroma/brotli,caidongyun/brotli,W3SS/brotli,rgordeev/brotli,minhlongdo/brotli,koolhazz/brotli,stamhe/brotli,hcxiong/brotli,windhorn/brotli,zhaohuaw/brotli,matsprea/brotli,agordon/brotli,kasper93/brotli,kasper93/brotli,chinanjjohn2012/brotli,s0ne0me/brotli,smourier/brotli,PritiKumr/brotli,datachand/brotli,google/brotli,sajith4u/brotli,google/brotli,johnnycastilho/brotli,yonchev/brotli,karpinski/brotli,rayning0/brotli,shaunstanislaus/brotli,iamjbn/brotli,sonivaibhv/brotli,windhorn/brotli,thurday/brotli,ya7lelkom/brotli,leo237/brotli,kasper93/brotli,hcxiong/brotli,kasper93/brotli,merckhung/brotli
078c55321908ca6e94fb1f8592119ba7c6b6f0df
core/src/oned/ODReader.cpp
core/src/oned/ODReader.cpp
/* * Copyright 2016 Nu-book Inc. * Copyright 2016 ZXing authors * * 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 "oned/ODReader.h" #include "oned/ODMultiUPCEANReader.h" #include "oned/ODCode39Reader.h" #include "oned/ODCode93Reader.h" #include "oned/ODCode128Reader.h" #include "oned/ODITFReader.h" #include "oned/ODCodabarReader.h" #include "oned/ODRSS14Reader.h" #include "oned/ODRSSExpandedReader.h" #include "Result.h" #include "BitArray.h" #include "BinaryBitmap.h" #include "DecodeHints.h" #include <unordered_set> #include <algorithm> namespace ZXing { namespace OneD { Reader::Reader(const DecodeHints& hints) : _tryHarder(hints.shouldTryHarder()), _tryRotate(hints.shouldTryRotate()) { _readers.reserve(8); auto possibleFormats = hints.possibleFormats(); std::unordered_set<BarcodeFormat, BarcodeFormatHasher> formats(possibleFormats.begin(), possibleFormats.end()); if (formats.empty()) { _readers.emplace_back(new MultiUPCEANReader(hints)); _readers.emplace_back(new Code39Reader(hints)); _readers.emplace_back(new CodabarReader(hints)); _readers.emplace_back(new Code93Reader()); _readers.emplace_back(new Code128Reader(hints)); _readers.emplace_back(new ITFReader(hints)); _readers.emplace_back(new RSS14Reader()); _readers.emplace_back(new RSSExpandedReader()); } else { if (formats.find(BarcodeFormat::EAN_13) != formats.end() || formats.find(BarcodeFormat::UPC_A) != formats.end() || formats.find(BarcodeFormat::EAN_8) != formats.end() || formats.find(BarcodeFormat::UPC_E) != formats.end()) { _readers.emplace_back(new MultiUPCEANReader(hints)); } if (formats.find(BarcodeFormat::CODE_39) != formats.end()) { _readers.emplace_back(new Code39Reader(hints)); } if (formats.find(BarcodeFormat::CODE_93) != formats.end()) { _readers.emplace_back(new Code93Reader()); } if (formats.find(BarcodeFormat::CODE_128) != formats.end()) { _readers.emplace_back(new Code128Reader(hints)); } if (formats.find(BarcodeFormat::ITF) != formats.end()) { _readers.emplace_back(new ITFReader(hints)); } if (formats.find(BarcodeFormat::CODABAR) != formats.end()) { _readers.emplace_back(new CodabarReader(hints)); } if (formats.find(BarcodeFormat::RSS_14) != formats.end()) { _readers.emplace_back(new RSS14Reader()); } if (formats.find(BarcodeFormat::RSS_EXPANDED) != formats.end()) { _readers.emplace_back(new RSSExpandedReader()); } } } Reader::~Reader() { } /** * We're going to examine rows from the middle outward, searching alternately above and below the * middle, and farther out each time. rowStep is the number of rows between each successive * attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then * middle + rowStep, then middle - (2 * rowStep), etc. * rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily * decided that moving up and down by about 1/16 of the image is pretty good; we try more of the * image if "trying harder". * * @param image The image to decode * @param hints Any hints that were requested * @return The contents of the decoded barcode * @throws NotFoundException Any spontaneous errors which occur */ static Result DoDecode(const std::vector<std::unique_ptr<RowReader>>& readers, const BinaryBitmap& image, bool tryHarder) { std::vector<std::unique_ptr<RowReader::DecodingState>> decodingState(readers.size()); int width = image.width(); int height = image.height(); int middle = height >> 1; int rowStep = std::max(1, height >> (tryHarder ? 8 : 5)); int maxLines = tryHarder ? height : // Look at the whole image, not just the center 15; // 15 rows spaced 1/32 apart is roughly the middle half of the image BitArray row(width); for (int x = 0; x < maxLines; x++) { // Scanning from the middle out. Determine which row we're looking at next: int rowStepsAboveOrBelow = (x + 1) / 2; bool isAbove = (x & 0x01) == 0; // i.e. is x even? int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow); if (rowNumber < 0 || rowNumber >= height) { // Oops, if we run off the top or bottom, stop break; } // Estimate black point for this row and load it: if (!image.getBlackRow(rowNumber, row)) { continue; } // While we have the image data in a BitArray, it's fairly cheap to reverse it in place to // handle decoding upside down barcodes. for (bool upsideDown : {false, true}) { // trying again? if (upsideDown) { // reverse the row and continue row.reverse(); } // Look for a barcode for (size_t r = 0; r < readers.size(); ++r) { Result result = readers[r]->decodeRow(rowNumber, row, decodingState[r]); if (result.isValid()) { // We found our barcode if (upsideDown) { // But it was upside down, so note that result.metadata().put(ResultMetadata::ORIENTATION, 180); // And remember to flip the result points horizontally. auto points = result.resultPoints(); for (auto& p : points) { p.set(width - p.x() - 1, p.y()); } result.setResultPoints(std::move(points)); } return result; } } } } return Result(DecodeStatus::NotFound); } // Note that we don't try rotation without the try harder flag, even if rotation was supported. Result Reader::decode(const BinaryBitmap& image) const { Result result = DoDecode(_readers, image, _tryHarder); if (result.isValid()) { return result; } if (_tryRotate && image.canRotate()) { auto rotatedImage = image.rotated(270); result = DoDecode(_readers, *rotatedImage, _tryHarder); if (result.isValid()) { // Record that we found it rotated 90 degrees CCW / 270 degrees CW auto& metadata = result.metadata(); metadata.put(ResultMetadata::ORIENTATION, (270 + metadata.getInt(ResultMetadata::ORIENTATION)) % 360); // Update result points auto points = result.resultPoints(); int height = rotatedImage->height(); for (auto& p : points) { p.set(height - p.y() - 1, p.x()); } result.setResultPoints(std::move(points)); } } return result; } } // OneD } // ZXing
/* * Copyright 2016 Nu-book Inc. * Copyright 2016 ZXing authors * * 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 "oned/ODReader.h" #include "oned/ODMultiUPCEANReader.h" #include "oned/ODCode39Reader.h" #include "oned/ODCode93Reader.h" #include "oned/ODCode128Reader.h" #include "oned/ODITFReader.h" #include "oned/ODCodabarReader.h" #include "oned/ODRSS14Reader.h" #include "oned/ODRSSExpandedReader.h" #include "Result.h" #include "BitArray.h" #include "BinaryBitmap.h" #include "DecodeHints.h" #include <unordered_set> #include <algorithm> namespace ZXing { namespace OneD { Reader::Reader(const DecodeHints& hints) : _tryHarder(hints.shouldTryHarder()), _tryRotate(hints.shouldTryRotate()) { _readers.reserve(8); auto possibleFormats = hints.possibleFormats(); std::unordered_set<BarcodeFormat, BarcodeFormatHasher> formats(possibleFormats.begin(), possibleFormats.end()); if (formats.empty()) { _readers.emplace_back(new MultiUPCEANReader(hints)); _readers.emplace_back(new Code39Reader(hints)); _readers.emplace_back(new CodabarReader(hints)); _readers.emplace_back(new Code93Reader()); _readers.emplace_back(new Code128Reader(hints)); _readers.emplace_back(new ITFReader(hints)); _readers.emplace_back(new RSS14Reader()); _readers.emplace_back(new RSSExpandedReader()); } else { if (formats.find(BarcodeFormat::EAN_13) != formats.end() || formats.find(BarcodeFormat::UPC_A) != formats.end() || formats.find(BarcodeFormat::EAN_8) != formats.end() || formats.find(BarcodeFormat::UPC_E) != formats.end()) { _readers.emplace_back(new MultiUPCEANReader(hints)); } if (formats.find(BarcodeFormat::CODE_39) != formats.end()) { _readers.emplace_back(new Code39Reader(hints)); } if (formats.find(BarcodeFormat::CODE_93) != formats.end()) { _readers.emplace_back(new Code93Reader()); } if (formats.find(BarcodeFormat::CODE_128) != formats.end()) { _readers.emplace_back(new Code128Reader(hints)); } if (formats.find(BarcodeFormat::ITF) != formats.end()) { _readers.emplace_back(new ITFReader(hints)); } if (formats.find(BarcodeFormat::CODABAR) != formats.end()) { _readers.emplace_back(new CodabarReader(hints)); } if (formats.find(BarcodeFormat::RSS_14) != formats.end()) { _readers.emplace_back(new RSS14Reader()); } if (formats.find(BarcodeFormat::RSS_EXPANDED) != formats.end()) { _readers.emplace_back(new RSSExpandedReader()); } } } Reader::~Reader() { } /** * We're going to examine rows from the middle outward, searching alternately above and below the * middle, and farther out each time. rowStep is the number of rows between each successive * attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then * middle + rowStep, then middle - (2 * rowStep), etc. * rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily * decided that moving up and down by about 1/16 of the image is pretty good; we try more of the * image if "trying harder". * * @param image The image to decode * @param hints Any hints that were requested * @return The contents of the decoded barcode * @throws NotFoundException Any spontaneous errors which occur */ static Result DoDecode(const std::vector<std::unique_ptr<RowReader>>& readers, const BinaryBitmap& image, bool tryHarder) { std::vector<std::unique_ptr<RowReader::DecodingState>> decodingState(readers.size()); int width = image.width(); int height = image.height(); int middle = height >> 1; int rowStep = std::max(1, height >> (tryHarder ? 8 : 5)); int maxLines = tryHarder ? height : // Look at the whole image, not just the center 15; // 15 rows spaced 1/32 apart is roughly the middle half of the image BitArray row(width); for (int x = 0; x < maxLines; x++) { // Scanning from the middle out. Determine which row we're looking at next: int rowStepsAboveOrBelow = (x + 1) / 2; bool isAbove = (x & 0x01) == 0; // i.e. is x even? int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow); if (rowNumber < 0 || rowNumber >= height) { // Oops, if we run off the top or bottom, stop break; } // Estimate black point for this row and load it: if (!image.getBlackRow(rowNumber, row)) { continue; } // While we have the image data in a BitArray, it's fairly cheap to reverse it in place to // handle decoding upside down barcodes. // Note: the RSSExpanded decoder depends on seeing each line from both directions. This // 'surprising' and inconsistent. It also requires the decoderState to be shared between // normal and reversed scans, which makes no sense in general because it would mix partial // detetection data from two codes of the same type next to each other. TODO.. // See also https://github.com/nu-book/zxing-cpp/issues/87 for (bool upsideDown : {false, true}) { // trying again? if (upsideDown) { // reverse the row and continue row.reverse(); } // Look for a barcode for (size_t r = 0; r < readers.size(); ++r) { Result result = readers[r]->decodeRow(rowNumber, row, decodingState[r]); if (result.isValid()) { // We found our barcode if (upsideDown) { // But it was upside down, so note that result.metadata().put(ResultMetadata::ORIENTATION, 180); // And remember to flip the result points horizontally. auto points = result.resultPoints(); for (auto& p : points) { p.set(width - p.x() - 1, p.y()); } result.setResultPoints(std::move(points)); } return result; } } } } return Result(DecodeStatus::NotFound); } // Note that we don't try rotation without the try harder flag, even if rotation was supported. Result Reader::decode(const BinaryBitmap& image) const { Result result = DoDecode(_readers, image, _tryHarder); if (result.isValid()) { return result; } if (_tryRotate && image.canRotate()) { auto rotatedImage = image.rotated(270); result = DoDecode(_readers, *rotatedImage, _tryHarder); if (result.isValid()) { // Record that we found it rotated 90 degrees CCW / 270 degrees CW auto& metadata = result.metadata(); metadata.put(ResultMetadata::ORIENTATION, (270 + metadata.getInt(ResultMetadata::ORIENTATION)) % 360); // Update result points auto points = result.resultPoints(); int height = rotatedImage->height(); for (auto& p : points) { p.set(height - p.y() - 1, p.x()); } result.setResultPoints(std::move(points)); } } return result; } } // OneD } // ZXing
add comment about upsideDown/RSSExpanded/DecoderState
add comment about upsideDown/RSSExpanded/DecoderState See also #87.
C++
apache-2.0
huycn/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp
6182c032c7e42ec8d78ee566a1058d960b13ff3f
engine/plugins/soundfile_api_libsndfile.cpp
engine/plugins/soundfile_api_libsndfile.cpp
// Copyright 2013 Samplecount S.L. // // 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 <methcla/plugins/soundfile_api_libsndfile.h> // #include "Log.hpp" #include <iostream> #include <memory> #include <random> #include <cassert> #include <cstdlib> #include <sndfile.h> struct SoundFileHandle { SNDFILE* sndfile; Methcla_SoundFile soundFile; }; extern "C" { static Methcla_Error soundfile_close(const Methcla_SoundFile*); static Methcla_Error soundfile_seek(const Methcla_SoundFile*, int64_t); static Methcla_Error soundfile_tell(const Methcla_SoundFile*, int64_t*); static Methcla_Error soundfile_read_float(const Methcla_SoundFile*, float*, size_t, size_t*); static Methcla_Error soundfile_open(const Methcla_SoundFileAPI*, const char*, Methcla_FileMode, Methcla_SoundFile**, Methcla_SoundFileInfo*); static const Methcla_SystemError* soundfile_last_system_error(const Methcla_SoundFileAPI*); static const char* soundfile_system_error_description(const Methcla_SystemError*); static void soundfile_system_error_destroy(const Methcla_SystemError*); } // extern "C" static Methcla_Error soundfile_close(const Methcla_SoundFile* file) { SoundFileHandle* handle = static_cast<SoundFileHandle*>(file->handle); sf_close(handle->sndfile); free(handle); return kMethcla_NoError; } static Methcla_Error soundfile_seek(const Methcla_SoundFile* file, int64_t numFrames) { SoundFileHandle* handle = static_cast<SoundFileHandle*>(file->handle); sf_count_t n = sf_seek(handle->sndfile, static_cast<sf_count_t>(numFrames), SEEK_SET); return n >= 0 ? kMethcla_NoError : kMethcla_UnspecifiedError; } static Methcla_Error soundfile_tell(const Methcla_SoundFile* file, int64_t* numFrames) { SoundFileHandle* handle = static_cast<SoundFileHandle*>(file->handle); sf_count_t n = sf_seek(handle->sndfile, 0, SEEK_CUR); if (n < 0) return kMethcla_UnspecifiedError; *numFrames = static_cast<int64_t>(n); return kMethcla_NoError; } static Methcla_Error soundfile_read_float(const Methcla_SoundFile* file, float* buffer, size_t inNumFrames, size_t* outNumFrames) { SoundFileHandle* handle = static_cast<SoundFileHandle*>(file->handle); sf_count_t n = sf_readf_float(handle->sndfile, buffer, inNumFrames); if (n < 0) return kMethcla_UnspecifiedError; assert(n <= (sf_count_t)inNumFrames); *outNumFrames = n; return kMethcla_NoError; } static bool convertMode(Methcla_FileMode mode, int* outMode) { switch (mode) { case kMethcla_Read: *outMode = SFM_READ; return true; case kMethcla_Write: *outMode = SFM_WRITE; return true; case kMethcla_ReadWrite: *outMode = SFM_RDWR; return true; } return true; } static Methcla_Error soundfile_open(const Methcla_SoundFileAPI* api, const char* path, Methcla_FileMode mode, Methcla_SoundFile** outFile, Methcla_SoundFileInfo* info) { if (path == nullptr) return kMethcla_ArgumentError; if (outFile == nullptr) return kMethcla_ArgumentError; int sfmode; if (!convertMode(mode, &sfmode)) return kMethcla_ArgumentError; SoundFileHandle* handle = static_cast<SoundFileHandle*>(std::malloc(sizeof(SoundFileHandle))); if (handle == nullptr) { return kMethcla_UnspecifiedError; } SF_INFO sfinfo; handle->sndfile = sf_open(path, sfmode, &sfinfo); if (handle->sndfile == nullptr) return kMethcla_UnspecifiedError; Methcla_SoundFile* file = &handle->soundFile; memset(file, 0, sizeof(*file)); file->handle = handle; file->close = soundfile_close; file->seek = soundfile_seek; file->tell = soundfile_tell; file->read_float = soundfile_read_float; *outFile = file; if (info != nullptr) { info->frames = sfinfo.frames; info->channels = std::abs(sfinfo.channels); info->samplerate = std::abs(sfinfo.samplerate); } // METHCLA_PRINT_DEBUG("soundfile_open: %s %lld %u %u", path, info->frames, info->channels, info->samplerate); return kMethcla_NoError; } static const char* soundfile_system_error_description(const Methcla_SystemError* error) { return "Unknown system error (ExtAudioFile)"; } static void soundfile_system_error_destroy(const Methcla_SystemError* error) { delete error; } static const Methcla_SystemError* soundfile_last_system_error(const Methcla_SoundFileAPI* api) { Methcla_SystemError* error = new (std::nothrow) Methcla_SystemError; if (error) { error->handle = nullptr; error->description = soundfile_system_error_description; error->destroy = soundfile_system_error_destroy; } return error; } static const Methcla_SoundFileAPI kSoundFileAPI = { nullptr, soundfile_open, soundfile_last_system_error }; static const Methcla_SoundFileAPI kSoundFileAPI = { nullptr, soundfile_open, soundfile_last_system_error }; METHCLA_EXPORT const Methcla_Library* methcla_soundfile_api_libsndfile(const Methcla_Host* host, const char*) { methcla_host_register_soundfile_api(host, &kSoundFileAPI); return nullptr; }
// Copyright 2013 Samplecount S.L. // // 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 <methcla/plugins/soundfile_api_libsndfile.h> // #include "Log.hpp" #include <iostream> #include <memory> #include <random> #include <cassert> #include <cstdlib> #include <sndfile.h> struct SoundFileHandle { SNDFILE* sndfile; Methcla_SoundFile soundFile; }; extern "C" { static Methcla_Error soundfile_close(const Methcla_SoundFile*); static Methcla_Error soundfile_seek(const Methcla_SoundFile*, int64_t); static Methcla_Error soundfile_tell(const Methcla_SoundFile*, int64_t*); static Methcla_Error soundfile_read_float(const Methcla_SoundFile*, float*, size_t, size_t*); static Methcla_Error soundfile_open(const Methcla_SoundFileAPI*, const char*, Methcla_FileMode, Methcla_SoundFile**, Methcla_SoundFileInfo*); static const Methcla_SystemError* soundfile_last_system_error(const Methcla_SoundFileAPI*); static const char* soundfile_system_error_description(const Methcla_SystemError*); static void soundfile_system_error_destroy(const Methcla_SystemError*); } // extern "C" static Methcla_Error soundfile_close(const Methcla_SoundFile* file) { SoundFileHandle* handle = static_cast<SoundFileHandle*>(file->handle); sf_close(handle->sndfile); free(handle); return kMethcla_NoError; } static Methcla_Error soundfile_seek(const Methcla_SoundFile* file, int64_t numFrames) { SoundFileHandle* handle = static_cast<SoundFileHandle*>(file->handle); sf_count_t n = sf_seek(handle->sndfile, static_cast<sf_count_t>(numFrames), SEEK_SET); return n >= 0 ? kMethcla_NoError : kMethcla_UnspecifiedError; } static Methcla_Error soundfile_tell(const Methcla_SoundFile* file, int64_t* numFrames) { SoundFileHandle* handle = static_cast<SoundFileHandle*>(file->handle); sf_count_t n = sf_seek(handle->sndfile, 0, SEEK_CUR); if (n < 0) return kMethcla_UnspecifiedError; *numFrames = static_cast<int64_t>(n); return kMethcla_NoError; } static Methcla_Error soundfile_read_float(const Methcla_SoundFile* file, float* buffer, size_t inNumFrames, size_t* outNumFrames) { SoundFileHandle* handle = static_cast<SoundFileHandle*>(file->handle); sf_count_t n = sf_readf_float(handle->sndfile, buffer, inNumFrames); if (n < 0) return kMethcla_UnspecifiedError; assert(n <= (sf_count_t)inNumFrames); *outNumFrames = n; return kMethcla_NoError; } static bool convertMode(Methcla_FileMode mode, int* outMode) { switch (mode) { case kMethcla_FileModeRead: *outMode = SFM_READ; return true; case kMethcla_FileModeWrite: *outMode = SFM_WRITE; return true; } return true; } static Methcla_Error soundfile_open(const Methcla_SoundFileAPI*, const char* path, Methcla_FileMode mode, Methcla_SoundFile** outFile, Methcla_SoundFileInfo* info) { if (path == nullptr) return kMethcla_ArgumentError; if (outFile == nullptr) return kMethcla_ArgumentError; int sfmode; if (!convertMode(mode, &sfmode)) return kMethcla_ArgumentError; SoundFileHandle* handle = static_cast<SoundFileHandle*>(std::malloc(sizeof(SoundFileHandle))); if (handle == nullptr) { return kMethcla_UnspecifiedError; } SF_INFO sfinfo; handle->sndfile = sf_open(path, sfmode, &sfinfo); if (handle->sndfile == nullptr) return kMethcla_UnspecifiedError; Methcla_SoundFile* file = &handle->soundFile; memset(file, 0, sizeof(*file)); file->handle = handle; file->close = soundfile_close; file->seek = soundfile_seek; file->tell = soundfile_tell; file->read_float = soundfile_read_float; *outFile = file; if (info != nullptr) { info->frames = sfinfo.frames; info->channels = std::abs(sfinfo.channels); info->samplerate = std::abs(sfinfo.samplerate); } // METHCLA_PRINT_DEBUG("soundfile_open: %s %lld %u %u", path, info->frames, info->channels, info->samplerate); return kMethcla_NoError; } static const char* soundfile_system_error_description(const Methcla_SystemError*) { return "Unknown system error (ExtAudioFile)"; } static void soundfile_system_error_destroy(const Methcla_SystemError* error) { delete error; } static const Methcla_SystemError* soundfile_last_system_error(const Methcla_SoundFileAPI*) { Methcla_SystemError* error = new (std::nothrow) Methcla_SystemError; if (error) { error->handle = nullptr; error->description = soundfile_system_error_description; error->destroy = soundfile_system_error_destroy; } return error; } static const Methcla_SoundFileAPI kSoundFileAPI = { nullptr, soundfile_open, soundfile_last_system_error }; METHCLA_EXPORT const Methcla_Library* methcla_soundfile_api_libsndfile(const Methcla_Host* host, const char*) { methcla_host_register_soundfile_api(host, &kSoundFileAPI); return nullptr; }
Fix compilation errors
Fix compilation errors
C++
apache-2.0
samplecount/methcla,samplecount/methcla,samplecount/methcla,samplecount/methcla,samplecount/methcla,samplecount/methcla
c549965a159e8bb06794d5043782c37453504477
engine/core/linux/NativeWindowLinux.cpp
engine/core/linux/NativeWindowLinux.cpp
// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #include "../Setup.h" #include <stdexcept> #include <X11/extensions/Xrandr.h> #include "NativeWindowLinux.hpp" #include "EngineLinux.hpp" #if OUZEL_SUPPORTS_X11 namespace { constexpr long NET_WM_STATE_REMOVE = 0L; constexpr long NET_WM_STATE_ADD = 1L; constexpr long NET_WM_STATE_TOGGLE = 2L; } #endif namespace ouzel::core::linux { NativeWindow::NativeWindow(const std::function<void(const Event&)>& initCallback, const Size2U& newSize, bool newResizable, bool newFullscreen, bool newExclusiveFullscreen, const std::string& newTitle): core::NativeWindow(initCallback, newSize, newResizable, newFullscreen, newExclusiveFullscreen, newTitle, true) { #if OUZEL_SUPPORTS_X11 const auto engineLinux = static_cast<Engine*>(engine); display = engineLinux->getDisplay(); const auto screen = XDefaultScreenOfDisplay(display); screenNumber = XScreenNumberOfScreen(screen); const auto rootWindow = RootWindow(display, screenNumber); int monitorCount; XRRMonitorInfo* monitors = XRRGetMonitors(display, rootWindow, True, &monitorCount); std::unique_ptr<XRRMonitorInfo, decltype(&XRRFreeMonitors)> monitorsPtr(monitors, XRRFreeMonitors); XRRMonitorInfo* primaryMonitor = (monitorCount > 0) ? &monitors[0] : nullptr; for (int i = 0; i < monitorCount; ++i) if (monitors[i].primary) { primaryMonitor = &monitors[i]; break; } constexpr std::uint32_t defaultWidth = 800U; constexpr std::uint32_t defaultHeight = 600U; if (size.v[0] <= 0.0F) size.v[0] = primaryMonitor ? static_cast<std::uint32_t>(primaryMonitor->width * 0.8F) : defaultWidth; if (size.v[1] <= 0.0F) size.v[1] = primaryMonitor ? static_cast<std::uint32_t>(primaryMonitor->height * 0.8F) : defaultHeight; resolution = size; const int x = primaryMonitor ? monitors[0].x + primaryMonitor->width / 2 - static_cast<int>(size.v[0] / 2) : 0; const int y = primaryMonitor ? monitors[0].y + primaryMonitor->height / 2 - static_cast<int>(size.v[1] / 2) : 0; XSetWindowAttributes attributes; attributes.background_pixel = XWhitePixel(display, screenNumber); attributes.border_pixel = 0; attributes.event_mask = FocusChangeMask | KeyPressMask | KeyRelease | ExposureMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask; window = XCreateWindow(display, rootWindow, x, y, static_cast<unsigned int>(size.v[0]), static_cast<unsigned int>(size.v[1]), 0, DefaultDepth(display, screenNumber), InputOutput, DefaultVisual(display, screenNumber), CWBorderPixel | CWBackPixel | CWEventMask, &attributes); if (!XSetStandardProperties(display, window, title.c_str(), title.c_str(), None, nullptr, 0, nullptr)) throw std::system_error(getLastError(), errorCategory, "Failed to set window properties"); if (!resizable) { XSizeHints sizeHints; sizeHints.flags = PPosition | PMinSize | PMaxSize; sizeHints.x = x; sizeHints.y = y; sizeHints.min_width = static_cast<int>(size.v[0]); sizeHints.max_width = static_cast<int>(size.v[0]); sizeHints.min_height = static_cast<int>(size.v[1]); sizeHints.max_height = static_cast<int>(size.v[1]); XSetWMNormalHints(display, window, &sizeHints); } else { XSizeHints sizeHints; sizeHints.flags = PPosition; sizeHints.x = x; sizeHints.y = y; XSetWMNormalHints(display, window, &sizeHints); } if (!XMapWindow(display, window)) throw std::system_error(getLastError(), errorCategory, "Failed to map window"); protocolsAtom = XInternAtom(display, "WM_PROTOCOLS", False); deleteAtom = XInternAtom(display, "WM_DELETE_WINDOW", False); XSetWMProtocols(display, window, &deleteAtom, 1); stateAtom = XInternAtom(display, "_NET_WM_STATE", False); if (!stateAtom) throw std::system_error(getLastError(), errorCategory, "State atom is null"); stateFullscreenAtom = XInternAtom(display, "_NET_WM_STATE_FULLSCREEN", False); if (!stateFullscreenAtom) throw std::system_error(getLastError(), errorCategory, "Fullscreen state atom is null"); activateWindowAtom = XInternAtom(display, "_NET_ACTIVE_WINDOW", False); if (fullscreen) { XEvent event; event.type = ClientMessage; event.xclient.window = window; event.xclient.message_type = stateAtom; event.xclient.format = 32; event.xclient.data.l[0] = NET_WM_STATE_ADD; event.xclient.data.l[1] = stateFullscreenAtom; event.xclient.data.l[2] = 0; // no second property to toggle event.xclient.data.l[3] = 1; // source indication: application event.xclient.data.l[4] = 0; // unused if (!XSendEvent(display, DefaultRootWindow(display), 0, SubstructureNotifyMask | SubstructureRedirectMask, &event)) throw std::system_error(getLastError(), errorCategory, "Failed to send X11 fullscreen message"); } #elif OUZEL_SUPPORTS_DISPMANX auto engineLinux = static_cast<Engine*>(engine); auto display = engineLinux->getDisplay(); DISPMANX_MODEINFO_T modeInfo; const std::int32_t success = vc_dispmanx_display_get_info(display, &modeInfo); if (success < 0) throw std::runtime_error("Failed to get display size"); VC_RECT_T dstRect; dstRect.x = 0; dstRect.y = 0; dstRect.width = modeInfo.width; dstRect.height = modeInfo.height; VC_RECT_T srcRect; srcRect.x = 0; srcRect.y = 0; srcRect.width = modeInfo.width; srcRect.height = modeInfo.height; DISPMANX_UPDATE_HANDLE_T dispmanUpdate = vc_dispmanx_update_start(0); if (dispmanUpdate == DISPMANX_NO_HANDLE) throw std::runtime_error("Failed to start display update"); DISPMANX_ELEMENT_HANDLE_T dispmanElement = vc_dispmanx_element_add(dispmanUpdate, display, 0, &dstRect, 0, &srcRect, DISPMANX_PROTECTION_NONE, 0, 0, DISPMANX_NO_ROTATE); if (dispmanElement == DISPMANX_NO_HANDLE) throw std::runtime_error("Failed to add display element"); window.element = dispmanElement; window.width = modeInfo.width; window.height = modeInfo.height; vc_dispmanx_update_submit_sync(dispmanUpdate); size.v[0] = static_cast<std::uint32_t>(modeInfo.width); size.v[1] = static_cast<std::uint32_t>(modeInfo.height); resolution = size; #endif } NativeWindow::~NativeWindow() { #if OUZEL_SUPPORTS_X11 if (display && window) XDestroyWindow(display, window); #endif } void NativeWindow::executeCommand(const Command& command) { switch (command.type) { case Command::Type::changeSize: setSize(command.size); break; case Command::Type::changeFullscreen: setFullscreen(command.fullscreen); break; case Command::Type::close: close(); break; case Command::Type::setTitle: setTitle(command.title); break; case Command::Type::bringToFront: bringToFront(); break; case Command::Type::show: show(); break; case Command::Type::hide: hide(); break; case Command::Type::minimize: minimize(); break; case Command::Type::maximize: maximize(); break; case Command::Type::restore: restore(); break; default: throw std::runtime_error("Invalid command"); } } void NativeWindow::close() { #if OUZEL_SUPPORTS_X11 if (!protocolsAtom || !deleteAtom) return; XEvent event; event.type = ClientMessage; event.xclient.window = window; event.xclient.message_type = protocolsAtom; event.xclient.format = 32; // data is set as 32-bit integers event.xclient.data.l[0] = deleteAtom; event.xclient.data.l[1] = CurrentTime; event.xclient.data.l[2] = 0; // unused event.xclient.data.l[3] = 0; // unused event.xclient.data.l[4] = 0; // unused if (!XSendEvent(display, window, False, NoEventMask, &event)) throw std::system_error(getLastError(), errorCategory, "Failed to send X11 delete message"); #endif } void NativeWindow::setSize(const Size2U& newSize) { size = newSize; #if OUZEL_SUPPORTS_X11 XWindowChanges changes; changes.width = static_cast<int>(size.v[0]); changes.height = static_cast<int>(size.v[1]); XConfigureWindow(display, window, CWWidth | CWHeight, &changes); if (!resizable) { XSizeHints sizeHints; sizeHints.flags = PMinSize | PMaxSize; sizeHints.min_width = static_cast<int>(size.v[0]); sizeHints.max_width = static_cast<int>(size.v[0]); sizeHints.min_height = static_cast<int>(size.v[1]); sizeHints.max_height = static_cast<int>(size.v[1]); XSetWMNormalHints(display, window, &sizeHints); } resolution = size; Event resolutionChangeEvent(Event::Type::resolutionChange); resolutionChangeEvent.size = resolution; sendEvent(resolutionChangeEvent); #endif } void NativeWindow::setFullscreen(bool newFullscreen) { #if OUZEL_SUPPORTS_X11 if (fullscreen != newFullscreen) { XEvent event; event.type = ClientMessage; event.xclient.window = window; event.xclient.message_type = stateAtom; event.xclient.format = 32; event.xclient.data.l[0] = newFullscreen ? NET_WM_STATE_ADD : NET_WM_STATE_REMOVE; event.xclient.data.l[1] = stateFullscreenAtom; event.xclient.data.l[2] = 0; // no second property to toggle event.xclient.data.l[3] = 1; // source indication: application event.xclient.data.l[4] = 0; // unused if (!XSendEvent(display, DefaultRootWindow(display), 0, SubstructureNotifyMask | SubstructureRedirectMask, &event)) throw std::system_error(getLastError(), errorCategory, "Failed to send X11 fullscreen message"); } #endif fullscreen = newFullscreen; } void NativeWindow::setTitle(const std::string& newTitle) { #if OUZEL_SUPPORTS_X11 if (title != newTitle) XStoreName(display, window, newTitle.c_str()); #endif title = newTitle; } void NativeWindow::bringToFront() { #if OUZEL_SUPPORTS_X11 XRaiseWindow(display, window); XEvent event; event.type = ClientMessage; event.xclient.window = window; event.xclient.message_type = activateWindowAtom; event.xclient.format = 32; event.xclient.data.l[0] = 1; // source indication: application event.xclient.data.l[1] = CurrentTime; event.xclient.data.l[2] = 0; if (!XSendEvent(display, DefaultRootWindow(display), 0, SubstructureNotifyMask | SubstructureRedirectMask, &event)) throw std::system_error(getLastError(), errorCategory, "Failed to send X11 activate window message"); XFlush(display); #endif } void NativeWindow::show() { #if OUZEL_SUPPORTS_X11 if (!isMapped()) { XMapRaised(display, window); XFlush(display); } #endif } void NativeWindow::hide() { #if OUZEL_SUPPORTS_X11 if (isMapped()) { XWithdrawWindow(display, window, screenNumber); XFlush(display); } #endif } void NativeWindow::minimize() { #if OUZEL_SUPPORTS_X11 XIconifyWindow(display, window, screenNumber); XFlush(display); #endif } void NativeWindow::maximize() { } void NativeWindow::restore() { #if OUZEL_SUPPORTS_X11 XRaiseWindow(display, window); XEvent event; event.type = ClientMessage; event.xclient.window = window; event.xclient.message_type = activateWindowAtom; event.xclient.format = 32; event.xclient.data.l[0] = 1; // source indication: application event.xclient.data.l[1] = CurrentTime; event.xclient.data.l[2] = 0; if (!XSendEvent(display, DefaultRootWindow(display), 0, SubstructureNotifyMask | SubstructureRedirectMask, &event)) throw std::system_error(getLastError(), errorCategory, "Failed to send X11 activate window message"); XFlush(display); #endif } #if OUZEL_SUPPORTS_X11 void NativeWindow::handleFocusIn() { Event focusChangeEvent(Event::Type::focusChange); focusChangeEvent.focus = true; sendEvent(focusChangeEvent); } void NativeWindow::handleFocusOut() { Event focusChangeEvent(Event::Type::focusChange); focusChangeEvent.focus = false; sendEvent(focusChangeEvent); } void NativeWindow::handleResize(const Size2U& newSize) { size = newSize; resolution = size; Event sizeChangeEvent(Event::Type::sizeChange); sizeChangeEvent.size = size; sendEvent(sizeChangeEvent); Event resolutionChangeEvent(Event::Type::resolutionChange); resolutionChangeEvent.size = resolution; sendEvent(resolutionChangeEvent); } void NativeWindow::handleMap() { sendEvent(Event(Event::Type::restore)); } void NativeWindow::handleUnmap() { sendEvent(Event(Event::Type::minimize)); } bool NativeWindow::isMapped() const { XWindowAttributes attributes; XGetWindowAttributes(display, window, &attributes); return attributes.map_state != IsUnmapped; } #endif }
// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #include "../Setup.h" #include <stdexcept> #include <X11/extensions/Xrandr.h> #include "NativeWindowLinux.hpp" #include "EngineLinux.hpp" #if OUZEL_SUPPORTS_X11 namespace { constexpr long NET_WM_STATE_REMOVE = 0L; constexpr long NET_WM_STATE_ADD = 1L; constexpr long NET_WM_STATE_TOGGLE = 2L; } #endif namespace ouzel::core::linux { NativeWindow::NativeWindow(const std::function<void(const Event&)>& initCallback, const Size2U& newSize, bool newResizable, bool newFullscreen, bool newExclusiveFullscreen, const std::string& newTitle): core::NativeWindow(initCallback, newSize, newResizable, newFullscreen, newExclusiveFullscreen, newTitle, true) { #if OUZEL_SUPPORTS_X11 const auto engineLinux = static_cast<Engine*>(engine); display = engineLinux->getDisplay(); const auto screen = XDefaultScreenOfDisplay(display); screenNumber = XScreenNumberOfScreen(screen); const auto rootWindow = RootWindow(display, screenNumber); int monitorCount; std::unique_ptr<XRRMonitorInfo, decltype(&XRRFreeMonitors)> monitors(XRRGetMonitors(display, rootWindow, True, &monitorCount), XRRFreeMonitors); XRRMonitorInfo* primaryMonitor = (monitorCount > 0) ? &monitors.get()[0] : nullptr; for (int i = 0; i < monitorCount; ++i) if (monitors.get()[i].primary) { primaryMonitor = &monitors.get()[i]; break; } constexpr std::uint32_t defaultWidth = 800U; constexpr std::uint32_t defaultHeight = 600U; if (size.v[0] <= 0.0F) size.v[0] = primaryMonitor ? static_cast<std::uint32_t>(primaryMonitor->width * 0.8F) : defaultWidth; if (size.v[1] <= 0.0F) size.v[1] = primaryMonitor ? static_cast<std::uint32_t>(primaryMonitor->height * 0.8F) : defaultHeight; resolution = size; const int x = primaryMonitor ? primaryMonitor->x + primaryMonitor->width / 2 - static_cast<int>(size.v[0] / 2) : 0; const int y = primaryMonitor ? primaryMonitor->y + primaryMonitor->height / 2 - static_cast<int>(size.v[1] / 2) : 0; XSetWindowAttributes attributes; attributes.background_pixel = XWhitePixel(display, screenNumber); attributes.border_pixel = 0; attributes.event_mask = FocusChangeMask | KeyPressMask | KeyRelease | ExposureMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask; window = XCreateWindow(display, rootWindow, x, y, static_cast<unsigned int>(size.v[0]), static_cast<unsigned int>(size.v[1]), 0, DefaultDepth(display, screenNumber), InputOutput, DefaultVisual(display, screenNumber), CWBorderPixel | CWBackPixel | CWEventMask, &attributes); if (!XSetStandardProperties(display, window, title.c_str(), title.c_str(), None, nullptr, 0, nullptr)) throw std::system_error(getLastError(), errorCategory, "Failed to set window properties"); if (!resizable) { XSizeHints sizeHints; sizeHints.flags = PPosition | PMinSize | PMaxSize; sizeHints.x = x; sizeHints.y = y; sizeHints.min_width = static_cast<int>(size.v[0]); sizeHints.max_width = static_cast<int>(size.v[0]); sizeHints.min_height = static_cast<int>(size.v[1]); sizeHints.max_height = static_cast<int>(size.v[1]); XSetWMNormalHints(display, window, &sizeHints); } else { XSizeHints sizeHints; sizeHints.flags = PPosition; sizeHints.x = x; sizeHints.y = y; XSetWMNormalHints(display, window, &sizeHints); } if (!XMapWindow(display, window)) throw std::system_error(getLastError(), errorCategory, "Failed to map window"); protocolsAtom = XInternAtom(display, "WM_PROTOCOLS", False); deleteAtom = XInternAtom(display, "WM_DELETE_WINDOW", False); XSetWMProtocols(display, window, &deleteAtom, 1); stateAtom = XInternAtom(display, "_NET_WM_STATE", False); if (!stateAtom) throw std::system_error(getLastError(), errorCategory, "State atom is null"); stateFullscreenAtom = XInternAtom(display, "_NET_WM_STATE_FULLSCREEN", False); if (!stateFullscreenAtom) throw std::system_error(getLastError(), errorCategory, "Fullscreen state atom is null"); activateWindowAtom = XInternAtom(display, "_NET_ACTIVE_WINDOW", False); if (fullscreen) { XEvent event; event.type = ClientMessage; event.xclient.window = window; event.xclient.message_type = stateAtom; event.xclient.format = 32; event.xclient.data.l[0] = NET_WM_STATE_ADD; event.xclient.data.l[1] = stateFullscreenAtom; event.xclient.data.l[2] = 0; // no second property to toggle event.xclient.data.l[3] = 1; // source indication: application event.xclient.data.l[4] = 0; // unused if (!XSendEvent(display, DefaultRootWindow(display), 0, SubstructureNotifyMask | SubstructureRedirectMask, &event)) throw std::system_error(getLastError(), errorCategory, "Failed to send X11 fullscreen message"); } #elif OUZEL_SUPPORTS_DISPMANX auto engineLinux = static_cast<Engine*>(engine); auto display = engineLinux->getDisplay(); DISPMANX_MODEINFO_T modeInfo; const std::int32_t success = vc_dispmanx_display_get_info(display, &modeInfo); if (success < 0) throw std::runtime_error("Failed to get display size"); VC_RECT_T dstRect; dstRect.x = 0; dstRect.y = 0; dstRect.width = modeInfo.width; dstRect.height = modeInfo.height; VC_RECT_T srcRect; srcRect.x = 0; srcRect.y = 0; srcRect.width = modeInfo.width; srcRect.height = modeInfo.height; DISPMANX_UPDATE_HANDLE_T dispmanUpdate = vc_dispmanx_update_start(0); if (dispmanUpdate == DISPMANX_NO_HANDLE) throw std::runtime_error("Failed to start display update"); DISPMANX_ELEMENT_HANDLE_T dispmanElement = vc_dispmanx_element_add(dispmanUpdate, display, 0, &dstRect, 0, &srcRect, DISPMANX_PROTECTION_NONE, 0, 0, DISPMANX_NO_ROTATE); if (dispmanElement == DISPMANX_NO_HANDLE) throw std::runtime_error("Failed to add display element"); window.element = dispmanElement; window.width = modeInfo.width; window.height = modeInfo.height; vc_dispmanx_update_submit_sync(dispmanUpdate); size.v[0] = static_cast<std::uint32_t>(modeInfo.width); size.v[1] = static_cast<std::uint32_t>(modeInfo.height); resolution = size; #endif } NativeWindow::~NativeWindow() { #if OUZEL_SUPPORTS_X11 if (display && window) XDestroyWindow(display, window); #endif } void NativeWindow::executeCommand(const Command& command) { switch (command.type) { case Command::Type::changeSize: setSize(command.size); break; case Command::Type::changeFullscreen: setFullscreen(command.fullscreen); break; case Command::Type::close: close(); break; case Command::Type::setTitle: setTitle(command.title); break; case Command::Type::bringToFront: bringToFront(); break; case Command::Type::show: show(); break; case Command::Type::hide: hide(); break; case Command::Type::minimize: minimize(); break; case Command::Type::maximize: maximize(); break; case Command::Type::restore: restore(); break; default: throw std::runtime_error("Invalid command"); } } void NativeWindow::close() { #if OUZEL_SUPPORTS_X11 if (!protocolsAtom || !deleteAtom) return; XEvent event; event.type = ClientMessage; event.xclient.window = window; event.xclient.message_type = protocolsAtom; event.xclient.format = 32; // data is set as 32-bit integers event.xclient.data.l[0] = deleteAtom; event.xclient.data.l[1] = CurrentTime; event.xclient.data.l[2] = 0; // unused event.xclient.data.l[3] = 0; // unused event.xclient.data.l[4] = 0; // unused if (!XSendEvent(display, window, False, NoEventMask, &event)) throw std::system_error(getLastError(), errorCategory, "Failed to send X11 delete message"); #endif } void NativeWindow::setSize(const Size2U& newSize) { size = newSize; #if OUZEL_SUPPORTS_X11 XWindowChanges changes; changes.width = static_cast<int>(size.v[0]); changes.height = static_cast<int>(size.v[1]); XConfigureWindow(display, window, CWWidth | CWHeight, &changes); if (!resizable) { XSizeHints sizeHints; sizeHints.flags = PMinSize | PMaxSize; sizeHints.min_width = static_cast<int>(size.v[0]); sizeHints.max_width = static_cast<int>(size.v[0]); sizeHints.min_height = static_cast<int>(size.v[1]); sizeHints.max_height = static_cast<int>(size.v[1]); XSetWMNormalHints(display, window, &sizeHints); } resolution = size; Event resolutionChangeEvent(Event::Type::resolutionChange); resolutionChangeEvent.size = resolution; sendEvent(resolutionChangeEvent); #endif } void NativeWindow::setFullscreen(bool newFullscreen) { #if OUZEL_SUPPORTS_X11 if (fullscreen != newFullscreen) { XEvent event; event.type = ClientMessage; event.xclient.window = window; event.xclient.message_type = stateAtom; event.xclient.format = 32; event.xclient.data.l[0] = newFullscreen ? NET_WM_STATE_ADD : NET_WM_STATE_REMOVE; event.xclient.data.l[1] = stateFullscreenAtom; event.xclient.data.l[2] = 0; // no second property to toggle event.xclient.data.l[3] = 1; // source indication: application event.xclient.data.l[4] = 0; // unused if (!XSendEvent(display, DefaultRootWindow(display), 0, SubstructureNotifyMask | SubstructureRedirectMask, &event)) throw std::system_error(getLastError(), errorCategory, "Failed to send X11 fullscreen message"); } #endif fullscreen = newFullscreen; } void NativeWindow::setTitle(const std::string& newTitle) { #if OUZEL_SUPPORTS_X11 if (title != newTitle) XStoreName(display, window, newTitle.c_str()); #endif title = newTitle; } void NativeWindow::bringToFront() { #if OUZEL_SUPPORTS_X11 XRaiseWindow(display, window); XEvent event; event.type = ClientMessage; event.xclient.window = window; event.xclient.message_type = activateWindowAtom; event.xclient.format = 32; event.xclient.data.l[0] = 1; // source indication: application event.xclient.data.l[1] = CurrentTime; event.xclient.data.l[2] = 0; if (!XSendEvent(display, DefaultRootWindow(display), 0, SubstructureNotifyMask | SubstructureRedirectMask, &event)) throw std::system_error(getLastError(), errorCategory, "Failed to send X11 activate window message"); XFlush(display); #endif } void NativeWindow::show() { #if OUZEL_SUPPORTS_X11 if (!isMapped()) { XMapRaised(display, window); XFlush(display); } #endif } void NativeWindow::hide() { #if OUZEL_SUPPORTS_X11 if (isMapped()) { XWithdrawWindow(display, window, screenNumber); XFlush(display); } #endif } void NativeWindow::minimize() { #if OUZEL_SUPPORTS_X11 XIconifyWindow(display, window, screenNumber); XFlush(display); #endif } void NativeWindow::maximize() { } void NativeWindow::restore() { #if OUZEL_SUPPORTS_X11 XRaiseWindow(display, window); XEvent event; event.type = ClientMessage; event.xclient.window = window; event.xclient.message_type = activateWindowAtom; event.xclient.format = 32; event.xclient.data.l[0] = 1; // source indication: application event.xclient.data.l[1] = CurrentTime; event.xclient.data.l[2] = 0; if (!XSendEvent(display, DefaultRootWindow(display), 0, SubstructureNotifyMask | SubstructureRedirectMask, &event)) throw std::system_error(getLastError(), errorCategory, "Failed to send X11 activate window message"); XFlush(display); #endif } #if OUZEL_SUPPORTS_X11 void NativeWindow::handleFocusIn() { Event focusChangeEvent(Event::Type::focusChange); focusChangeEvent.focus = true; sendEvent(focusChangeEvent); } void NativeWindow::handleFocusOut() { Event focusChangeEvent(Event::Type::focusChange); focusChangeEvent.focus = false; sendEvent(focusChangeEvent); } void NativeWindow::handleResize(const Size2U& newSize) { size = newSize; resolution = size; Event sizeChangeEvent(Event::Type::sizeChange); sizeChangeEvent.size = size; sendEvent(sizeChangeEvent); Event resolutionChangeEvent(Event::Type::resolutionChange); resolutionChangeEvent.size = resolution; sendEvent(resolutionChangeEvent); } void NativeWindow::handleMap() { sendEvent(Event(Event::Type::restore)); } void NativeWindow::handleUnmap() { sendEvent(Event(Event::Type::minimize)); } bool NativeWindow::isMapped() const { XWindowAttributes attributes; XGetWindowAttributes(display, window, &attributes); return attributes.map_state != IsUnmapped; } #endif }
Fix window position on Linux
Fix window position on Linux
C++
unlicense
elnormous/ouzel,elnormous/ouzel,elnormous/ouzel
a4b30363e6ebd3428468b839a4e395da56b12a30
engine/thread/Thread.hpp
engine/thread/Thread.hpp
// Ouzel by Elviss Strazdins #ifndef OUZEL_THREAD_THREAD_HPP #define OUZEL_THREAD_THREAD_HPP #include <system_error> #include <thread> #ifdef _WIN32 # pragma push_macro("WIN32_LEAN_AND_MEAN") # pragma push_macro("NOMINMAX") # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # ifndef NOMINMAX # define NOMINMAX # endif # include <Windows.h> # pragma pop_macro("WIN32_LEAN_AND_MEAN") # pragma pop_macro("NOMINMAX") #elif defined(__unix__) || defined(__APPLE__) # include <pthread.h> #endif namespace ouzel::thread { class Thread final { public: Thread() noexcept = default; Thread(const Thread&) = delete; Thread(Thread&& other) noexcept: t{std::move(other.t)} {} Thread(const std::thread&) = delete; Thread(std::thread&& other) noexcept: t{std::move(other)} {} Thread& operator=(const Thread&) = delete; Thread& operator=(Thread&& other) noexcept { t = std::move(other.t); return *this; } Thread& operator=(const std::thread&) = delete; Thread& operator=(std::thread&& other) noexcept { t = std::move(other); return *this; } template <typename Callable, typename... Args> explicit Thread(Callable&& f, Args&&... args): t{std::forward<Callable>(f), std::forward<Args>(args)...} { } ~Thread() { if (t.joinable()) t.join(); } auto isJoinable() const noexcept { return t.joinable(); } auto getId() const noexcept { return t.get_id(); } auto getNativeHandle() { return t.native_handle(); } void join() { t.join(); } void setPriority(float priority, [[maybe_unused]] bool realtime) { #ifdef _MSC_VER static constexpr int priorities[] = { THREAD_PRIORITY_IDLE, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST, THREAD_PRIORITY_TIME_CRITICAL }; if (!SetThreadPriority(t.native_handle(), priorities[static_cast<std::size_t>((priority + 1.0F) * 6.0F / 2.0F)])) throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to set thread name"}; #else if (priority < 0.0F) priority = 0.0F; const auto policy = realtime ? SCHED_RR : SCHED_OTHER; const auto minPriority = sched_get_priority_min(policy); if (minPriority == -1) throw std::system_error{errno, std::system_category(), "Failed to get thread min priority"}; const auto maxPriority = sched_get_priority_max(policy); if (maxPriority == -1) throw std::system_error{errno, std::system_category(), "Failed to get thread max priority"}; sched_param param; param.sched_priority = static_cast<int>(priority * static_cast<float>(maxPriority - minPriority)) + minPriority; if (const auto error = pthread_setschedparam(t.native_handle(), policy, &param); error != 0) throw std::system_error{error, std::system_category(), "Failed to set thread priority"}; #endif } private: std::thread t; }; } #endif // OUZEL_THREAD_THREAD_HPP
// Ouzel by Elviss Strazdins #ifndef OUZEL_THREAD_THREAD_HPP #define OUZEL_THREAD_THREAD_HPP #include <system_error> #include <thread> #ifdef _WIN32 # pragma push_macro("WIN32_LEAN_AND_MEAN") # pragma push_macro("NOMINMAX") # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # ifndef NOMINMAX # define NOMINMAX # endif # include <Windows.h> # pragma pop_macro("WIN32_LEAN_AND_MEAN") # pragma pop_macro("NOMINMAX") #elif defined(__unix__) || defined(__APPLE__) # include <pthread.h> #endif namespace ouzel::thread { class Thread final { public: Thread() noexcept = default; Thread(const Thread&) = delete; Thread(Thread&& other) noexcept: t{std::move(other.t)} {} Thread(const std::thread&) = delete; Thread(std::thread&& other) noexcept: t{std::move(other)} {} Thread& operator=(const Thread&) = delete; Thread& operator=(Thread&& other) noexcept { t = std::move(other.t); return *this; } Thread& operator=(const std::thread&) = delete; Thread& operator=(std::thread&& other) noexcept { if (t.joinable()) t.join(); t = std::move(other); return *this; } template <typename Callable, typename... Args> explicit Thread(Callable&& f, Args&&... args): t{std::forward<Callable>(f), std::forward<Args>(args)...} { } ~Thread() { if (t.joinable()) t.join(); } auto isJoinable() const noexcept { return t.joinable(); } auto getId() const noexcept { return t.get_id(); } auto getNativeHandle() { return t.native_handle(); } void join() { t.join(); } void setPriority(float priority, [[maybe_unused]] bool realtime) { #ifdef _MSC_VER static constexpr int priorities[] = { THREAD_PRIORITY_IDLE, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST, THREAD_PRIORITY_TIME_CRITICAL }; if (!SetThreadPriority(t.native_handle(), priorities[static_cast<std::size_t>((priority + 1.0F) * 6.0F / 2.0F)])) throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), "Failed to set thread name"}; #else if (priority < 0.0F) priority = 0.0F; const auto policy = realtime ? SCHED_RR : SCHED_OTHER; const auto minPriority = sched_get_priority_min(policy); if (minPriority == -1) throw std::system_error{errno, std::system_category(), "Failed to get thread min priority"}; const auto maxPriority = sched_get_priority_max(policy); if (maxPriority == -1) throw std::system_error{errno, std::system_category(), "Failed to get thread max priority"}; sched_param param; param.sched_priority = static_cast<int>(priority * static_cast<float>(maxPriority - minPriority)) + minPriority; if (const auto error = pthread_setschedparam(t.native_handle(), policy, &param); error != 0) throw std::system_error{error, std::system_category(), "Failed to set thread priority"}; #endif } private: std::thread t; }; } #endif // OUZEL_THREAD_THREAD_HPP
Join a joinable thread in move operator
Join a joinable thread in move operator
C++
unlicense
elnormous/ouzel,elnormous/ouzel,elnormous/ouzel
7f97f73c1b4c44e06989a9d8a7d5f4ba30078af3
environment/core/hlt.hpp
environment/core/hlt.hpp
#ifndef HLT_H #define HLT_H #include <list> #include <vector> #include <random> #include <algorithm> #include <functional> #include <iostream> #include <fstream> #include <assert.h> #include <array> #include "json.hpp" extern bool quiet_output; namespace hlt { constexpr auto MAX_PLAYERS = 4; constexpr auto MAX_PLAYER_SHIPS = 200; constexpr auto MAX_QUEUED_MOVES = 1; struct GameConstants { int PLANETS_PER_PLAYER = 6; unsigned int EXTRA_PLANETS = 4; int DRAG = 3; int MAX_SPEED = 30; int MAX_ACCELERATION = 10; unsigned short MAX_SHIP_HEALTH = 255; unsigned short BASE_SHIP_HEALTH = 255; unsigned short DOCKED_SHIP_REGENERATION = 0; unsigned int WEAPON_COOLDOWN = 1; int WEAPON_RADIUS = 5; int WEAPON_DAMAGE = 128; unsigned int EXPLOSION_RADIUS = 5; unsigned int MAX_DOCKING_DISTANCE = 4; unsigned int DOCK_TURNS = 5; int PRODUCTION_PER_SHIP = 100; unsigned int BASE_PRODUCTIVITY = 25; unsigned int ADDITIONAL_PRODUCTIVITY = 15; static auto get_mut() -> GameConstants& { // Guaranteed initialized only once by C++11 static GameConstants instance; return instance; } static auto get() -> const GameConstants& { return get_mut(); } auto to_json() const -> nlohmann::json; auto from_json(const nlohmann::json& json) -> void; }; typedef unsigned char PlayerId; typedef unsigned long EntityIndex; //! A poor man's std::optional. template<typename T> using possibly = std::pair<T, bool>; struct Location { unsigned short pos_x, pos_y; friend auto operator<< (std::ostream& ostream, const Location& location) -> std::ostream&; }; struct Velocity { short vel_x, vel_y; auto accelerate_by(unsigned short magnitude, double angle) -> void; auto magnitude() const -> double; auto angle() const -> double; }; static bool operator==(const Location& l1, const Location& l2) { return l1.pos_x == l2.pos_x && l1.pos_y == l2.pos_y; } struct Entity { Location location; unsigned short health; //! The radius of the entity, in terms of grid cells from the center. //! Ships have a radius of 0 (they occupy only the center). A planet //! with radius=1 will occupy 5 grid cells (the center and the four //! adjacent cells in the cardinal directions) unsigned short radius; void kill() { health = 0; } bool is_alive() const { return health > 0; } auto heal(unsigned short points) -> void { health = std::min(GameConstants::get().MAX_SHIP_HEALTH, static_cast<unsigned short>(health + points)); } }; enum class DockingStatus { Undocked = 0, Docking = 1, Docked = 2, Undocking = 3, }; struct Ship : Entity { Velocity velocity; unsigned int weapon_cooldown; DockingStatus docking_status; unsigned int docking_progress; EntityIndex docked_planet; auto reset_docking_status() -> void { docking_status = DockingStatus::Undocked; docking_progress = 0; docked_planet = 0; } auto revive(const Location& loc) -> void { health = GameConstants::get().BASE_SHIP_HEALTH; location = loc; weapon_cooldown = 0; radius = 0; velocity = { 0, 0 }; docking_status = DockingStatus::Undocked; docking_progress = 0; docked_planet = 0; } }; struct Planet : Entity { PlayerId owner; bool owned; unsigned short remaining_production; unsigned short current_production; unsigned short docking_spots; //! Contains IDs of all ships in the process of docking or undocking, //! as well as docked ships. std::vector<EntityIndex> docked_ships; Planet(unsigned short x, unsigned short y, unsigned short radius) { location.pos_x = x; location.pos_y = y; this->radius = radius; docking_spots = radius; remaining_production = static_cast<unsigned short>(std::sqrt(10 * radius)) * 100; current_production = 0; health = static_cast<unsigned short>(radius * GameConstants::get().MAX_SHIP_HEALTH / 100); docked_ships = std::vector<EntityIndex>(); owned = false; } auto add_ship(EntityIndex ship) -> void; auto remove_ship(EntityIndex ship) -> void; }; enum class EntityType { InvalidEntity, ShipEntity, PlanetEntity, }; //! A way to uniquely identify an Entity, regardless of its type. struct EntityId { private: //! Planets are unowned, and have player ID == -1. int _player_id; int _entity_index; EntityId(); public: EntityType type; auto is_valid() const -> bool; auto player_id() const -> PlayerId; auto entity_index() const -> EntityIndex; //! Construct an entity ID representing an invalid entity. static auto invalid() -> EntityId; //! Construct an entity ID for the given planet. static auto for_planet(EntityIndex index) -> EntityId; //! Construct an entity ID for the given ship. static auto for_ship(PlayerId player_id, EntityIndex index) -> EntityId; friend auto operator<< (std::ostream& ostream, const EntityId& id) -> std::ostream&; friend auto operator== (const EntityId& id1, const EntityId& id2) -> bool; friend auto operator!= (const EntityId& id1, const EntityId& id2) -> bool; }; enum class MoveType { //! Noop is not user-specifiable - instead it's the default command, //! used to mean that no command was issued Noop = 0, Thrust, Dock, Undock, //! Error wraps a move that was syntactically valid, but could not be //! executed in the current game state. Error, }; struct Move { MoveType type; EntityIndex shipId; union { struct { unsigned short thrust; unsigned short angle; } thrust; EntityIndex dock_to; } move; }; typedef std::array<std::array<hlt::Move, MAX_PLAYER_SHIPS>, MAX_QUEUED_MOVES> PlayerMoveQueue; typedef std::array<PlayerMoveQueue, MAX_PLAYERS> MoveQueue; class Map { public: std::array<std::array<Ship, MAX_PLAYER_SHIPS>, MAX_PLAYERS> ships; std::vector<Planet> planets; unsigned short map_width, map_height; //Number of rows and columns, NOT maximum index. Map(); Map(const Map& other_map); Map(unsigned short width, unsigned short height); auto get_ship(PlayerId player, EntityIndex entity) -> Ship&; auto get_ship(EntityId entity_id) -> Ship&; auto get_planet(EntityId entity_id) -> Planet&; auto get_entity(EntityId entity_id) -> Entity&; auto get_distance(Location l1, Location l2) const -> float; auto get_angle(Location l1, Location l2) const -> float; auto location_with_delta(const Location& location, int dx, int dy) -> possibly<Location>; }; } #endif
#ifndef HLT_H #define HLT_H #include <list> #include <vector> #include <random> #include <algorithm> #include <functional> #include <iostream> #include <fstream> #include <assert.h> #include <array> #include "json.hpp" extern bool quiet_output; namespace hlt { constexpr auto MAX_PLAYERS = 4; constexpr auto MAX_PLAYER_SHIPS = 200; constexpr auto MAX_QUEUED_MOVES = 1; struct GameConstants { int PLANETS_PER_PLAYER = 6; unsigned int EXTRA_PLANETS = 4; int DRAG = 3; int MAX_SPEED = 30; int MAX_ACCELERATION = 10; unsigned short MAX_SHIP_HEALTH = 255; unsigned short BASE_SHIP_HEALTH = 255; unsigned short DOCKED_SHIP_REGENERATION = 0; unsigned int WEAPON_COOLDOWN = 1; int WEAPON_RADIUS = 5; int WEAPON_DAMAGE = 128; unsigned int EXPLOSION_RADIUS = 5; unsigned int MAX_DOCKING_DISTANCE = 4; unsigned int DOCK_TURNS = 5; int PRODUCTION_PER_SHIP = 100; unsigned int BASE_PRODUCTIVITY = 25; unsigned int ADDITIONAL_PRODUCTIVITY = 15; static auto get_mut() -> GameConstants& { // Guaranteed initialized only once by C++11 static GameConstants instance; return instance; } static auto get() -> const GameConstants& { return get_mut(); } auto to_json() const -> nlohmann::json; auto from_json(const nlohmann::json& json) -> void; }; typedef unsigned char PlayerId; typedef unsigned long EntityIndex; //! A poor man's std::optional. template<typename T> using possibly = std::pair<T, bool>; struct Location { unsigned short pos_x, pos_y; friend auto operator<< (std::ostream& ostream, const Location& location) -> std::ostream&; }; struct Velocity { short vel_x, vel_y; auto accelerate_by(unsigned short magnitude, double angle) -> void; auto magnitude() const -> double; auto angle() const -> double; }; static bool operator==(const Location& l1, const Location& l2) { return l1.pos_x == l2.pos_x && l1.pos_y == l2.pos_y; } struct Entity { Location location; unsigned short health; //! The radius of the entity, in terms of grid cells from the center. //! Ships have a radius of 0 (they occupy only the center). A planet //! with radius=1 will occupy 5 grid cells (the center and the four //! adjacent cells in the cardinal directions) unsigned short radius; void kill() { health = 0; } bool is_alive() const { return health > 0; } auto heal(unsigned short points) -> void { health = std::min(GameConstants::get().MAX_SHIP_HEALTH, static_cast<unsigned short>(health + points)); } }; enum class DockingStatus { Undocked = 0, Docking = 1, Docked = 2, Undocking = 3, }; struct Ship : Entity { Velocity velocity; unsigned int weapon_cooldown; DockingStatus docking_status; unsigned int docking_progress; EntityIndex docked_planet; auto reset_docking_status() -> void { docking_status = DockingStatus::Undocked; docking_progress = 0; docked_planet = 0; } auto revive(const Location& loc) -> void { health = GameConstants::get().BASE_SHIP_HEALTH; location = loc; weapon_cooldown = 0; radius = 0; velocity = { 0, 0 }; docking_status = DockingStatus::Undocked; docking_progress = 0; docked_planet = 0; } }; struct Planet : Entity { PlayerId owner; bool owned; unsigned short remaining_production; unsigned short current_production; unsigned short docking_spots; //! Contains IDs of all ships in the process of docking or undocking, //! as well as docked ships. std::vector<EntityIndex> docked_ships; Planet(unsigned short x, unsigned short y, unsigned short radius) { location.pos_x = x; location.pos_y = y; this->radius = radius; docking_spots = radius; remaining_production = static_cast<unsigned short>(std::sqrt(10 * radius)) * 100; current_production = 0; health = static_cast<unsigned short>(radius * GameConstants::get().MAX_SHIP_HEALTH); docked_ships = std::vector<EntityIndex>(); owned = false; } auto add_ship(EntityIndex ship) -> void; auto remove_ship(EntityIndex ship) -> void; }; enum class EntityType { InvalidEntity, ShipEntity, PlanetEntity, }; //! A way to uniquely identify an Entity, regardless of its type. struct EntityId { private: //! Planets are unowned, and have player ID == -1. int _player_id; int _entity_index; EntityId(); public: EntityType type; auto is_valid() const -> bool; auto player_id() const -> PlayerId; auto entity_index() const -> EntityIndex; //! Construct an entity ID representing an invalid entity. static auto invalid() -> EntityId; //! Construct an entity ID for the given planet. static auto for_planet(EntityIndex index) -> EntityId; //! Construct an entity ID for the given ship. static auto for_ship(PlayerId player_id, EntityIndex index) -> EntityId; friend auto operator<< (std::ostream& ostream, const EntityId& id) -> std::ostream&; friend auto operator== (const EntityId& id1, const EntityId& id2) -> bool; friend auto operator!= (const EntityId& id1, const EntityId& id2) -> bool; }; enum class MoveType { //! Noop is not user-specifiable - instead it's the default command, //! used to mean that no command was issued Noop = 0, Thrust, Dock, Undock, //! Error wraps a move that was syntactically valid, but could not be //! executed in the current game state. Error, }; struct Move { MoveType type; EntityIndex shipId; union { struct { unsigned short thrust; unsigned short angle; } thrust; EntityIndex dock_to; } move; }; typedef std::array<std::array<hlt::Move, MAX_PLAYER_SHIPS>, MAX_QUEUED_MOVES> PlayerMoveQueue; typedef std::array<PlayerMoveQueue, MAX_PLAYERS> MoveQueue; class Map { public: std::array<std::array<Ship, MAX_PLAYER_SHIPS>, MAX_PLAYERS> ships; std::vector<Planet> planets; unsigned short map_width, map_height; //Number of rows and columns, NOT maximum index. Map(); Map(const Map& other_map); Map(unsigned short width, unsigned short height); auto get_ship(PlayerId player, EntityIndex entity) -> Ship&; auto get_ship(EntityId entity_id) -> Ship&; auto get_planet(EntityId entity_id) -> Planet&; auto get_entity(EntityId entity_id) -> Entity&; auto get_distance(Location l1, Location l2) const -> float; auto get_angle(Location l1, Location l2) const -> float; auto location_with_delta(const Location& location, int dx, int dy) -> possibly<Location>; }; } #endif
Fix planet health calculation (whoops)
Fix planet health calculation (whoops)
C++
mit
lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II
29bae28aec1dd243d775d8114e3bd2b01bca8ba6
treeplayer/src/TTreeIndex.cxx
treeplayer/src/TTreeIndex.cxx
// @(#)root/tree:$Name: $:$Id: TTreeIndex.cxx,v 1.2 2004/07/09 07:41:43 brun Exp $ // Author: Rene Brun 05/07/2004 /************************************************************************* * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // A Tree Index with majorname and minorname. // // // ////////////////////////////////////////////////////////////////////////// #include "TTreeIndex.h" #include "TTree.h" ClassImp(TTreeIndex) //______________________________________________________________________________ TTreeIndex::TTreeIndex(): TVirtualIndex() { // Default constructor for TTreeIndex fTree = 0; fN = 0; fIndexValues = 0; fIndex = 0; fMajorFormula = 0; fMinorFormula = 0; fMajorFormulaParent = 0; fMinorFormulaParent = 0; } //______________________________________________________________________________ TTreeIndex::TTreeIndex(const TTree *T, const char *majorname, const char *minorname) : TVirtualIndex() { // Normal constructor for TTreeIndex // // Build an index table using the leaves of Tree T with major & minor names // The index is built with the expressions given in "majorname" and "minorname". // // a Long64_t array fIndexValues is built with: // major = the value of majorname converted to an integer // minor = the value of minorname converted to an integer // fIndexValues[i] = major<<31 + minor // This array is sorted. The sorted fIndex[i] contains the serial number // in the Tree corresponding to the pair "major,minor" in fIndexvalues[i]. // // Once the index is computed, one can retrieve one entry via // T->GetEntryWithIndex(majornumber, minornumber) // Example: // tree.BuildIndex("Run","Event"); //creates an index using leaves Run and Event // tree.GetEntryWithIndex(1234,56789); //reads entry corresponding to // Run=1234 and Event=56789 // // Note that majorname and minorname may be expressions using original // Tree variables eg: "run-90000", "event +3*xx". However the result // must be integer. // In case an expression is specified, the equivalent expression must be computed // when calling GetEntryWithIndex. // // To build an index with only majorname, specify minorname="0" (default) // // TreeIndex and Friend Trees // --------------------------- // Assuming a parent Tree T and a friend Tree TF, the following cases are supported: // CASE 1: T->GetEntry(entry) is called // In this case, the serial number entry is used to retrieve // the data in both Trees. // CASE 2: T->GetEntry(entry) is called, TF has a TreeIndex // the expressions given in major/minorname of TF are used // to compute the value pair major,minor with the data in T. // TF->GetEntry(major,minor) is then called (tricky case!) // CASE 3: T->GetEntry(major,minor) is called. // It is assumed that both T and TF have a TreeIndex built using // the same major and minor name. // // Saving the TreeIndex // -------------------- // Once the index is built, it can be saved with the TTree object // with tree.Write(); (if the file has been open in "update" mode). // // The most convenient place to create the index is at the end of // the filling process just before saving the Tree header. // If a previous index was computed, it is redefined by this new call. // // Note that this function can also be applied to a TChain. // // The return value is the number of entries in the Index (< 0 indicates failure) fTree = (TTree*)T; fN = 0; fIndexValues = 0; fIndex = 0; fMajorFormula = 0; fMinorFormula = 0; fMajorFormulaParent = 0; fMinorFormulaParent = 0; fMajorName = majorname; fMinorName = minorname; if (!T) return; fN = (Long64_t)T->GetEntries(); if (fN <= 0) { Error("TreeIndex","Cannot build a TreeIndex with a Tree having no entries"); return; } GetMajorFormula(); GetMinorFormula(); if (!fMajorFormula || !fMinorFormula) { Error("TreeIndex","Cannot build the index with major=%s, minor=%s",fMajorName.Data(), fMinorName.Data()); return; } if (!fMajorFormula->GetNdim() || !fMinorFormula->GetNdim()) { Error("TreeIndex","Cannot build the index with major=%s, minor=%s",fMajorName.Data(), fMinorName.Data()); return; } Long64_t *w = new Long64_t[fN]; Long64_t i; for (i=0;i<fN;i++) { GetEntry(i); Double_t majord = fMajorFormula->EvalInstance(); Double_t minord = fMinorFormula->EvalInstance(); Long64_t majorv = (Long64_t)majord; Long64_t minorv = (Long64_t)minord; w[i] = majorv<<31; w[i] += minorv; } fIndex = new Long64_t[fN]; TMath::Sort(fN,w,fIndex,0); fIndexValues = new Long64_t[fN]; for (i=0;i<fN;i++) { fIndexValues[i] = w[fIndex[i]]; } delete [] w; } //______________________________________________________________________________ TTreeIndex::~TTreeIndex() { delete [] fIndexValues; fIndexValues = 0; delete [] fIndex; fIndex = 0; delete fMajorFormula; fMajorFormula = 0; delete fMinorFormula; fMinorFormula = 0; delete fMajorFormulaParent; fMajorFormulaParent = 0; delete fMinorFormulaParent; fMinorFormulaParent = 0; } //______________________________________________________________________________ Int_t TTreeIndex::GetEntry(Long64_t entry) { // Read in memory the branches referenced in major and minorname if (!fTree) return 0; TLeaf *leaf; Int_t i; Int_t nbytes = 0; for (i=0;i<10;i++) { if (!fMajorFormula) break; leaf = fMajorFormula->GetLeaf(i); if (!leaf) break; nbytes += leaf->GetBranch()->GetEntry(entry); } for (i=0;i<10;i++) { if (!fMinorFormula) break; leaf = fMinorFormula->GetLeaf(i); if (!leaf) break; nbytes += leaf->GetBranch()->GetEntry(entry); } return nbytes; } //______________________________________________________________________________ Int_t TTreeIndex::GetEntryNumberFriend(const TTree *T) { // returns the entry number in this friend Tree corresponding to entry in // the master Tree T. // In case this friend Tree and T do not share an index with the same // major and minor name, the entry serial number in the friend tree // and in the master Tree are assumed to be the same GetMajorFormulaParent(T); GetMinorFormulaParent(T); if (!fMajorFormulaParent || !fMinorFormulaParent) return -1; Double_t majord = fMajorFormulaParent->EvalInstance(); Double_t minord = fMinorFormulaParent->EvalInstance(); Long64_t majorv = (Long64_t)majord; Long64_t minorv = (Long64_t)minord; return fTree->GetEntryNumberWithIndex(majorv,minorv); } //______________________________________________________________________________ Long64_t TTreeIndex::GetEntryNumberWithBestIndex(Int_t major, Int_t minor) const { // Return entry number corresponding to major and minor number // Note that this function returns only the entry number, not the data // To read the data corresponding to an entry number, use TTree::GetEntryWithIndex // the BuildIndex function has created a table of Double_t* of sorted values // corresponding to val = major + minor*1e-9; // The function performs binary search in this sorted table. // If it finds a pair that maches val, it returns directly the // index in the table. // If an entry corresponding to major and minor is not found, the function // returns the index of the major,minor pair immediatly lower than the // requested value, ie it will return -1 if the pair is lower than // the first entry in the index. // // See also GetEntryNumberWithIndex if (fN == 0) return -1; Long64_t value = Long64_t(major)<<31; value += minor; Int_t i = TMath::BinarySearch(fN, fIndexValues, value); if (i < 0) return -1; return fIndex[i]; } //______________________________________________________________________________ Long64_t TTreeIndex::GetEntryNumberWithIndex(Int_t major, Int_t minor) const { // Return entry number corresponding to major and minor number // Note that this function returns only the entry number, not the data // To read the data corresponding to an entry number, use TTree::GetEntryWithIndex // the BuildIndex function has created a table of Double_t* of sorted values // corresponding to val = major + minor*1e-9; // The function performs binary search in this sorted table. // If it finds a pair that maches val, it returns directly the // index in the table, otherwise it returns -1. // // See also GetEntryNumberWithBestIndex if (fN == 0) return -1; Long64_t value = Long64_t(major)<<31; value += minor; Int_t i = TMath::BinarySearch(fN, fIndexValues, value); if (i < 0) return -1; if (TMath::Abs(fIndexValues[i] - value) > 1.e-10) return -1; return fIndex[i]; } //______________________________________________________________________________ TTreeFormula *TTreeIndex::GetMajorFormula() { // return a pointer to the TreeFormula corresponding to the majorname if (!fMajorFormula) fMajorFormula = new TTreeFormula("Major",fMajorName.Data(),fTree); return fMajorFormula; } //______________________________________________________________________________ TTreeFormula *TTreeIndex::GetMinorFormula() { // return a pointer to the TreeFormula corresponding to the minorname if (!fMinorFormula) fMinorFormula = new TTreeFormula("Minor",fMinorName.Data(),fTree); return fMinorFormula; } //______________________________________________________________________________ TTreeFormula *TTreeIndex::GetMajorFormulaParent(const TTree *T) { // return a pointer to the TreeFormula corresponding to the majorname in parent tree T if (!fMajorFormulaParent) fMajorFormulaParent = new TTreeFormula("MajorP",fMajorName.Data(),(TTree*)T); return fMajorFormulaParent; } //______________________________________________________________________________ TTreeFormula *TTreeIndex::GetMinorFormulaParent(const TTree *T) { // return a pointer to the TreeFormula corresponding to the minorname in parent tree T if (!fMinorFormulaParent) fMinorFormulaParent = new TTreeFormula("MinorP",fMinorName.Data(),(TTree*)T); return fMinorFormulaParent; } //______________________________________________________________________________ void TTreeIndex::Print(Option_t * option) const { // print the table with : serial number, majorname, minorname // if option = "10" print only the first 10 entries // if option = "100" print only the first 100 entries // if option = "1000" print only the first 1000 entries TString opt = option; Long64_t n = fN; if (opt.Contains("10")) n = 10; if (opt.Contains("100")) n = 100; if (opt.Contains("1000")) n = 1000; printf("\n**********************************************\n"); printf("* Index of Tree: %s/%s\n",fTree->GetName(),fTree->GetTitle()); printf("**********************************************\n"); printf("%8s : %16s : %16s\n","serial",fMajorName.Data(),fMinorName.Data()); printf("**********************************************\n"); for (Long64_t i=0;i<n;i++) { Long64_t minor = fIndexValues[i] & 0xffff; Long64_t major = fIndexValues[i]>>31; printf("%8lld : %8lld : %8lld\n",i,major,minor); } } //______________________________________________________________________________ void TTreeIndex::Streamer(TBuffer &R__b) { // Stream an object of class TTreeIndex. // Note that this Streamer should be changed to an automatic Streamer // once TStreamerInfo supports an index of type Long64_t UInt_t R__s, R__c; if (R__b.IsReading()) { Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v) { } TVirtualIndex::Streamer(R__b); fMajorName.Streamer(R__b); fMinorName.Streamer(R__b); R__b >> fN; fIndexValues = new Long64_t[fN]; R__b.ReadFastArray(fIndexValues,fN); fIndex = new Long64_t[fN]; R__b.ReadFastArray(fIndex,fN); R__b.CheckByteCount(R__s, R__c, TTreeIndex::IsA()); } else { R__c = R__b.WriteVersion(TTreeIndex::IsA(), kTRUE); TVirtualIndex::Streamer(R__b); fMajorName.Streamer(R__b); fMinorName.Streamer(R__b); R__b << fN; R__b.WriteFastArray(fIndexValues, fN); R__b.WriteFastArray(fIndex, fN); R__b.SetByteCount(R__c, kTRUE); } } //______________________________________________________________________________ void TTreeIndex::SetTree(const TTree *T) { // this function is called by TChain::LoadTree and TTreePlayer::UpdateFormulaLeaves // when a new Tree is loaded. // Because Trees in a TChain may have a different list of leaves, one // must update the leaves numbers in the TTreeFormula used by the TreeIndex. fTree = (TTree*)T; if (fMajorFormula) {fMajorFormula->SetTree(fTree); fMajorFormula->UpdateFormulaLeaves();} if (fMinorFormula) {fMinorFormula->SetTree(fTree); fMinorFormula->UpdateFormulaLeaves();} if (fMajorFormulaParent) {fMajorFormulaParent->SetTree(fTree); fMajorFormulaParent->UpdateFormulaLeaves();} if (fMinorFormulaParent) {fMinorFormulaParent->SetTree(fTree); fMinorFormulaParent->UpdateFormulaLeaves();} }
// @(#)root/tree:$Name: $:$Id: TTreeIndex.cxx,v 1.3 2004/07/09 07:54:59 brun Exp $ // Author: Rene Brun 05/07/2004 /************************************************************************* * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // A Tree Index with majorname and minorname. // // // ////////////////////////////////////////////////////////////////////////// #include "TTreeIndex.h" #include "TTree.h" ClassImp(TTreeIndex) //______________________________________________________________________________ TTreeIndex::TTreeIndex(): TVirtualIndex() { // Default constructor for TTreeIndex fTree = 0; fN = 0; fIndexValues = 0; fIndex = 0; fMajorFormula = 0; fMinorFormula = 0; fMajorFormulaParent = 0; fMinorFormulaParent = 0; } //______________________________________________________________________________ TTreeIndex::TTreeIndex(const TTree *T, const char *majorname, const char *minorname) : TVirtualIndex() { // Normal constructor for TTreeIndex // // Build an index table using the leaves of Tree T with major & minor names // The index is built with the expressions given in "majorname" and "minorname". // // a Long64_t array fIndexValues is built with: // major = the value of majorname converted to an integer // minor = the value of minorname converted to an integer // fIndexValues[i] = major<<31 + minor // This array is sorted. The sorted fIndex[i] contains the serial number // in the Tree corresponding to the pair "major,minor" in fIndexvalues[i]. // // Once the index is computed, one can retrieve one entry via // T->GetEntryWithIndex(majornumber, minornumber) // Example: // tree.BuildIndex("Run","Event"); //creates an index using leaves Run and Event // tree.GetEntryWithIndex(1234,56789); //reads entry corresponding to // Run=1234 and Event=56789 // // Note that majorname and minorname may be expressions using original // Tree variables eg: "run-90000", "event +3*xx". However the result // must be integer. // In case an expression is specified, the equivalent expression must be computed // when calling GetEntryWithIndex. // // To build an index with only majorname, specify minorname="0" (default) // // TreeIndex and Friend Trees // --------------------------- // Assuming a parent Tree T and a friend Tree TF, the following cases are supported: // CASE 1: T->GetEntry(entry) is called // In this case, the serial number entry is used to retrieve // the data in both Trees. // CASE 2: T->GetEntry(entry) is called, TF has a TreeIndex // the expressions given in major/minorname of TF are used // to compute the value pair major,minor with the data in T. // TF->GetEntry(major,minor) is then called (tricky case!) // CASE 3: T->GetEntry(major,minor) is called. // It is assumed that both T and TF have a TreeIndex built using // the same major and minor name. // // Saving the TreeIndex // -------------------- // Once the index is built, it can be saved with the TTree object // with tree.Write(); (if the file has been open in "update" mode). // // The most convenient place to create the index is at the end of // the filling process just before saving the Tree header. // If a previous index was computed, it is redefined by this new call. // // Note that this function can also be applied to a TChain. // // The return value is the number of entries in the Index (< 0 indicates failure) fTree = (TTree*)T; fN = 0; fIndexValues = 0; fIndex = 0; fMajorFormula = 0; fMinorFormula = 0; fMajorFormulaParent = 0; fMinorFormulaParent = 0; fMajorName = majorname; fMinorName = minorname; if (!T) return; fN = (Long64_t)T->GetEntries(); if (fN <= 0) { Error("TreeIndex","Cannot build a TreeIndex with a Tree having no entries"); return; } GetMajorFormula(); GetMinorFormula(); if (!fMajorFormula || !fMinorFormula) { Error("TreeIndex","Cannot build the index with major=%s, minor=%s",fMajorName.Data(), fMinorName.Data()); return; } if (!fMajorFormula->GetNdim() || !fMinorFormula->GetNdim()) { Error("TreeIndex","Cannot build the index with major=%s, minor=%s",fMajorName.Data(), fMinorName.Data()); return; } Long64_t *w = new Long64_t[fN]; Long64_t i; for (i=0;i<fN;i++) { GetEntry(i); Double_t majord = fMajorFormula->EvalInstance(); Double_t minord = fMinorFormula->EvalInstance(); Long64_t majorv = (Long64_t)majord; Long64_t minorv = (Long64_t)minord; w[i] = majorv<<31; w[i] += minorv; } fIndex = new Long64_t[fN]; TMath::Sort(fN,w,fIndex,0); fIndexValues = new Long64_t[fN]; for (i=0;i<fN;i++) { fIndexValues[i] = w[fIndex[i]]; } delete [] w; } //______________________________________________________________________________ TTreeIndex::~TTreeIndex() { if (fTree && fTree->GetTreeIndex() == this) fTree->SetTreeIndex(0); delete [] fIndexValues; fIndexValues = 0; delete [] fIndex; fIndex = 0; delete fMajorFormula; fMajorFormula = 0; delete fMinorFormula; fMinorFormula = 0; delete fMajorFormulaParent; fMajorFormulaParent = 0; delete fMinorFormulaParent; fMinorFormulaParent = 0; } //______________________________________________________________________________ Int_t TTreeIndex::GetEntry(Long64_t entry) { // Read in memory the branches referenced in major and minorname if (!fTree) return 0; TLeaf *leaf; Int_t i; Int_t nbytes = 0; for (i=0;i<10;i++) { if (!fMajorFormula) break; leaf = fMajorFormula->GetLeaf(i); if (!leaf) break; nbytes += leaf->GetBranch()->GetEntry(entry); } for (i=0;i<10;i++) { if (!fMinorFormula) break; leaf = fMinorFormula->GetLeaf(i); if (!leaf) break; nbytes += leaf->GetBranch()->GetEntry(entry); } return nbytes; } //______________________________________________________________________________ Int_t TTreeIndex::GetEntryNumberFriend(const TTree *T) { // returns the entry number in this friend Tree corresponding to entry in // the master Tree T. // In case this friend Tree and T do not share an index with the same // major and minor name, the entry serial number in the friend tree // and in the master Tree are assumed to be the same if (!T) return -3; GetMajorFormulaParent(T); GetMinorFormulaParent(T); if (!fMajorFormulaParent || !fMinorFormulaParent) return -1; if (!fMajorFormulaParent->GetNdim() || !fMinorFormulaParent->GetNdim()) { // The Tree Index in the friend has a pair majorname,minorname // not available in the parent Tree T. // if the friend Tree has less entries than the parent, this is an error Int_t pentry = T->GetReadEntry(); if (pentry >= (Int_t)fTree->GetEntries()) return -2; // otherwise we ignore the Tree Index and return the entry number // in the parent Tree. return pentry; } // majorname, minorname exist in the parent Tree // we find the current values pair majorv,minorv in the parent Tree Double_t majord = fMajorFormulaParent->EvalInstance(); Double_t minord = fMinorFormulaParent->EvalInstance(); Long64_t majorv = (Long64_t)majord; Long64_t minorv = (Long64_t)minord; // we check if this pair exist in the index. // if yes, we return the corresponding entry number // if not the function returns -1 return fTree->GetEntryNumberWithIndex(majorv,minorv); } //______________________________________________________________________________ Long64_t TTreeIndex::GetEntryNumberWithBestIndex(Int_t major, Int_t minor) const { // Return entry number corresponding to major and minor number // Note that this function returns only the entry number, not the data // To read the data corresponding to an entry number, use TTree::GetEntryWithIndex // the BuildIndex function has created a table of Double_t* of sorted values // corresponding to val = major + minor*1e-9; // The function performs binary search in this sorted table. // If it finds a pair that maches val, it returns directly the // index in the table. // If an entry corresponding to major and minor is not found, the function // returns the index of the major,minor pair immediatly lower than the // requested value, ie it will return -1 if the pair is lower than // the first entry in the index. // // See also GetEntryNumberWithIndex if (fN == 0) return -1; Long64_t value = Long64_t(major)<<31; value += minor; Int_t i = TMath::BinarySearch(fN, fIndexValues, value); if (i < 0) return -1; return fIndex[i]; } //______________________________________________________________________________ Long64_t TTreeIndex::GetEntryNumberWithIndex(Int_t major, Int_t minor) const { // Return entry number corresponding to major and minor number // Note that this function returns only the entry number, not the data // To read the data corresponding to an entry number, use TTree::GetEntryWithIndex // the BuildIndex function has created a table of Double_t* of sorted values // corresponding to val = major + minor*1e-9; // The function performs binary search in this sorted table. // If it finds a pair that maches val, it returns directly the // index in the table, otherwise it returns -1. // // See also GetEntryNumberWithBestIndex if (fN == 0) return -1; Long64_t value = Long64_t(major)<<31; value += minor; Int_t i = TMath::BinarySearch(fN, fIndexValues, value); if (i < 0) return -1; if (TMath::Abs(fIndexValues[i] - value) > 1.e-10) return -1; return fIndex[i]; } //______________________________________________________________________________ TTreeFormula *TTreeIndex::GetMajorFormula() { // return a pointer to the TreeFormula corresponding to the majorname if (!fMajorFormula) fMajorFormula = new TTreeFormula("Major",fMajorName.Data(),fTree); return fMajorFormula; } //______________________________________________________________________________ TTreeFormula *TTreeIndex::GetMinorFormula() { // return a pointer to the TreeFormula corresponding to the minorname if (!fMinorFormula) fMinorFormula = new TTreeFormula("Minor",fMinorName.Data(),fTree); return fMinorFormula; } //______________________________________________________________________________ TTreeFormula *TTreeIndex::GetMajorFormulaParent(const TTree *T) { // return a pointer to the TreeFormula corresponding to the majorname in parent tree T if (!fMajorFormulaParent) fMajorFormulaParent = new TTreeFormula("MajorP",fMajorName.Data(),(TTree*)T); return fMajorFormulaParent; } //______________________________________________________________________________ TTreeFormula *TTreeIndex::GetMinorFormulaParent(const TTree *T) { // return a pointer to the TreeFormula corresponding to the minorname in parent tree T if (!fMinorFormulaParent) fMinorFormulaParent = new TTreeFormula("MinorP",fMinorName.Data(),(TTree*)T); return fMinorFormulaParent; } //______________________________________________________________________________ void TTreeIndex::Print(Option_t * option) const { // print the table with : serial number, majorname, minorname // if option = "10" print only the first 10 entries // if option = "100" print only the first 100 entries // if option = "1000" print only the first 1000 entries TString opt = option; Long64_t n = fN; if (opt.Contains("10")) n = 10; if (opt.Contains("100")) n = 100; if (opt.Contains("1000")) n = 1000; printf("\n**********************************************\n"); printf("* Index of Tree: %s/%s\n",fTree->GetName(),fTree->GetTitle()); printf("**********************************************\n"); printf("%8s : %16s : %16s\n","serial",fMajorName.Data(),fMinorName.Data()); printf("**********************************************\n"); for (Long64_t i=0;i<n;i++) { Long64_t minor = fIndexValues[i] & 0xffff; Long64_t major = fIndexValues[i]>>31; printf("%8lld : %8lld : %8lld\n",i,major,minor); } } //______________________________________________________________________________ void TTreeIndex::Streamer(TBuffer &R__b) { // Stream an object of class TTreeIndex. // Note that this Streamer should be changed to an automatic Streamer // once TStreamerInfo supports an index of type Long64_t UInt_t R__s, R__c; if (R__b.IsReading()) { Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v) { } TVirtualIndex::Streamer(R__b); fMajorName.Streamer(R__b); fMinorName.Streamer(R__b); R__b >> fN; fIndexValues = new Long64_t[fN]; R__b.ReadFastArray(fIndexValues,fN); fIndex = new Long64_t[fN]; R__b.ReadFastArray(fIndex,fN); R__b.CheckByteCount(R__s, R__c, TTreeIndex::IsA()); } else { R__c = R__b.WriteVersion(TTreeIndex::IsA(), kTRUE); TVirtualIndex::Streamer(R__b); fMajorName.Streamer(R__b); fMinorName.Streamer(R__b); R__b << fN; R__b.WriteFastArray(fIndexValues, fN); R__b.WriteFastArray(fIndex, fN); R__b.SetByteCount(R__c, kTRUE); } } //______________________________________________________________________________ void TTreeIndex::SetTree(const TTree *T) { // this function is called by TChain::LoadTree and TTreePlayer::UpdateFormulaLeaves // when a new Tree is loaded. // Because Trees in a TChain may have a different list of leaves, one // must update the leaves numbers in the TTreeFormula used by the TreeIndex. fTree = (TTree*)T; if (fMajorFormula) {fMajorFormula->SetTree(fTree); fMajorFormula->UpdateFormulaLeaves();} if (fMinorFormula) {fMinorFormula->SetTree(fTree); fMinorFormula->UpdateFormulaLeaves();} if (fMajorFormulaParent) {fMajorFormulaParent->SetTree(fTree); fMajorFormulaParent->UpdateFormulaLeaves();} if (fMinorFormulaParent) {fMinorFormulaParent->SetTree(fTree); fMinorFormulaParent->UpdateFormulaLeaves();} }
Extend the functionality of TTreeIndex::GetEntryNumberFriend to support additional cases like a Tree Index in the friend disconnected from the parent Tree. Add more comments in this key function explaining the steps and decisions.
Extend the functionality of TTreeIndex::GetEntryNumberFriend to support additional cases like a Tree Index in the friend disconnected from the parent Tree. Add more comments in this key function explaining the steps and decisions. git-svn-id: ecbadac9c76e8cf640a0bca86f6bd796c98521e3@9473 27541ba8-7e3a-0410-8455-c3a389f83636
C++
lgpl-2.1
dawehner/root,dawehner/root,dawehner/root,dawehner/root,bbannier/ROOT,bbannier/ROOT,dawehner/root,bbannier/ROOT,dawehner/root,bbannier/ROOT,dawehner/root,bbannier/ROOT,dawehner/root,bbannier/ROOT,bbannier/ROOT
cfbb72f812bf182b8bf87d72f9dbb2f090d424d8
daemon/timing_histogram.cc
daemon/timing_histogram.cc
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2015 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "timing_histogram.h" #include <platform/platform.h> #include <atomic> #include <sstream> #include <string> #include <cJSON.h> TimingHistogram::TimingHistogram() { reset(); } TimingHistogram::TimingHistogram(const TimingHistogram &other) { *this = other; } template <typename T> static void copy(T&dst, const T&src) { dst.store(src.load(std::memory_order_relaxed), std::memory_order_relaxed); } /** * This isn't completely accurate, but it's only called whenever we're * grabbing the stats. We don't want to create a lock in order to make * sure that "total" is in 100% sync with all of the samples.. We * don't care <em>THAT</em> much for being accurate.. */ TimingHistogram& TimingHistogram::operator=(const TimingHistogram&other) { copy(ns, other.ns); size_t idx; size_t len = usec.size(); for (idx = 0; idx < len; ++idx) { copy(usec[idx], other.usec[idx]); } len = msec.size(); for (idx = 0; idx < len; ++idx) { copy(msec[idx], other.msec[idx]); } len = halfsec.size(); for (idx = 0; idx < len; ++idx) { copy(halfsec[idx], other.halfsec[idx]); } len = wayout.size(); for (idx = 0; idx < len; ++idx) { copy(wayout[idx], other.wayout[idx]); } copy(total, other.total); return *this; } void TimingHistogram::reset(void) { ns.store(0, std::memory_order_relaxed); for(auto& us: usec) { us.store(0, std::memory_order_relaxed); } for(auto& ms: msec) { ms.store(0, std::memory_order_relaxed); } for(auto& hs: halfsec) { hs.store(0, std::memory_order_relaxed); } for (auto& wo: wayout) { wo.store(0, std::memory_order_relaxed); } total.store(0, std::memory_order_relaxed); } void TimingHistogram::add(const hrtime_t nsec) { hrtime_t us = nsec / 1000; hrtime_t ms = us / 1000; hrtime_t hs = ms / 500; if (us == 0) { ns.fetch_add(1, std::memory_order_relaxed); } else if (us < 1000) { usec[us / 10].fetch_add(1, std::memory_order_relaxed); } else if (ms < 50) { msec[ms].fetch_add(1, std::memory_order_relaxed); } else if (hs < 10) { halfsec[hs].fetch_add(1, std::memory_order_relaxed); } else { // [5-9], [10-19], [20-39], [40-79], [80-inf]. hrtime_t sec = hs / 2; if (sec < 10) { wayout[0].fetch_add(1, std::memory_order_relaxed); } else if (sec < 20) { wayout[1].fetch_add(1, std::memory_order_relaxed); } else if (sec < 40) { wayout[2].fetch_add(1, std::memory_order_relaxed); } else if (sec < 80) { wayout[3].fetch_add(1, std::memory_order_relaxed); } else { wayout[4].fetch_add(1, std::memory_order_relaxed); } } total.fetch_add(1, std::memory_order_relaxed); } std::string TimingHistogram::to_string(void) { cJSON *root = cJSON_CreateObject(); cJSON_AddNumberToObject(root, "ns", get_ns()); cJSON *array = cJSON_CreateArray(); for (auto &us : usec) { cJSON *obj = cJSON_CreateNumber(us.load(std::memory_order_relaxed)); cJSON_AddItemToArray(array, obj); } cJSON_AddItemToObject(root, "us", array); array = cJSON_CreateArray(); size_t len = msec.size(); // element 0 isn't used for (size_t ii = 1; ii < len; ii++) { cJSON *obj = cJSON_CreateNumber(get_msec(ii)); cJSON_AddItemToArray(array, obj); } cJSON_AddItemToObject(root, "ms", array); array = cJSON_CreateArray(); for (auto &hs : halfsec) { cJSON *obj = cJSON_CreateNumber(hs.load(std::memory_order_relaxed)); cJSON_AddItemToArray(array, obj); } cJSON_AddItemToObject(root, "500ms", array); cJSON_AddNumberToObject(root, "5s-9s", get_wayout(0)); cJSON_AddNumberToObject(root, "10s-19s", get_wayout(1)); cJSON_AddNumberToObject(root, "20s-39s", get_wayout(2)); cJSON_AddNumberToObject(root, "40s-79s", get_wayout(3)); cJSON_AddNumberToObject(root, "80s-inf", get_wayout(4)); // for backwards compatibility, add the old wayouts cJSON_AddNumberToObject(root, "wayout", aggregate_wayout()); char *ptr = cJSON_PrintUnformatted(root); std::string ret(ptr); cJSON_Free(ptr); return ret; } /* get functions of Timings class */ uint32_t TimingHistogram::get_ns() { return ns.load(std::memory_order_relaxed); } uint32_t TimingHistogram::get_usec(const uint8_t index) { return usec[index].load(std::memory_order_relaxed); } uint32_t TimingHistogram::get_msec(const uint8_t index) { return msec[index].load(std::memory_order_relaxed); } uint32_t TimingHistogram::get_halfsec(const uint8_t index) { return halfsec[index].load(std::memory_order_relaxed); } uint32_t TimingHistogram::get_wayout(const uint8_t index) { return wayout[index].load(std::memory_order_relaxed); } uint32_t TimingHistogram::aggregate_wayout() { uint32_t ret = 0; for (auto &wo : wayout) { ret += wo.load(std::memory_order_relaxed); } return ret; } uint32_t TimingHistogram::get_total() { return total.load(std::memory_order_relaxed); }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2015 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "timing_histogram.h" #include <platform/platform.h> #include <atomic> #include <sstream> #include <string> #include <cJSON.h> #include <cJSON_utils.h> TimingHistogram::TimingHistogram() { reset(); } TimingHistogram::TimingHistogram(const TimingHistogram &other) { *this = other; } template <typename T> static void copy(T&dst, const T&src) { dst.store(src.load(std::memory_order_relaxed), std::memory_order_relaxed); } /** * This isn't completely accurate, but it's only called whenever we're * grabbing the stats. We don't want to create a lock in order to make * sure that "total" is in 100% sync with all of the samples.. We * don't care <em>THAT</em> much for being accurate.. */ TimingHistogram& TimingHistogram::operator=(const TimingHistogram&other) { copy(ns, other.ns); size_t idx; size_t len = usec.size(); for (idx = 0; idx < len; ++idx) { copy(usec[idx], other.usec[idx]); } len = msec.size(); for (idx = 0; idx < len; ++idx) { copy(msec[idx], other.msec[idx]); } len = halfsec.size(); for (idx = 0; idx < len; ++idx) { copy(halfsec[idx], other.halfsec[idx]); } len = wayout.size(); for (idx = 0; idx < len; ++idx) { copy(wayout[idx], other.wayout[idx]); } copy(total, other.total); return *this; } void TimingHistogram::reset(void) { ns.store(0, std::memory_order_relaxed); for(auto& us: usec) { us.store(0, std::memory_order_relaxed); } for(auto& ms: msec) { ms.store(0, std::memory_order_relaxed); } for(auto& hs: halfsec) { hs.store(0, std::memory_order_relaxed); } for (auto& wo: wayout) { wo.store(0, std::memory_order_relaxed); } total.store(0, std::memory_order_relaxed); } void TimingHistogram::add(const hrtime_t nsec) { hrtime_t us = nsec / 1000; hrtime_t ms = us / 1000; hrtime_t hs = ms / 500; if (us == 0) { ns.fetch_add(1, std::memory_order_relaxed); } else if (us < 1000) { usec[us / 10].fetch_add(1, std::memory_order_relaxed); } else if (ms < 50) { msec[ms].fetch_add(1, std::memory_order_relaxed); } else if (hs < 10) { halfsec[hs].fetch_add(1, std::memory_order_relaxed); } else { // [5-9], [10-19], [20-39], [40-79], [80-inf]. hrtime_t sec = hs / 2; if (sec < 10) { wayout[0].fetch_add(1, std::memory_order_relaxed); } else if (sec < 20) { wayout[1].fetch_add(1, std::memory_order_relaxed); } else if (sec < 40) { wayout[2].fetch_add(1, std::memory_order_relaxed); } else if (sec < 80) { wayout[3].fetch_add(1, std::memory_order_relaxed); } else { wayout[4].fetch_add(1, std::memory_order_relaxed); } } total.fetch_add(1, std::memory_order_relaxed); } std::string TimingHistogram::to_string(void) { unique_cJSON_ptr json(cJSON_CreateObject()); cJSON* root = json.get(); if (root == nullptr) { throw std::bad_alloc(); } cJSON_AddNumberToObject(root, "ns", get_ns()); cJSON *array = cJSON_CreateArray(); for (auto &us : usec) { cJSON *obj = cJSON_CreateNumber(us.load(std::memory_order_relaxed)); cJSON_AddItemToArray(array, obj); } cJSON_AddItemToObject(root, "us", array); array = cJSON_CreateArray(); size_t len = msec.size(); // element 0 isn't used for (size_t ii = 1; ii < len; ii++) { cJSON *obj = cJSON_CreateNumber(get_msec(ii)); cJSON_AddItemToArray(array, obj); } cJSON_AddItemToObject(root, "ms", array); array = cJSON_CreateArray(); for (auto &hs : halfsec) { cJSON *obj = cJSON_CreateNumber(hs.load(std::memory_order_relaxed)); cJSON_AddItemToArray(array, obj); } cJSON_AddItemToObject(root, "500ms", array); cJSON_AddNumberToObject(root, "5s-9s", get_wayout(0)); cJSON_AddNumberToObject(root, "10s-19s", get_wayout(1)); cJSON_AddNumberToObject(root, "20s-39s", get_wayout(2)); cJSON_AddNumberToObject(root, "40s-79s", get_wayout(3)); cJSON_AddNumberToObject(root, "80s-inf", get_wayout(4)); // for backwards compatibility, add the old wayouts cJSON_AddNumberToObject(root, "wayout", aggregate_wayout()); char *ptr = cJSON_PrintUnformatted(root); std::string ret(ptr); cJSON_Free(ptr); return ret; } /* get functions of Timings class */ uint32_t TimingHistogram::get_ns() { return ns.load(std::memory_order_relaxed); } uint32_t TimingHistogram::get_usec(const uint8_t index) { return usec[index].load(std::memory_order_relaxed); } uint32_t TimingHistogram::get_msec(const uint8_t index) { return msec[index].load(std::memory_order_relaxed); } uint32_t TimingHistogram::get_halfsec(const uint8_t index) { return halfsec[index].load(std::memory_order_relaxed); } uint32_t TimingHistogram::get_wayout(const uint8_t index) { return wayout[index].load(std::memory_order_relaxed); } uint32_t TimingHistogram::aggregate_wayout() { uint32_t ret = 0; for (auto &wo : wayout) { ret += wo.load(std::memory_order_relaxed); } return ret; } uint32_t TimingHistogram::get_total() { return total.load(std::memory_order_relaxed); }
Fix memoryleak in subdoc_execute stat
Fix memoryleak in subdoc_execute stat Change-Id: I1dda195c87b5e8d33d059c95ed6f7fb91057820d Reviewed-on: http://review.couchbase.org/57804 Well-Formed: buildbot <[email protected]> Tested-by: buildbot <[email protected]> Reviewed-by: Dave Rigby <[email protected]>
C++
bsd-3-clause
daverigby/memcached,owendCB/memcached,couchbase/memcached,daverigby/memcached,daverigby/kv_engine,daverigby/memcached,daverigby/kv_engine,owendCB/memcached,couchbase/memcached,couchbase/memcached,daverigby/memcached,daverigby/kv_engine,daverigby/kv_engine,owendCB/memcached,couchbase/memcached,owendCB/memcached
a502592ffeae50a46506481cf93e426d5e852701
dune/stuff/grid/information.hh
dune/stuff/grid/information.hh
// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_GRID_INFORMATION_HH #define DUNE_STUFF_GRID_INFORMATION_HH #include <ostream> #include <boost/format.hpp> #include <boost/range/adaptor/reversed.hpp> #include <dune/stuff/common/disable_warnings.hh> # include <dune/grid/common/gridview.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/common/math.hh> #include <dune/stuff/grid/intersection.hh> #include <dune/stuff/common/ranges.hh> #include <dune/stuff/grid/walk.hh> #include <dune/stuff/aliases.hh> #include <dune/stuff/grid/entity.hh> namespace Dune { namespace Stuff { namespace Grid { using namespace Dune::Stuff::Common; struct Statistics { int numberOfEntities; int numberOfIntersections; int numberOfInnerIntersections; int numberOfBoundaryIntersections; double maxGridWidth; template <class GridViewType> Statistics(const GridViewType& gridView) : numberOfEntities(gridView.size(0)), numberOfIntersections(0), numberOfInnerIntersections(0) , numberOfBoundaryIntersections(0), maxGridWidth(0) { for (const auto& entity : viewRange(gridView)) { for (const auto& intIt : intersectionRange(gridView, entity)) { ++numberOfIntersections; maxGridWidth = std::max(intIt.geometry().volume(), maxGridWidth); // if we are inside the grid numberOfInnerIntersections += ( intIt.neighbor() && !intIt.boundary() ); // if we are on the boundary of the grid numberOfBoundaryIntersections += ( !intIt.neighbor() && intIt.boundary() ); } } } }; /** \brief grid statistic output to given stream */ template< class GridViewType > void printInfo(const GridViewType& gridView, std::ostream& out) { const Statistics st(gridView); out << "found " << st.numberOfEntities << " entities," << std::endl; out << "found " << st.numberOfIntersections << " intersections," << std::endl; out << " " << st.numberOfInnerIntersections << " intersections inside and" << std::endl; out << " " << st.numberOfBoundaryIntersections << " intersections on the boundary." << std::endl; out << " maxGridWidth is " << st.maxGridWidth << std::endl; } // printGridInformation /** * \attention Not optimal, does a whole grid walk! **/ template< class GridViewType > unsigned int maxNumberOfNeighbors(const GridViewType& gridView) { unsigned int maxNeighbours = 0; for (const auto& entity : viewRange(gridView)) { unsigned int neighbours = 0; for (const auto& i : intersectionRange(gridView, entity)) { ++neighbours; } maxNeighbours = std::max(maxNeighbours, neighbours); } return maxNeighbours; } // unsigned int maxNumberOfNeighbors(const GridPartType& gridPart) //! Provide min/max coordinates for all space dimensions of a GridView template< class GridViewType > struct Dimensions { static_assert(std::is_base_of<GridView<typename GridViewType::Traits>, GridViewType>::value, "GridViewType is no GridView"); typedef typename GridViewType::Grid GridType; //! automatic running min/max typedef Dune::Stuff::Common::MinMaxAvg< typename GridType::ctype > MinMaxAvgType; typedef std::array< MinMaxAvgType, GridType::dimensionworld > CoordLimitsType; typedef typename GridType::template Codim<0>::Entity EntityType; CoordLimitsType coord_limits; MinMaxAvgType entity_volume; MinMaxAvgType entity_width; //! gridwalk functor that does the actual work for \ref GridDimensions class GridDimensionsFunctor { CoordLimitsType& coord_limits_; MinMaxAvgType& entity_volume_; MinMaxAvgType& entity_width_; public: GridDimensionsFunctor(CoordLimitsType& c, MinMaxAvgType& e, MinMaxAvgType& w) : coord_limits_(c) , entity_volume_(e) , entity_width_(w) {} template< class Entity > void operator()(const Entity& ent, const int /*ent_idx*/) { const auto& geo = ent.geometry(); entity_volume_( geo.volume() ); entity_width_(entityDiameter(ent)); for (int i = 0; i < geo.corners(); ++i) { const auto& corner( geo.corner(i) ); for (size_t k = 0; k < GridType::dimensionworld; ++k) coord_limits_[k](corner[k]); } } // () }; double volumeRelation() const { return entity_volume.min() != 0.0 ? entity_volume.max() / entity_volume.min() : -1; } Dimensions(const GridViewType& gridView) { GridDimensionsFunctor f(coord_limits, entity_volume, entity_width); GridWalk< GridViewType >(gridView).walkCodim0(f); } Dimensions(const EntityType& entity) { GridDimensionsFunctor f(coord_limits, entity_volume, entity_width); f(entity, 0); } }; template <class GridType> Dimensions<typename GridType::LeafGridViewType> dimensions(const GridType& grid) { return Dimensions<typename GridType::LeafGridViewType>(grid.leafGridView()); } template <class GridViewType > Dimensions<GridViewType> dimensions(const GridViewType& gridView) { return Dimensions<GridViewType>(gridView); } template <class GridViewType> Dimensions<GridViewType> dimensions(const typename GridViewType::Grid::template Codim<0>::Entity& entity) { return Dimensions<GridViewType>(entity); } } // namespace Grid } // end of namespace Stuff } // namespace Dune template< class T > inline std::ostream& operator<<(std::ostream& s, const DSG::Dimensions< T >& d) { for (size_t k = 0; k < T::dimensionworld; ++k) { const auto& mma = d.coord_limits[k]; s << boost::format("x%d\tmin: %e\tavg: %e\tmax: %e\n") % k % mma.min() % mma.average() % mma.max(); } s << boost::format("Entity vol min: %e\tavg: %e\tmax: %e\tQout: %e") % d.entity_volume.min() % d.entity_volume.average() % d.entity_volume.max() % d.volumeRelation(); s << std::endl; return s; } // << #endif // DUNE_STUFF_GRID_INFORMATION_HH
// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_GRID_INFORMATION_HH #define DUNE_STUFF_GRID_INFORMATION_HH #include <ostream> #include <boost/format.hpp> #include <boost/range/adaptor/reversed.hpp> #include <dune/stuff/common/disable_warnings.hh> # include <dune/grid/common/gridview.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/common/math.hh> #include <dune/stuff/grid/intersection.hh> #include <dune/stuff/common/ranges.hh> #include <dune/stuff/grid/walk.hh> #include <dune/stuff/aliases.hh> #include <dune/stuff/grid/entity.hh> namespace Dune { namespace Stuff { namespace Grid { using namespace Dune::Stuff::Common; struct Statistics { int numberOfEntities; int numberOfIntersections; int numberOfInnerIntersections; int numberOfBoundaryIntersections; double maxGridWidth; template <class GridViewType> Statistics(const GridViewType& gridView) : numberOfEntities(gridView.size(0)), numberOfIntersections(0), numberOfInnerIntersections(0) , numberOfBoundaryIntersections(0), maxGridWidth(0) { for (const auto& entity : viewRange(gridView)) { for (const auto& intIt : intersectionRange(gridView, entity)) { ++numberOfIntersections; maxGridWidth = std::max(intIt.geometry().volume(), maxGridWidth); // if we are inside the grid numberOfInnerIntersections += ( intIt.neighbor() && !intIt.boundary() ); // if we are on the boundary of the grid numberOfBoundaryIntersections += ( !intIt.neighbor() && intIt.boundary() ); } } } }; /** \brief grid statistic output to given stream */ template< class GridViewType > void printInfo(const GridViewType& gridView, std::ostream& out) { const Statistics st(gridView); out << "found " << st.numberOfEntities << " entities," << std::endl; out << "found " << st.numberOfIntersections << " intersections," << std::endl; out << " " << st.numberOfInnerIntersections << " intersections inside and" << std::endl; out << " " << st.numberOfBoundaryIntersections << " intersections on the boundary." << std::endl; out << " maxGridWidth is " << st.maxGridWidth << std::endl; } // printGridInformation /** * \attention Not optimal, does a whole grid walk! **/ template< class GridViewType > unsigned int maxNumberOfNeighbors(const GridViewType& gridView) { unsigned int maxNeighbours = 0; for (const auto& entity : viewRange(gridView)) { unsigned int neighbours = 0; for (const auto& i : intersectionRange(gridView, entity)) { ++neighbours; } maxNeighbours = std::max(maxNeighbours, neighbours); } return maxNeighbours; } // unsigned int maxNumberOfNeighbors(const GridPartType& gridPart) //! Provide min/max coordinates for all space dimensions of a GridView template< class GridViewType > struct Dimensions { static_assert(std::is_base_of<GridView<typename GridViewType::Traits>, GridViewType>::value, "GridViewType is no GridView"); typedef typename GridViewType::Grid GridType; //! automatic running min/max typedef Dune::Stuff::Common::MinMaxAvg< typename GridType::ctype > MinMaxAvgType; typedef std::array< MinMaxAvgType, GridType::dimensionworld > CoordLimitsType; typedef typename GridType::template Codim<0>::Entity EntityType; CoordLimitsType coord_limits; MinMaxAvgType entity_volume; MinMaxAvgType entity_width; //! gridwalk functor that does the actual work for \ref GridDimensions class GridDimensionsFunctor { CoordLimitsType& coord_limits_; MinMaxAvgType& entity_volume_; MinMaxAvgType& entity_width_; public: GridDimensionsFunctor(CoordLimitsType& c, MinMaxAvgType& e, MinMaxAvgType& w) : coord_limits_(c) , entity_volume_(e) , entity_width_(w) {} template< class Entity > void operator()(const Entity& ent, const int /*ent_idx*/) { const auto& geo = ent.geometry(); entity_volume_( geo.volume() ); entity_width_(entityDiameter(ent)); for (int i = 0; i < geo.corners(); ++i) { const auto& corner( geo.corner(i) ); for (size_t k = 0; k < GridType::dimensionworld; ++k) coord_limits_[k](corner[k]); } } // () }; double volumeRelation() const { return entity_volume.min() != 0.0 ? entity_volume.max() / entity_volume.min() : -1; } Dimensions(const GridViewType& gridView) { GridDimensionsFunctor f(coord_limits, entity_volume, entity_width); GridWalk< GridViewType >(gridView).operator()(f); } Dimensions(const EntityType& entity) { GridDimensionsFunctor f(coord_limits, entity_volume, entity_width); f(entity, 0); } }; template <class GridType> Dimensions<typename GridType::LeafGridViewType> dimensions(const GridType& grid) { return Dimensions<typename GridType::LeafGridViewType>(grid.leafGridView()); } template <class GridViewType > Dimensions<GridViewType> dimensions(const GridViewType& gridView) { return Dimensions<GridViewType>(gridView); } template <class GridViewType> Dimensions<GridViewType> dimensions(const typename GridViewType::Grid::template Codim<0>::Entity& entity) { return Dimensions<GridViewType>(entity); } } // namespace Grid } // end of namespace Stuff } // namespace Dune template< class T > inline std::ostream& operator<<(std::ostream& s, const DSG::Dimensions< T >& d) { for (size_t k = 0; k < T::dimensionworld; ++k) { const auto& mma = d.coord_limits[k]; s << boost::format("x%d\tmin: %e\tavg: %e\tmax: %e\n") % k % mma.min() % mma.average() % mma.max(); } s << boost::format("Entity vol min: %e\tavg: %e\tmax: %e\tQout: %e") % d.entity_volume.min() % d.entity_volume.average() % d.entity_volume.max() % d.volumeRelation(); s << std::endl; return s; } // << #endif // DUNE_STUFF_GRID_INFORMATION_HH
replace deprecated method
[grid.information] replace deprecated method
C++
bsd-2-clause
renemilk/DUNE-Stuff,renemilk/DUNE-Stuff,renemilk/DUNE-Stuff
daedc223785890eeaa40f2fd89a786c20ee15861
examples/heatTransfer/read/heatRead.cpp
examples/heatTransfer/read/heatRead.cpp
/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * IO_ADIOS2.cpp * * Created on: Nov 2017 * Author: Norbert Podhorszki * */ #include <mpi.h> #include "adios2.h" #include <cstdint> #include <iomanip> #include <iostream> #include <math.h> #include <memory> #include <stdexcept> #include <string> #include <vector> #include "PrintDataStep.h" #include "ReadSettings.h" void printUsage() { std::cout << "Usage: heatRead config input output N M \n" << " config: XML config file to use\n" << " input: name of input data file/stream\n" << " output: name of output data file/stream\n" << " N: number of processes in X dimension\n" << " M: number of processes in Y dimension\n\n"; } void Compute(const std::vector<double> &Tin, std::vector<double> &Tout, std::vector<double> &dT, bool firstStep) { /* Compute dT and * copy Tin into Tout as it will be used for calculating dT in the * next step */ if (firstStep) { for (int i = 0; i < dT.size(); i++) { dT[i] = 0; Tout[i] = Tin[i]; } } else { for (int i = 0; i < dT.size(); i++) { dT[i] = Tout[i] - Tin[i]; Tout[i] = Tin[i]; } } } int main(int argc, char *argv[]) { MPI_Init(&argc, &argv); /* When writer and reader is launched together with a single mpirun command, the world comm spans all applications. We have to split and create the local 'world' communicator for the reader only. When writer and reader is launched separately, the mpiReaderComm communicator will just equal the MPI_COMM_WORLD. */ int wrank, wnproc; MPI_Comm_rank(MPI_COMM_WORLD, &wrank); MPI_Comm_size(MPI_COMM_WORLD, &wnproc); const unsigned int color = 2; MPI_Comm mpiReaderComm; MPI_Comm_split(MPI_COMM_WORLD, color, wrank, &mpiReaderComm); int rank, nproc; MPI_Comm_rank(mpiReaderComm, &rank); MPI_Comm_size(mpiReaderComm, &nproc); try { ReadSettings settings(argc, argv, rank, nproc); adios2::ADIOS ad(settings.configfile, mpiReaderComm, adios2::DebugON); // Define method for engine creation // 1. Get method def from config file or define new one adios2::IO inIO = ad.DeclareIO("readerInput"); if (!inIO.InConfigFile()) { // if not defined by user, we can change the default settings // BPFile is the default engine inIO.SetEngine("BPFile"); inIO.SetParameters({{"num_threads", "1"}}); // ISO-POSIX file output is the default transport (called "File") // Passing parameters to the transport inIO.AddTransport("File", {{"verbose", "4"}}); } adios2::IO outIO = ad.DeclareIO("readerOutput"); adios2::Engine reader = inIO.Open(settings.inputfile, adios2::Mode::Read, mpiReaderComm); std::vector<double> Tin; std::vector<double> Tout; std::vector<double> dT; adios2::Variable<double> vTin; adios2::Variable<double> vTout; adios2::Variable<double> vdT; adios2::Engine writer; bool firstStep = true; int step = 0; while (true) { adios2::StepStatus status = reader.BeginStep(adios2::StepMode::NextAvailable, 0.0f); if (status != adios2::StepStatus::OK) { break; } // Variable objects disappear between steps so we need this every // step vTin = inIO.InquireVariable<double>("T"); if (!vTin) { std::cout << "Error: NO variable T found. Unable to proceed. " "Exiting. " << std::endl; break; } if (firstStep) { unsigned int gndx = vTin.Shape()[0]; unsigned int gndy = vTin.Shape()[1]; if (rank == 0) { std::cout << "gndx = " << gndx << std::endl; std::cout << "gndy = " << gndy << std::endl; } settings.DecomposeArray(gndx, gndy); Tin.resize(settings.readsize[0] * settings.readsize[1]); Tout.resize(settings.readsize[0] * settings.readsize[1]); dT.resize(settings.readsize[0] * settings.readsize[1]); /* Create output variables and open output stream */ vTout = outIO.DefineVariable<double>( "T", {gndx, gndy}, settings.offset, settings.readsize); vdT = outIO.DefineVariable<double>( "dT", {gndx, gndy}, settings.offset, settings.readsize); writer = outIO.Open(settings.outputfile, adios2::Mode::Write, mpiReaderComm); MPI_Barrier(mpiReaderComm); // sync processes just for stdout } if (!rank) { std::cout << "Processing step " << step << std::endl; } // Create a 2D selection for the subset vTin.SetSelection( adios2::Box<adios2::Dims>(settings.offset, settings.readsize)); // Arrays are read by scheduling one or more of them // and performing the reads at once reader.Get<double>(vTin, Tin.data()); /*printDataStep(Tin.data(), settings.readsize.data(), settings.offset.data(), rank, step); */ reader.EndStep(); /* Compute dT from current T (Tin) and previous T (Tout) * and save Tin in Tout for output and for future computation */ Compute(Tin, Tout, dT, firstStep); /* Output Tout and dT */ writer.BeginStep(); if (vTout) writer.Put<double>(vTout, Tout.data()); if (vdT) writer.Put<double>(vdT, dT.data()); writer.EndStep(); step++; firstStep = false; } reader.Close(); if (writer) writer.Close(); } catch (std::invalid_argument &e) // command-line argument errors { std::cout << e.what() << std::endl; printUsage(); } MPI_Finalize(); return 0; }
/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * IO_ADIOS2.cpp * * Created on: Nov 2017 * Author: Norbert Podhorszki * */ #include <mpi.h> #include "adios2.h" #include <cstdint> #include <iomanip> #include <iostream> #include <math.h> #include <memory> #include <stdexcept> #include <string> #include <vector> #include "PrintDataStep.h" #include "ReadSettings.h" void printUsage() { std::cout << "Usage: heatRead config input output N M \n" << " config: XML config file to use\n" << " input: name of input data file/stream\n" << " output: name of output data file/stream\n" << " N: number of processes in X dimension\n" << " M: number of processes in Y dimension\n\n"; } void Compute(const std::vector<double> &Tin, std::vector<double> &Tout, std::vector<double> &dT, bool firstStep) { /* Compute dT and * copy Tin into Tout as it will be used for calculating dT in the * next step */ if (firstStep) { for (int i = 0; i < dT.size(); i++) { dT[i] = 0; Tout[i] = Tin[i]; } } else { for (int i = 0; i < dT.size(); i++) { dT[i] = Tout[i] - Tin[i]; Tout[i] = Tin[i]; } } } int main(int argc, char *argv[]) { MPI_Init(&argc, &argv); /* When writer and reader is launched together with a single mpirun command, the world comm spans all applications. We have to split and create the local 'world' communicator for the reader only. When writer and reader is launched separately, the mpiReaderComm communicator will just equal the MPI_COMM_WORLD. */ int wrank, wnproc; MPI_Comm_rank(MPI_COMM_WORLD, &wrank); MPI_Comm_size(MPI_COMM_WORLD, &wnproc); const unsigned int color = 2; MPI_Comm mpiReaderComm; MPI_Comm_split(MPI_COMM_WORLD, color, wrank, &mpiReaderComm); int rank, nproc; MPI_Comm_rank(mpiReaderComm, &rank); MPI_Comm_size(mpiReaderComm, &nproc); try { ReadSettings settings(argc, argv, rank, nproc); adios2::ADIOS ad(settings.configfile, mpiReaderComm, adios2::DebugON); // Define method for engine creation // 1. Get method def from config file or define new one adios2::IO inIO = ad.DeclareIO("readerInput"); if (!inIO.InConfigFile()) { // if not defined by user, we can change the default settings // BPFile is the default engine inIO.SetEngine("BPFile"); inIO.SetParameters({{"num_threads", "1"}}); // ISO-POSIX file output is the default transport (called "File") // Passing parameters to the transport inIO.AddTransport("File", {{"verbose", "4"}}); } adios2::IO outIO = ad.DeclareIO("readerOutput"); adios2::Engine reader = inIO.Open(settings.inputfile, adios2::Mode::Read, mpiReaderComm); reader.FixedSchedule(); std::vector<double> Tin; std::vector<double> Tout; std::vector<double> dT; adios2::Variable<double> vTin; adios2::Variable<double> vTout; adios2::Variable<double> vdT; adios2::Engine writer; bool firstStep = true; int step = 0; while (true) { adios2::StepStatus status = reader.BeginStep(adios2::StepMode::NextAvailable, 0.0f); if (status != adios2::StepStatus::OK) { break; } // Variable objects disappear between steps so we need this every // step vTin = inIO.InquireVariable<double>("T"); if (!vTin) { std::cout << "Error: NO variable T found. Unable to proceed. " "Exiting. " << std::endl; break; } if (firstStep) { unsigned int gndx = vTin.Shape()[0]; unsigned int gndy = vTin.Shape()[1]; if (rank == 0) { std::cout << "gndx = " << gndx << std::endl; std::cout << "gndy = " << gndy << std::endl; } settings.DecomposeArray(gndx, gndy); Tin.resize(settings.readsize[0] * settings.readsize[1]); Tout.resize(settings.readsize[0] * settings.readsize[1]); dT.resize(settings.readsize[0] * settings.readsize[1]); /* Create output variables and open output stream */ vTout = outIO.DefineVariable<double>( "T", {gndx, gndy}, settings.offset, settings.readsize); vdT = outIO.DefineVariable<double>( "dT", {gndx, gndy}, settings.offset, settings.readsize); writer = outIO.Open(settings.outputfile, adios2::Mode::Write, mpiReaderComm); MPI_Barrier(mpiReaderComm); // sync processes just for stdout } if (!rank) { std::cout << "Processing step " << step << std::endl; } // Create a 2D selection for the subset vTin.SetSelection( adios2::Box<adios2::Dims>(settings.offset, settings.readsize)); // Arrays are read by scheduling one or more of them // and performing the reads at once reader.Get<double>(vTin, Tin.data()); /*printDataStep(Tin.data(), settings.readsize.data(), settings.offset.data(), rank, step); */ reader.EndStep(); /* Compute dT from current T (Tin) and previous T (Tout) * and save Tin in Tout for output and for future computation */ Compute(Tin, Tout, dT, firstStep); /* Output Tout and dT */ writer.BeginStep(); if (vTout) writer.Put<double>(vTout, Tout.data()); if (vdT) writer.Put<double>(vdT, dT.data()); writer.EndStep(); step++; firstStep = false; } reader.Close(); if (writer) writer.Close(); } catch (std::invalid_argument &e) // command-line argument errors { std::cout << e.what() << std::endl; printUsage(); } MPI_Finalize(); return 0; }
Fix reader schedule too
Fix reader schedule too
C++
apache-2.0
JasonRuonanWang/ADIOS2,JasonRuonanWang/ADIOS2,JasonRuonanWang/ADIOS2,ornladios/ADIOS2,JasonRuonanWang/ADIOS2,JasonRuonanWang/ADIOS2,ornladios/ADIOS2,ornladios/ADIOS2,ornladios/ADIOS2,ornladios/ADIOS2
c71fab7465ed96758f5ad46482547dfaa75b236d
examples/src/system_information_example.cpp
examples/src/system_information_example.cpp
#include <cstdio> #include <iostream> #include "utility.hpp" // Inludes common necessary includes for development using depthai library #include "depthai/depthai.hpp" void printSystemInformation(dai::SystemInformation); int main() { using namespace std; dai::Pipeline pipeline; auto sysLog = pipeline.create<dai::node::SystemLogger>(); auto xout = pipeline.create<dai::node::XLinkOut>(); // properties sysLog->setRate(1.0f); // 1 hz updates xout->setStreamName("sysinfo"); // links sysLog->out.link(xout->input); // Connect to device dai::Device device; // Start pipeline device.startPipeline(pipeline); // Create 'sysinfo' queue auto queue = device.getOutputQueue("sysinfo"); // Query device (before pipeline starts) dai::MemoryInfo ddr = device.getDdrMemoryUsage(); printf("Ddr used / total - %.2f / %.2f MiB\n", ddr.used / (1024.0f * 1024.0f), ddr.total / (1024.0f * 1024.0f)); dai::MemoryInfo cmx = device.getCmxMemoryUsage(); printf("Cmx used / total - %.2f / %.2f MiB\n", cmx.used / (1024.0f * 1024.0f), cmx.total / (1024.0f * 1024.0f)); while(1) { auto sysInfo = queue->get<dai::SystemInformation>(); printSystemInformation(*sysInfo); } } void printSystemInformation(dai::SystemInformation info) { printf("Ddr used / total - %.2f / %.2f MiB\n", info.ddrMemoryUsage.used / (1024.0f * 1024.0f), info.ddrMemoryUsage.total / (1024.0f * 1024.0f)); printf("Cmx used / total - %.2f / %.2f MiB\n", info.cmxMemoryUsage.used / (1024.0f * 1024.0f), info.cmxMemoryUsage.total / (1024.0f * 1024.0f)); printf("LeonCss heap used / total - %.2f / %.2f MiB\n", info.leonCssMemoryUsage.used / (1024.0f * 1024.0f), info.leonCssMemoryUsage.total / (1024.0f * 1024.0f)); printf("LeonMss heap used / total - %.2f / %.2f MiB\n", info.leonMssMemoryUsage.used / (1024.0f * 1024.0f), info.leonMssMemoryUsage.total / (1024.0f * 1024.0f)); const auto& t = info.chipTemperature; printf("Chip temperature - average: %.2f, css: %.2f, mss: %.2f, upa0: %.2f, upa1: %.2f\n", t.average, t.css, t.mss, t.upa, t.dss); printf("Cpu usage - Leon OS: %.2f %%, Leon RT: %.2f %%\n", info.leonCssCpuUsage.average * 100, info.leonMssCpuUsage.average * 100); }
#include <cstdio> #include <iostream> #include "utility.hpp" // Inludes common necessary includes for development using depthai library #include "depthai/depthai.hpp" void printSystemInformation(dai::SystemInformation); int main() { using namespace std; dai::Pipeline pipeline; auto sysLog = pipeline.create<dai::node::SystemLogger>(); auto xout = pipeline.create<dai::node::XLinkOut>(); // properties sysLog->setRate(1.0f); // 1 hz updates xout->setStreamName("sysinfo"); // links sysLog->out.link(xout->input); // Connect to device dai::Device device; // Query device (before pipeline starts) dai::MemoryInfo ddr = device.getDdrMemoryUsage(); printf("Ddr used / total - %.2f / %.2f MiB\n", ddr.used / (1024.0f * 1024.0f), ddr.total / (1024.0f * 1024.0f)); dai::MemoryInfo cmx = device.getCmxMemoryUsage(); printf("Cmx used / total - %.2f / %.2f MiB\n", cmx.used / (1024.0f * 1024.0f), cmx.total / (1024.0f * 1024.0f)); // Start pipeline device.startPipeline(pipeline); // Create 'sysinfo' queue auto queue = device.getOutputQueue("sysinfo"); while(1) { auto sysInfo = queue->get<dai::SystemInformation>(); printSystemInformation(*sysInfo); } } void printSystemInformation(dai::SystemInformation info) { printf("Ddr used / total - %.2f / %.2f MiB\n", info.ddrMemoryUsage.used / (1024.0f * 1024.0f), info.ddrMemoryUsage.total / (1024.0f * 1024.0f)); printf("Cmx used / total - %.2f / %.2f MiB\n", info.cmxMemoryUsage.used / (1024.0f * 1024.0f), info.cmxMemoryUsage.total / (1024.0f * 1024.0f)); printf("LeonCss heap used / total - %.2f / %.2f MiB\n", info.leonCssMemoryUsage.used / (1024.0f * 1024.0f), info.leonCssMemoryUsage.total / (1024.0f * 1024.0f)); printf("LeonMss heap used / total - %.2f / %.2f MiB\n", info.leonMssMemoryUsage.used / (1024.0f * 1024.0f), info.leonMssMemoryUsage.total / (1024.0f * 1024.0f)); const auto& t = info.chipTemperature; printf("Chip temperature - average: %.2f, css: %.2f, mss: %.2f, upa0: %.2f, upa1: %.2f\n", t.average, t.css, t.mss, t.upa, t.dss); printf("Cpu usage - Leon OS: %.2f %%, Leon RT: %.2f %%\n", info.leonCssCpuUsage.average * 100, info.leonMssCpuUsage.average * 100); }
Move queue init after pipeline start in system information example
Move queue init after pipeline start in system information example
C++
mit
luxonis/depthai-core,luxonis/depthai-core,luxonis/depthai-core
8070f78451ce8c33bcac19e6261aaefa2dc260c6
content/renderer/media/android/media_info_loader.cc
content/renderer/media/android/media_info_loader.cc
// Copyright 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 "content/renderer/media/android/media_info_loader.h" #include "base/bits.h" #include "base/callback_helpers.h" #include "base/metrics/histogram.h" #include "third_party/WebKit/public/platform/WebURLError.h" #include "third_party/WebKit/public/platform/WebURLLoader.h" #include "third_party/WebKit/public/platform/WebURLResponse.h" #include "third_party/WebKit/public/web/WebFrame.h" using WebKit::WebFrame; using WebKit::WebURLError; using WebKit::WebURLLoader; using WebKit::WebURLLoaderOptions; using WebKit::WebURLRequest; using WebKit::WebURLResponse; using webkit_media::ActiveLoader; namespace content { static const int kHttpOK = 200; MediaInfoLoader::MediaInfoLoader( const GURL& url, WebKit::WebMediaPlayer::CORSMode cors_mode, const ReadyCB& ready_cb) : loader_failed_(false), url_(url), cors_mode_(cors_mode), single_origin_(true), ready_cb_(ready_cb) {} MediaInfoLoader::~MediaInfoLoader() {} void MediaInfoLoader::Start(WebKit::WebFrame* frame) { // Make sure we have not started. DCHECK(!ready_cb_.is_null()); CHECK(frame); start_time_ = base::TimeTicks::Now(); // Prepare the request. WebURLRequest request(url_); request.setTargetType(WebURLRequest::TargetIsMedia); frame->setReferrerForRequest(request, WebKit::WebURL()); scoped_ptr<WebURLLoader> loader; if (test_loader_) { loader = test_loader_.Pass(); } else { WebURLLoaderOptions options; if (cors_mode_ == WebKit::WebMediaPlayer::CORSModeUnspecified) { options.allowCredentials = true; options.crossOriginRequestPolicy = WebURLLoaderOptions::CrossOriginRequestPolicyAllow; } else { options.exposeAllResponseHeaders = true; options.crossOriginRequestPolicy = WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl; if (cors_mode_ == WebKit::WebMediaPlayer::CORSModeUseCredentials) options.allowCredentials = true; } loader.reset(frame->createAssociatedURLLoader(options)); } // Start the resource loading. loader->loadAsynchronously(request, this); active_loader_.reset(new ActiveLoader(loader.Pass())); } ///////////////////////////////////////////////////////////////////////////// // WebKit::WebURLLoaderClient implementation. void MediaInfoLoader::willSendRequest( WebURLLoader* loader, WebURLRequest& newRequest, const WebURLResponse& redirectResponse) { // The load may have been stopped and |ready_cb| is destroyed. // In this case we shouldn't do anything. if (ready_cb_.is_null()) { // Set the url in the request to an invalid value (empty url). newRequest.setURL(WebKit::WebURL()); return; } // Only allow |single_origin_| if we haven't seen a different origin yet. if (single_origin_) single_origin_ = url_.GetOrigin() == GURL(newRequest.url()).GetOrigin(); url_ = newRequest.url(); } void MediaInfoLoader::didSendData( WebURLLoader* loader, unsigned long long bytes_sent, unsigned long long total_bytes_to_be_sent) { NOTIMPLEMENTED(); } void MediaInfoLoader::didReceiveResponse( WebURLLoader* loader, const WebURLResponse& response) { DVLOG(1) << "didReceiveResponse: HTTP/" << (response.httpVersion() == WebURLResponse::HTTP_0_9 ? "0.9" : response.httpVersion() == WebURLResponse::HTTP_1_0 ? "1.0" : response.httpVersion() == WebURLResponse::HTTP_1_1 ? "1.1" : "Unknown") << " " << response.httpStatusCode(); DCHECK(active_loader_.get()); if (response.httpStatusCode() == kHttpOK) { DidBecomeReady(kOk); return; } loader_failed_ = true; DidBecomeReady(kFailed); } void MediaInfoLoader::didReceiveData( WebURLLoader* loader, const char* data, int data_length, int encoded_data_length) { // Ignored. } void MediaInfoLoader::didDownloadData( WebKit::WebURLLoader* loader, int dataLength) { NOTIMPLEMENTED(); } void MediaInfoLoader::didReceiveCachedMetadata( WebURLLoader* loader, const char* data, int data_length) { NOTIMPLEMENTED(); } void MediaInfoLoader::didFinishLoading( WebURLLoader* loader, double finishTime) { DCHECK(active_loader_.get()); DidBecomeReady(kOk); } void MediaInfoLoader::didFail( WebURLLoader* loader, const WebURLError& error) { DVLOG(1) << "didFail: reason=" << error.reason << ", isCancellation=" << error.isCancellation << ", domain=" << error.domain.utf8().data() << ", localizedDescription=" << error.localizedDescription.utf8().data(); DCHECK(active_loader_.get()); loader_failed_ = true; DidBecomeReady(kFailed); } bool MediaInfoLoader::HasSingleOrigin() const { DCHECK(ready_cb_.is_null()) << "Must become ready before calling HasSingleOrigin()"; return single_origin_; } bool MediaInfoLoader::DidPassCORSAccessCheck() const { DCHECK(ready_cb_.is_null()) << "Must become ready before calling DidPassCORSAccessCheck()"; return !loader_failed_ && cors_mode_ != WebKit::WebMediaPlayer::CORSModeUnspecified; } ///////////////////////////////////////////////////////////////////////////// // Helper methods. void MediaInfoLoader::DidBecomeReady(Status status) { UMA_HISTOGRAM_TIMES("Media.InfoLoadDelay", base::TimeTicks::Now() - start_time_); active_loader_.reset(); if (!ready_cb_.is_null()) base::ResetAndReturn(&ready_cb_).Run(status); } } // namespace content
// Copyright 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 "content/renderer/media/android/media_info_loader.h" #include "base/bits.h" #include "base/callback_helpers.h" #include "base/metrics/histogram.h" #include "third_party/WebKit/public/platform/WebURLError.h" #include "third_party/WebKit/public/platform/WebURLLoader.h" #include "third_party/WebKit/public/platform/WebURLResponse.h" #include "third_party/WebKit/public/web/WebFrame.h" using WebKit::WebFrame; using WebKit::WebURLError; using WebKit::WebURLLoader; using WebKit::WebURLLoaderOptions; using WebKit::WebURLRequest; using WebKit::WebURLResponse; using webkit_media::ActiveLoader; namespace content { static const int kHttpOK = 200; MediaInfoLoader::MediaInfoLoader( const GURL& url, WebKit::WebMediaPlayer::CORSMode cors_mode, const ReadyCB& ready_cb) : loader_failed_(false), url_(url), cors_mode_(cors_mode), single_origin_(true), ready_cb_(ready_cb) {} MediaInfoLoader::~MediaInfoLoader() {} void MediaInfoLoader::Start(WebKit::WebFrame* frame) { // Make sure we have not started. DCHECK(!ready_cb_.is_null()); CHECK(frame); start_time_ = base::TimeTicks::Now(); // Prepare the request. WebURLRequest request(url_); request.setTargetType(WebURLRequest::TargetIsMedia); frame->setReferrerForRequest(request, WebKit::WebURL()); scoped_ptr<WebURLLoader> loader; if (test_loader_) { loader = test_loader_.Pass(); } else { WebURLLoaderOptions options; if (cors_mode_ == WebKit::WebMediaPlayer::CORSModeUnspecified) { options.allowCredentials = true; options.crossOriginRequestPolicy = WebURLLoaderOptions::CrossOriginRequestPolicyAllow; } else { options.exposeAllResponseHeaders = true; options.crossOriginRequestPolicy = WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl; if (cors_mode_ == WebKit::WebMediaPlayer::CORSModeUseCredentials) options.allowCredentials = true; } loader.reset(frame->createAssociatedURLLoader(options)); } // Start the resource loading. loader->loadAsynchronously(request, this); active_loader_.reset(new ActiveLoader(loader.Pass())); } ///////////////////////////////////////////////////////////////////////////// // WebKit::WebURLLoaderClient implementation. void MediaInfoLoader::willSendRequest( WebURLLoader* loader, WebURLRequest& newRequest, const WebURLResponse& redirectResponse) { // The load may have been stopped and |ready_cb| is destroyed. // In this case we shouldn't do anything. if (ready_cb_.is_null()) { // Set the url in the request to an invalid value (empty url). newRequest.setURL(WebKit::WebURL()); return; } // Only allow |single_origin_| if we haven't seen a different origin yet. if (single_origin_) single_origin_ = url_.GetOrigin() == GURL(newRequest.url()).GetOrigin(); url_ = newRequest.url(); } void MediaInfoLoader::didSendData( WebURLLoader* loader, unsigned long long bytes_sent, unsigned long long total_bytes_to_be_sent) { NOTIMPLEMENTED(); } void MediaInfoLoader::didReceiveResponse( WebURLLoader* loader, const WebURLResponse& response) { DVLOG(1) << "didReceiveResponse: HTTP/" << (response.httpVersion() == WebURLResponse::HTTP_0_9 ? "0.9" : response.httpVersion() == WebURLResponse::HTTP_1_0 ? "1.0" : response.httpVersion() == WebURLResponse::HTTP_1_1 ? "1.1" : "Unknown") << " " << response.httpStatusCode(); DCHECK(active_loader_.get()); if (response.httpStatusCode() == kHttpOK || url_.SchemeIsFile()) { DidBecomeReady(kOk); return; } loader_failed_ = true; DidBecomeReady(kFailed); } void MediaInfoLoader::didReceiveData( WebURLLoader* loader, const char* data, int data_length, int encoded_data_length) { // Ignored. } void MediaInfoLoader::didDownloadData( WebKit::WebURLLoader* loader, int dataLength) { NOTIMPLEMENTED(); } void MediaInfoLoader::didReceiveCachedMetadata( WebURLLoader* loader, const char* data, int data_length) { NOTIMPLEMENTED(); } void MediaInfoLoader::didFinishLoading( WebURLLoader* loader, double finishTime) { DCHECK(active_loader_.get()); DidBecomeReady(kOk); } void MediaInfoLoader::didFail( WebURLLoader* loader, const WebURLError& error) { DVLOG(1) << "didFail: reason=" << error.reason << ", isCancellation=" << error.isCancellation << ", domain=" << error.domain.utf8().data() << ", localizedDescription=" << error.localizedDescription.utf8().data(); DCHECK(active_loader_.get()); loader_failed_ = true; DidBecomeReady(kFailed); } bool MediaInfoLoader::HasSingleOrigin() const { DCHECK(ready_cb_.is_null()) << "Must become ready before calling HasSingleOrigin()"; return single_origin_; } bool MediaInfoLoader::DidPassCORSAccessCheck() const { DCHECK(ready_cb_.is_null()) << "Must become ready before calling DidPassCORSAccessCheck()"; return !loader_failed_ && cors_mode_ != WebKit::WebMediaPlayer::CORSModeUnspecified; } ///////////////////////////////////////////////////////////////////////////// // Helper methods. void MediaInfoLoader::DidBecomeReady(Status status) { UMA_HISTOGRAM_TIMES("Media.InfoLoadDelay", base::TimeTicks::Now() - start_time_); active_loader_.reset(); if (!ready_cb_.is_null()) base::ResetAndReturn(&ready_cb_).Run(status); } } // namespace content
Fix the issue of ContentShell can't play video with file scheme.
Fix the issue of ContentShell can't play video with file scheme. MediaInfoLoader checks single security origin and CROS access, but for media resources with file protocol, it always returns false, which disables local video playback. BUG=234710 TEST=video with file protocol Review URL: https://chromiumcodereview.appspot.com/19324002 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@211967 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk
d8a214444f94c42ac5346866da14ef5e5d2573c3
cpp/src/RoundRobinCodisPool.cpp
cpp/src/RoundRobinCodisPool.cpp
#include "RoundRobinCodisPool.h" #include "Log.h" #include "json/json.h" #include "ScopedLock.h" using namespace bfd::codis; RoundRobinCodisPool::RoundRobinCodisPool(const string& zookeeperAddr, const string& proxyPath, const string& businessID) :m_Zh(NULL), m_ZookeeperAddr(zookeeperAddr), m_ProxyPath(proxyPath),m_Mutex(PTHREAD_MUTEX_INITIALIZER), proxyIndex(-1),m_BusinessID(businessID) { m_Zh = zookeeper_init(zookeeperAddr.c_str(), proxy_watcher, 10000, NULL, this, 0); int cnt = 0; while (zoo_state(m_Zh)!=ZOO_CONNECTED_STATE && cnt<10000) { usleep(30000); cnt++; } if (cnt == 10000) { LOG(ERROR, "connect zookeeper error! zookeeperAddr="+zookeeperAddr); exit(1); } Init(m_Zh, proxyPath); } RoundRobinCodisPool::~RoundRobinCodisPool() { ScopedLock lock(m_Mutex); for (size_t i=0; i<m_Proxys.size(); i++) { if (m_Proxys[i] != NULL) { delete m_Proxys[i]; m_Proxys[i] = NULL; } } } CodisClient* RoundRobinCodisPool::GetProxy() { int index = -1; ScopedLock lock(m_Mutex); { index = ++proxyIndex; if (proxyIndex >= m_Proxys.size()) { proxyIndex = 0; index = 0; } if (m_Proxys.size() == 0) { index = -1; proxyIndex = -1; } //} if (index == -1) { return NULL; } else { return m_Proxys[index]; } } } void RoundRobinCodisPool::Init(zhandle_t *(&zh), const string& proxyPath) { vector<pair<string, int> > proxyInfos; proxyInfos = GetProxyInfos(m_Zh, proxyPath); if (proxyInfos.size() == 0) { LOG(ERROR, "no proxy can be used!"); exit(1); } InitProxyConns(proxyInfos); } vector<pair<string, int> > RoundRobinCodisPool::GetProxyInfos(zhandle_t *(&zh), const string& proxyPath) { vector<pair<string, int> > proxys; struct String_vector strings; int rc0 = zoo_get_children(zh, proxyPath.c_str(),1, &strings); if (rc0 != ZOK) { stringstream stream; stream << "get children from %s faild!!!\n proxypath=" << proxyPath; LOG(ERROR, stream.str()); exit(1); } char **pstr = strings.data; ostringstream sentinel_addr_oss; vector<string> proxyNameVec; for (int i=0; i<strings.count; ++i, ++pstr) { Json::Reader reader; Json::Value state; stringstream proxyFullPath; proxyFullPath << proxyPath << "/" << *pstr; string node_data = ZkGet(zh, proxyFullPath.str()); if (!reader.parse(node_data.c_str(), state, false)) { stringstream stream; stream << "data format json is faild [path: " << proxyFullPath << "][data:" << node_data << "]\n"; LOG(ERROR, stream.str()); continue; } if (state.isMember("state") && state["state"].isString() && state["state"].asString() == string("online")) { if (state.isMember("addr") && state["addr"].isString()) { string ipport = state["addr"].asString(); vector<string> proxyinfo = split(ipport, ':'); if (proxyinfo.size()>1) { int port = atoi(proxyinfo[1].c_str()); proxys.push_back(make_pair(proxyinfo[0], port)); } } } else { stringstream stream; stream << "get proxy state faild [path: " << proxyFullPath << "][data:" << state.toStyledString() << "]\n"; LOG(ERROR, stream.str()); } } return proxys; } void RoundRobinCodisPool::InitProxyConns(const vector<pair<string, int> >& proxyInfos) { vector<CodisClient*> proxys; for (size_t i=0; i<proxyInfos.size(); i++) { CodisClient *proxy = new CodisClient(proxyInfos[i].first, proxyInfos[i].second, m_BusinessID); proxys.push_back(proxy); } { ScopedLock lock(m_Mutex); m_Proxys.swap(proxys); m_ProxyInfos = proxyInfos; } for (size_t i=0; i<proxys.size(); i++) { if (proxys[i] != NULL) { delete proxys[i]; proxys[i] = NULL; } } } string RoundRobinCodisPool::ZkGet(zhandle_t *(&zh), const string &path, bool watch) { char * buffer = NULL; Stat stat; int buf_len = 0; int rc; rc = zoo_get(zh, path.c_str(), 0, NULL, &buf_len, &stat); if (rc != ZOK) { LOG(ERROR, string("getting zk node stats failed:")+zerror(rc)); return ""; } buffer = (char*)malloc(sizeof(char) * (stat.dataLength+1)); buf_len = stat.dataLength + 1; rc = zoo_get(zh, path.c_str(), watch, buffer, &buf_len, NULL); if (rc != ZOK) { LOG(ERROR, string("getting zk node stats failed:")+zerror(rc)); if (buffer != NULL) { free(buffer); buffer = NULL; } return ""; } string return_str = buffer; if (buffer != NULL) { free(buffer); buffer = NULL; } return return_str; } void RoundRobinCodisPool::proxy_watcher(zhandle_t *zh, int type, int state, const char *path, void *context) { stringstream stream; stream << "zkevent type=" << type << "stats=" << state; LOG(INFO, stream.str()); RoundRobinCodisPool* ptr = reinterpret_cast<RoundRobinCodisPool*>(context); if ((type==ZOO_SESSION_EVENT) && (state==ZOO_CONNECTING_STATE)) { zookeeper_close(ptr->m_Zh); ptr->m_Zh = zookeeper_init(ptr->m_ZookeeperAddr.c_str(), proxy_watcher, 10000, NULL, context, 0); int cnt = 0; while (zoo_state(ptr->m_Zh)!=ZOO_CONNECTED_STATE && cnt<10000) { usleep(30000); cnt++; } if (cnt == 10000) { LOG(ERROR, "connect zookeeper error! zookeeperAddr="+ptr->m_ZookeeperAddr); exit(1); } ptr->Init(ptr->m_Zh, ptr->m_ProxyPath); } else if ((type==ZOO_SESSION_EVENT) && (state==ZOO_EXPIRED_SESSION_STATE)) { zookeeper_close(ptr->m_Zh); ptr->m_Zh = zookeeper_init(ptr->m_ZookeeperAddr.c_str(), proxy_watcher, 10000, NULL, context, 0); int cnt = 0; while (zoo_state(ptr->m_Zh)!=ZOO_CONNECTED_STATE && cnt<10000) { usleep(30000); cnt++; } if (cnt == 10000) { LOG(ERROR, "connect zookeeper error! zookeeperAddr="+ptr->m_ZookeeperAddr); exit(1); } ptr->Init(ptr->m_Zh, ptr->m_ProxyPath); } else if ((type==ZOO_SESSION_EVENT) && (state==ZOO_CONNECTED_STATE)) { } else if ((state==ZOO_CONNECTED_STATE) && (type==ZOO_CHANGED_EVENT)) { //ptr->Init(ptr->m_Zh, ptr->m_ProxyPath); } else if ((state==ZOO_CONNECTED_STATE) && (type==ZOO_DELETED_EVENT)) { //ptr->Init(ptr->m_Zh, ptr->m_ProxyPath); } else if ((state==ZOO_CONNECTED_STATE) && (type==ZOO_CHILD_EVENT)) { sleep(5); ptr->Init(ptr->m_Zh, ptr->m_ProxyPath); } else if ((state==ZOO_CONNECTED_STATE) && (type==ZOO_CREATED_EVENT)) { //ptr->Init(ptr->m_Zh, ptr->m_ProxyPath); } else { LOG(ERROR, "zookeeper connection state changed but not implemented"); } }
#include "RoundRobinCodisPool.h" #include "Log.h" #include "json/json.h" #include "ScopedLock.h" using namespace bfd::codis; RoundRobinCodisPool::RoundRobinCodisPool(const string& zookeeperAddr, const string& proxyPath, const string& businessID) :m_Zh(NULL), m_ZookeeperAddr(zookeeperAddr), m_ProxyPath(proxyPath),m_Mutex(PTHREAD_MUTEX_INITIALIZER), proxyIndex(-1),m_BusinessID(businessID) { m_Zh = zookeeper_init(zookeeperAddr.c_str(), proxy_watcher, 10000, NULL, this, 0); int cnt = 0; while (zoo_state(m_Zh)!=ZOO_CONNECTED_STATE && cnt<10000) { usleep(30000); cnt++; } if (cnt == 10000) { LOG(ERROR, "connect zookeeper error! zookeeperAddr="+zookeeperAddr); exit(1); } Init(m_Zh, proxyPath); } RoundRobinCodisPool::~RoundRobinCodisPool() { ScopedLock lock(m_Mutex); for (size_t i=0; i<m_Proxys.size(); i++) { if (m_Proxys[i] != NULL) { delete m_Proxys[i]; m_Proxys[i] = NULL; } } } CodisClient* RoundRobinCodisPool::GetProxy() { ScopedLock lock(m_Mutex); int idx = ++proxyIndex % m_Proxys.size(); return m_Proxys[idx]; } void RoundRobinCodisPool::Init(zhandle_t *(&zh), const string& proxyPath) { vector<pair<string, int> > proxyInfos; proxyInfos = GetProxyInfos(m_Zh, proxyPath); if (proxyInfos.size() == 0) { LOG(ERROR, "no proxy can be used!"); exit(1); } InitProxyConns(proxyInfos); } vector<pair<string, int> > RoundRobinCodisPool::GetProxyInfos(zhandle_t *(&zh), const string& proxyPath) { vector<pair<string, int> > proxys; struct String_vector strings; int rc0 = zoo_get_children(zh, proxyPath.c_str(),1, &strings); if (rc0 != ZOK) { stringstream stream; stream << "get children from %s faild!!!\n proxypath=" << proxyPath; LOG(ERROR, stream.str()); exit(1); } char **pstr = strings.data; ostringstream sentinel_addr_oss; vector<string> proxyNameVec; for (int i=0; i<strings.count; ++i, ++pstr) { Json::Reader reader; Json::Value state; stringstream proxyFullPath; proxyFullPath << proxyPath << "/" << *pstr; string node_data = ZkGet(zh, proxyFullPath.str()); if (!reader.parse(node_data.c_str(), state, false)) { stringstream stream; stream << "data format json is faild [path: " << proxyFullPath << "][data:" << node_data << "]\n"; LOG(ERROR, stream.str()); continue; } if (state.isMember("state") && state["state"].isString() && state["state"].asString() == string("online")) { if (state.isMember("addr") && state["addr"].isString()) { string ipport = state["addr"].asString(); vector<string> proxyinfo = split(ipport, ':'); if (proxyinfo.size()>1) { int port = atoi(proxyinfo[1].c_str()); proxys.push_back(make_pair(proxyinfo[0], port)); } } } else { stringstream stream; stream << "get proxy state faild [path: " << proxyFullPath << "][data:" << state.toStyledString() << "]\n"; LOG(ERROR, stream.str()); } } return proxys; } void RoundRobinCodisPool::InitProxyConns(const vector<pair<string, int> >& proxyInfos) { vector<CodisClient*> proxys; for (size_t i=0; i<proxyInfos.size(); i++) { CodisClient *proxy = new CodisClient(proxyInfos[i].first, proxyInfos[i].second, m_BusinessID); proxys.push_back(proxy); } { ScopedLock lock(m_Mutex); m_Proxys.swap(proxys); m_ProxyInfos = proxyInfos; } for (size_t i=0; i<proxys.size(); i++) { if (proxys[i] != NULL) { delete proxys[i]; proxys[i] = NULL; } } } string RoundRobinCodisPool::ZkGet(zhandle_t *(&zh), const string &path, bool watch) { char * buffer = NULL; Stat stat; int buf_len = 0; int rc; rc = zoo_get(zh, path.c_str(), 0, NULL, &buf_len, &stat); if (rc != ZOK) { LOG(ERROR, string("getting zk node stats failed:")+zerror(rc)); return ""; } buffer = (char*)malloc(sizeof(char) * (stat.dataLength+1)); buf_len = stat.dataLength + 1; rc = zoo_get(zh, path.c_str(), watch, buffer, &buf_len, NULL); if (rc != ZOK) { LOG(ERROR, string("getting zk node stats failed:")+zerror(rc)); if (buffer != NULL) { free(buffer); buffer = NULL; } return ""; } string return_str = buffer; if (buffer != NULL) { free(buffer); buffer = NULL; } return return_str; } void RoundRobinCodisPool::proxy_watcher(zhandle_t *zh, int type, int state, const char *path, void *context) { stringstream stream; stream << "zkevent type=" << type << "stats=" << state; LOG(INFO, stream.str()); RoundRobinCodisPool* ptr = reinterpret_cast<RoundRobinCodisPool*>(context); if ((type==ZOO_SESSION_EVENT) && (state==ZOO_CONNECTING_STATE)) { zookeeper_close(ptr->m_Zh); ptr->m_Zh = zookeeper_init(ptr->m_ZookeeperAddr.c_str(), proxy_watcher, 10000, NULL, context, 0); int cnt = 0; while (zoo_state(ptr->m_Zh)!=ZOO_CONNECTED_STATE && cnt<10000) { usleep(30000); cnt++; } if (cnt == 10000) { LOG(ERROR, "connect zookeeper error! zookeeperAddr="+ptr->m_ZookeeperAddr); exit(1); } ptr->Init(ptr->m_Zh, ptr->m_ProxyPath); } else if ((type==ZOO_SESSION_EVENT) && (state==ZOO_EXPIRED_SESSION_STATE)) { zookeeper_close(ptr->m_Zh); ptr->m_Zh = zookeeper_init(ptr->m_ZookeeperAddr.c_str(), proxy_watcher, 10000, NULL, context, 0); int cnt = 0; while (zoo_state(ptr->m_Zh)!=ZOO_CONNECTED_STATE && cnt<10000) { usleep(30000); cnt++; } if (cnt == 10000) { LOG(ERROR, "connect zookeeper error! zookeeperAddr="+ptr->m_ZookeeperAddr); exit(1); } ptr->Init(ptr->m_Zh, ptr->m_ProxyPath); } else if ((type==ZOO_SESSION_EVENT) && (state==ZOO_CONNECTED_STATE)) { } else if ((state==ZOO_CONNECTED_STATE) && (type==ZOO_CHANGED_EVENT)) { //ptr->Init(ptr->m_Zh, ptr->m_ProxyPath); } else if ((state==ZOO_CONNECTED_STATE) && (type==ZOO_DELETED_EVENT)) { //ptr->Init(ptr->m_Zh, ptr->m_ProxyPath); } else if ((state==ZOO_CONNECTED_STATE) && (type==ZOO_CHILD_EVENT)) { sleep(5); ptr->Init(ptr->m_Zh, ptr->m_ProxyPath); } else if ((state==ZOO_CONNECTED_STATE) && (type==ZOO_CREATED_EVENT)) { //ptr->Init(ptr->m_Zh, ptr->m_ProxyPath); } else { LOG(ERROR, "zookeeper connection state changed but not implemented"); } }
update getproxy
update getproxy
C++
apache-2.0
baifendian/CodisClient,baifendian/CodisClient,baifendian/CodisClient,baifendian/CodisClient,baifendian/CodisClient
827ad7a88c642d3f818077b7802581a621e8e0c8
chrome/browser/tab_contents/web_drag_dest_gtk.cc
chrome/browser/tab_contents/web_drag_dest_gtk.cc
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/tab_contents/web_drag_dest_gtk.h" #include <string> #include "app/gtk_dnd_util.h" #include "base/file_path.h" #include "base/utf_string_conversions.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "net/base/net_util.h" using WebKit::WebDragOperation; using WebKit::WebDragOperationCopy; using WebKit::WebDragOperationMove; using WebKit::WebDragOperationNone; WebDragDestGtk::WebDragDestGtk(TabContents* tab_contents, GtkWidget* widget) : tab_contents_(tab_contents), widget_(widget), context_(NULL), method_factory_(this) { gtk_drag_dest_set(widget, static_cast<GtkDestDefaults>(0), NULL, 0, GDK_ACTION_COPY); g_signal_connect(widget, "drag-motion", G_CALLBACK(OnDragMotionThunk), this); g_signal_connect(widget, "drag-leave", G_CALLBACK(OnDragLeaveThunk), this); g_signal_connect(widget, "drag-drop", G_CALLBACK(OnDragDropThunk), this); g_signal_connect(widget, "drag-data-received", G_CALLBACK(OnDragDataReceivedThunk), this); destroy_handler_ = g_signal_connect( widget, "destroy", G_CALLBACK(gtk_widget_destroyed), &widget_); } WebDragDestGtk::~WebDragDestGtk() { if (widget_) { gtk_drag_dest_unset(widget_); g_signal_handler_disconnect(widget_, destroy_handler_); } } void WebDragDestGtk::UpdateDragStatus(WebDragOperation operation) { if (context_) { // TODO(estade): we might want to support other actions besides copy, // but that would increase the cost of getting our drag success guess // wrong. is_drop_target_ = operation != WebDragOperationNone; gdk_drag_status(context_, is_drop_target_ ? GDK_ACTION_COPY : static_cast<GdkDragAction>(0), drag_over_time_); } } void WebDragDestGtk::DragLeave() { tab_contents_->render_view_host()->DragTargetDragLeave(); } gboolean WebDragDestGtk::OnDragMotion(GtkWidget* sender, GdkDragContext* context, gint x, gint y, guint time) { if (context_ != context) { context_ = context; drop_data_.reset(new WebDropData); is_drop_target_ = false; static int supported_targets[] = { gtk_dnd_util::TEXT_PLAIN, gtk_dnd_util::TEXT_URI_LIST, gtk_dnd_util::TEXT_HTML, // TODO(estade): support image drags? }; data_requests_ = arraysize(supported_targets); for (size_t i = 0; i < arraysize(supported_targets); ++i) { gtk_drag_get_data(widget_, context, gtk_dnd_util::GetAtomForTarget(supported_targets[i]), time); } } else if (data_requests_ == 0) { tab_contents_->render_view_host()-> DragTargetDragOver(gtk_util::ClientPoint(widget_), gtk_util::ScreenPoint(widget_), static_cast<WebDragOperation>( WebDragOperationCopy | WebDragOperationMove)); // TODO(snej): Pass appropriate DragOperation instead of hardcoding drag_over_time_ = time; } // Pretend we are a drag destination because we don't want to wait for // the renderer to tell us if we really are or not. return TRUE; } void WebDragDestGtk::OnDragDataReceived( GtkWidget* sender, GdkDragContext* context, gint x, gint y, GtkSelectionData* data, guint info, guint time) { // We might get the data from an old get_data() request that we no longer // care about. if (context != context_) return; data_requests_--; // Decode the data. if (data->data) { // If the source can't provide us with valid data for a requested target, // data->data will be NULL. if (data->target == gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_PLAIN)) { guchar* text = gtk_selection_data_get_text(data); if (text) { drop_data_->plain_text = UTF8ToUTF16(std::string(reinterpret_cast<char*>(text), data->length)); g_free(text); } } else if (data->target == gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_URI_LIST)) { gchar** uris = gtk_selection_data_get_uris(data); if (uris) { for (gchar** uri_iter = uris; *uri_iter; uri_iter++) { // TODO(estade): Can the filenames have a non-UTF8 encoding? FilePath file_path; if (net::FileURLToFilePath(GURL(*uri_iter), &file_path)) drop_data_->filenames.push_back(UTF8ToUTF16(file_path.value())); } // Also, write the first URI as the URL. if (uris[0]) drop_data_->url = GURL(uris[0]); g_strfreev(uris); } } else if (data->target == gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_HTML)) { // TODO(estade): Can the html have a non-UTF8 encoding? drop_data_->text_html = UTF8ToUTF16(std::string(reinterpret_cast<char*>(data->data), data->length)); // We leave the base URL empty. } } if (data_requests_ == 0) { // Tell the renderer about the drag. // |x| and |y| are seemingly arbitrary at this point. tab_contents_->render_view_host()-> DragTargetDragEnter(*drop_data_.get(), gtk_util::ClientPoint(widget_), gtk_util::ScreenPoint(widget_), static_cast<WebDragOperation>( WebDragOperationCopy | WebDragOperationMove)); // TODO(snej): Pass appropriate DragOperation instead of hardcoding drag_over_time_ = time; } } // The drag has left our widget; forward this information to the renderer. void WebDragDestGtk::OnDragLeave(GtkWidget* sender, GdkDragContext* context, guint time) { // Set |context_| to NULL to make sure we will recognize the next DragMotion // as an enter. context_ = NULL; drop_data_.reset(); // When GTK sends us a drag-drop signal, it is shortly (and synchronously) // preceded by a drag-leave. The renderer doesn't like getting the signals // in this order so delay telling it about the drag-leave till we are sure // we are not getting a drop as well. MessageLoop::current()->PostTask(FROM_HERE, method_factory_.NewRunnableMethod(&WebDragDestGtk::DragLeave)); } // Called by GTK when the user releases the mouse, executing a drop. gboolean WebDragDestGtk::OnDragDrop(GtkWidget* sender, GdkDragContext* context, gint x, gint y, guint time) { // Cancel that drag leave! method_factory_.RevokeAll(); tab_contents_->render_view_host()-> DragTargetDrop(gtk_util::ClientPoint(widget_), gtk_util::ScreenPoint(widget_)); // The second parameter is just an educated guess, but at least we will // get the drag-end animation right sometimes. gtk_drag_finish(context, is_drop_target_, FALSE, time); return TRUE; }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/tab_contents/web_drag_dest_gtk.h" #include <string> #include "app/gtk_dnd_util.h" #include "base/file_path.h" #include "base/utf_string_conversions.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "net/base/net_util.h" using WebKit::WebDragOperation; using WebKit::WebDragOperationCopy; using WebKit::WebDragOperationMove; using WebKit::WebDragOperationNone; WebDragDestGtk::WebDragDestGtk(TabContents* tab_contents, GtkWidget* widget) : tab_contents_(tab_contents), widget_(widget), context_(NULL), method_factory_(this) { gtk_drag_dest_set(widget, static_cast<GtkDestDefaults>(0), NULL, 0, GDK_ACTION_COPY); g_signal_connect(widget, "drag-motion", G_CALLBACK(OnDragMotionThunk), this); g_signal_connect(widget, "drag-leave", G_CALLBACK(OnDragLeaveThunk), this); g_signal_connect(widget, "drag-drop", G_CALLBACK(OnDragDropThunk), this); g_signal_connect(widget, "drag-data-received", G_CALLBACK(OnDragDataReceivedThunk), this); destroy_handler_ = g_signal_connect( widget, "destroy", G_CALLBACK(gtk_widget_destroyed), &widget_); } WebDragDestGtk::~WebDragDestGtk() { if (widget_) { gtk_drag_dest_unset(widget_); g_signal_handler_disconnect(widget_, destroy_handler_); } } void WebDragDestGtk::UpdateDragStatus(WebDragOperation operation) { if (context_) { // TODO(estade): we might want to support other actions besides copy, // but that would increase the cost of getting our drag success guess // wrong. is_drop_target_ = operation != WebDragOperationNone; gdk_drag_status(context_, is_drop_target_ ? GDK_ACTION_COPY : static_cast<GdkDragAction>(0), drag_over_time_); } } void WebDragDestGtk::DragLeave() { tab_contents_->render_view_host()->DragTargetDragLeave(); } gboolean WebDragDestGtk::OnDragMotion(GtkWidget* sender, GdkDragContext* context, gint x, gint y, guint time) { if (context_ != context) { context_ = context; drop_data_.reset(new WebDropData); is_drop_target_ = false; static int supported_targets[] = { gtk_dnd_util::TEXT_PLAIN, gtk_dnd_util::TEXT_URI_LIST, gtk_dnd_util::TEXT_HTML, gtk_dnd_util::NETSCAPE_URL, gtk_dnd_util::CHROME_NAMED_URL, // TODO(estade): support image drags? }; data_requests_ = arraysize(supported_targets); for (size_t i = 0; i < arraysize(supported_targets); ++i) { gtk_drag_get_data(widget_, context, gtk_dnd_util::GetAtomForTarget(supported_targets[i]), time); } } else if (data_requests_ == 0) { tab_contents_->render_view_host()-> DragTargetDragOver(gtk_util::ClientPoint(widget_), gtk_util::ScreenPoint(widget_), static_cast<WebDragOperation>( WebDragOperationCopy | WebDragOperationMove)); // TODO(snej): Pass appropriate DragOperation instead of hardcoding drag_over_time_ = time; } // Pretend we are a drag destination because we don't want to wait for // the renderer to tell us if we really are or not. return TRUE; } void WebDragDestGtk::OnDragDataReceived( GtkWidget* sender, GdkDragContext* context, gint x, gint y, GtkSelectionData* data, guint info, guint time) { // We might get the data from an old get_data() request that we no longer // care about. if (context != context_) return; data_requests_--; // Decode the data. if (data->data) { // If the source can't provide us with valid data for a requested target, // data->data will be NULL. if (data->target == gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_PLAIN)) { guchar* text = gtk_selection_data_get_text(data); if (text) { drop_data_->plain_text = UTF8ToUTF16(std::string(reinterpret_cast<char*>(text), data->length)); g_free(text); } } else if (data->target == gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_URI_LIST)) { gchar** uris = gtk_selection_data_get_uris(data); if (uris) { for (gchar** uri_iter = uris; *uri_iter; uri_iter++) { // TODO(estade): Can the filenames have a non-UTF8 encoding? FilePath file_path; if (net::FileURLToFilePath(GURL(*uri_iter), &file_path)) drop_data_->filenames.push_back(UTF8ToUTF16(file_path.value())); } // Also, write the first URI as the URL. if (uris[0]) drop_data_->url = GURL(uris[0]); g_strfreev(uris); } } else if (data->target == gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_HTML)) { // TODO(estade): Can the html have a non-UTF8 encoding? drop_data_->text_html = UTF8ToUTF16(std::string(reinterpret_cast<char*>(data->data), data->length)); // We leave the base URL empty. } else if (data->target == gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::NETSCAPE_URL)) { std::string netscape_url(reinterpret_cast<char*>(data->data), data->length); size_t split = netscape_url.find_first_of('\n'); if (split != std::string::npos) { drop_data_->url_title = UTF8ToUTF16(netscape_url.substr(0, split)); if (split < netscape_url.size() - 1) drop_data_->url = GURL(netscape_url.substr(split + 1)); } } else if (data->target == gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::CHROME_NAMED_URL)) { gtk_dnd_util::ExtractNamedURL(data, &drop_data_->url, &drop_data_->url_title); } } if (data_requests_ == 0) { // Tell the renderer about the drag. // |x| and |y| are seemingly arbitrary at this point. tab_contents_->render_view_host()-> DragTargetDragEnter(*drop_data_.get(), gtk_util::ClientPoint(widget_), gtk_util::ScreenPoint(widget_), static_cast<WebDragOperation>( WebDragOperationCopy | WebDragOperationMove)); // TODO(snej): Pass appropriate DragOperation instead of hardcoding drag_over_time_ = time; } } // The drag has left our widget; forward this information to the renderer. void WebDragDestGtk::OnDragLeave(GtkWidget* sender, GdkDragContext* context, guint time) { // Set |context_| to NULL to make sure we will recognize the next DragMotion // as an enter. context_ = NULL; drop_data_.reset(); // When GTK sends us a drag-drop signal, it is shortly (and synchronously) // preceded by a drag-leave. The renderer doesn't like getting the signals // in this order so delay telling it about the drag-leave till we are sure // we are not getting a drop as well. MessageLoop::current()->PostTask(FROM_HERE, method_factory_.NewRunnableMethod(&WebDragDestGtk::DragLeave)); } // Called by GTK when the user releases the mouse, executing a drop. gboolean WebDragDestGtk::OnDragDrop(GtkWidget* sender, GdkDragContext* context, gint x, gint y, guint time) { // Cancel that drag leave! method_factory_.RevokeAll(); tab_contents_->render_view_host()-> DragTargetDrop(gtk_util::ClientPoint(widget_), gtk_util::ScreenPoint(widget_)); // The second parameter is just an educated guess, but at least we will // get the drag-end animation right sometimes. gtk_drag_finish(context, is_drop_target_, FALSE, time); return TRUE; }
Add a couple more drop targets to the render view.
Add a couple more drop targets to the render view. BUG=35063 TEST=see bug Review URL: http://codereview.chromium.org/1030001 git-svn-id: http://src.chromium.org/svn/trunk/src@41772 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: b1509db625ece1f87d39c9601569e897c70cf23f
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
9cbff7fc179450fb07ec30400434620b8b1c6420
test/opengl/save_state.cpp
test/opengl/save_state.cpp
// Test doesn't build on windows, because OpenGL on windows is a nightmare. #ifdef _WIN32 #include <stdio.h> int main() { printf("Skipping test on Windows\n"); return 0; } #else #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <cstring> #include "../src/runtime/mini_opengl.h" #include "Halide.h" extern "C" void glGenTextures(GLsizei, GLuint *); extern "C" void glTexParameteri(GLenum, GLenum, GLint); extern "C" void glBindTexture(GLenum, GLuint); extern "C" void glTexImage2D(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *); extern "C" GLuint glCreateProgram(); extern "C" void glAttachShader(GLuint, GLuint); extern "C" void glLinkProgram(GLuint); extern "C" void glGetProgramiv(GLuint, GLenum, GLint *); extern "C" void glGetProgramInfoLog(GLuint, GLsizei, GLsizei *, GLchar *); extern "C" GLuint glCreateShader(GLenum); extern "C" void glShaderSource(GLuint, GLsizei, const GLchar **, const GLint *); extern "C" void glCompileShader(GLuint); extern "C" void glGetShaderiv(GLuint, GLenum, GLint *); extern "C" void glGetShaderInfoLog(GLuint, GLsizei, GLsizei *, GLchar *); extern "C" void glEnable(GLenum); extern "C" void glDisable(GLenum); extern "C" void glGetIntegerv(GLenum, GLint *); extern "C" void glGetBooleanv(GLenum, GLboolean *); extern "C" GLenum glGetError(); extern "C" void glActiveTexture(GLenum); extern "C" void glEnableVertexAttribArray(GLuint); extern "C" void glDisableVertexAttribArray(GLuint); extern "C" void glUseProgram(GLuint); extern "C" void glGenBuffers(GLsizei, GLuint *); extern "C" void glViewport(GLint, GLint, GLsizei, GLsizei); extern "C" void glGenFramebuffers(GLsizei, GLuint *); extern "C" void glBindBuffer(GLenum, GLuint); extern "C" void glBindFramebuffer(GLenum, GLuint); extern "C" void glGenVertexArrays(GLsizei, GLuint *); extern "C" void glBindVertexArray(GLuint); extern "C" void glGetVertexAttribiv(GLuint, GLenum, GLint *); extern "C" const GLubyte* glGetString(GLenum name); // Generates an arbitrary program. class Program { public: static GLuint handle() { const char *vertexShader = " \ attribute vec4 Position; \ attribute vec2 TexCoordIn; \ varying vec2 TexCoordOut; \ void main(void) { \ gl_Position = Position; \ TexCoordOut = TexCoordIn; \ }"; const char *fragmentShader = " \ varying vec2 TexCoordOut; \ uniform sampler2D Texture; \ void main(void) { \ gl_FragColor = texture2D(Texture, TexCoordOut); \ }"; GLuint handle = glCreateProgram(); glAttachShader(handle, compileShader("vertex", vertexShader, GL_VERTEX_SHADER)); glAttachShader(handle, compileShader("fragment", fragmentShader, GL_FRAGMENT_SHADER)); glLinkProgram(handle); GLint linkSuccess; glGetProgramiv(handle, GL_LINK_STATUS, &linkSuccess); if (linkSuccess == GL_FALSE) { GLchar messages[256]; glGetProgramInfoLog(handle, sizeof(messages), 0, messages); fprintf(stderr, "Error linking program: %s\n", messages); exit(1); } return handle; } private: static GLuint compileShader(const char *label, const char *shaderString, GLenum shaderType) { const GLuint handle = glCreateShader(shaderType); const int len = strlen(shaderString); glShaderSource(handle, 1, &shaderString, &len); glCompileShader(handle); GLint compileSuccess; glGetShaderiv(handle, GL_COMPILE_STATUS, &compileSuccess); if (compileSuccess == GL_FALSE) { GLchar messages[256]; glGetShaderInfoLog(handle, sizeof(messages), 0, messages); fprintf(stderr, "Error compiling %s shader: %s\n", label, messages); exit(1); } return handle; } }; // Encapsulates setting OpenGL's state to arbitrary values, and checking // whether the state matches those values. class KnownState { private: void gl_enable(GLenum cap, bool state) { (state ? glEnable : glDisable)(cap); } GLuint gl_gen(void (*fn)(GLsizei, GLuint *)) { GLuint val; (*fn)(1, &val); return val; } void check_value(const char *operation, const char *label, GLenum pname, GLint initial) { GLint val; glGetIntegerv(pname, &val); if (val != initial) { fprintf(stderr, "%s did not restore %s: initial value was %d (%#x), current value is %d (%#x)\n", operation, label, initial, initial, val, val); errors = true; } } void check_value(const char *operation, const char *label, GLenum pname, GLenum initial) { check_value(operation, label, pname, (GLint) initial); } void check_value(const char *operation, const char *label, GLenum pname, GLint initial[], int n=4) { GLint val[2048]; glGetIntegerv(pname, val); for (int i=0; i<n; i++) { if (val[i] != initial[i]) { fprintf(stderr, "%s did not restore %s: initial value was", operation, label); for (int j=0; j<n; j++) fprintf(stderr, " %d", initial[j]); fprintf(stderr, ", current value is"); for (int j=0; j<n; j++) fprintf(stderr, " %d", val[j]); fprintf(stderr, "\n"); errors = true; return; } } } void check_value(const char *operation, const char *label, GLenum pname, bool initial) { GLboolean val; glGetBooleanv(pname, &val); if (val != initial) { fprintf(stderr, "%s did not restore boolean %s: initial value was %s, current value is %s\n", operation, label, initial ? "true" : "false", val ? "true" : "false"); errors = true; } } void check_error(const char *label) { GLenum err = glGetError(); if (err != GL_NO_ERROR) { fprintf(stderr, "Error setting %s: OpenGL error %#x\n", label, err); errors = true; } } // version of OpenGL int gl_major_version; int gl_minor_version; GLenum initial_active_texture; GLint initial_viewport[4]; GLuint initial_array_buffer_binding; GLuint initial_element_array_buffer_binding; GLuint initial_current_program; GLuint initial_framebuffer_binding; static const int ntextures = 10; GLuint initial_bound_textures[ntextures]; bool initial_cull_face; bool initial_depth_test; static const int nvertex_attribs = 10; bool initial_vertex_attrib_array_enabled[nvertex_attribs]; // The next two functions are stolen from opengl.cpp // and are used to parse the major/minor version of OpenGL // to see if vertex array objects are supported const char *parse_int(const char *str, int *val) { int v = 0; size_t i = 0; while (str[i] >= '0' && str[i] <= '9') { v = 10 * v + (str[i] - '0'); i++; } if (i > 0) { *val = v; return &str[i]; } return NULL; } const char *parse_opengl_version(const char *str, int *major, int *minor) { str = parse_int(str, major); if (str == NULL || *str != '.') { return NULL; } return parse_int(str + 1, minor); } GLuint initial_vertex_array_binding; public: bool errors; // This sets most values to generated or arbitrary values, which the // halide calls would be unlikely to accidentally use. But for boolean // values, we want to be sure that halide is really restoring the // initial value, not just setting it to true or false. So we need to // be able to try both. void setup(bool boolval) { // parse the OpenGL version const char *version = (const char *)glGetString(GL_VERSION); parse_opengl_version(version, &gl_major_version, &gl_minor_version); glGenTextures(ntextures, initial_bound_textures); for (int i=0; i<ntextures; i++) { glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, initial_bound_textures[i]); } glActiveTexture(initial_active_texture = GL_TEXTURE3); for (int i=0; i<nvertex_attribs; i++) { if ( (initial_vertex_attrib_array_enabled[i] = boolval ) ) glEnableVertexAttribArray(i); else glDisableVertexAttribArray(i); char buf[256]; sprintf(buf, "vertex attrib array %d state", i); check_error(buf); } glUseProgram(initial_current_program = Program::handle()); glViewport(initial_viewport[0] = 111, initial_viewport[1] = 222, initial_viewport[2] = 333, initial_viewport[3] = 444); gl_enable(GL_CULL_FACE, initial_cull_face = boolval); gl_enable(GL_DEPTH_TEST, initial_depth_test = boolval); glBindBuffer(GL_ARRAY_BUFFER, initial_array_buffer_binding = gl_gen(glGenBuffers)); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, initial_element_array_buffer_binding = gl_gen(glGenBuffers)); glBindFramebuffer(GL_FRAMEBUFFER, initial_framebuffer_binding = gl_gen(glGenFramebuffers)); // Vertex array objects are only used by Halide if the OpenGL version >=3 if (gl_major_version >= 3) { glBindVertexArray(initial_vertex_array_binding = gl_gen(glGenVertexArrays)); check_error("known state"); } } void check(const char *operation) { check_value(operation, "ActiveTexture", GL_ACTIVE_TEXTURE, initial_active_texture); check_value(operation, "current program", GL_CURRENT_PROGRAM, initial_current_program); check_value(operation, "framebuffer binding", GL_FRAMEBUFFER_BINDING, initial_framebuffer_binding); check_value(operation, "array buffer binding", GL_ARRAY_BUFFER_BINDING, initial_array_buffer_binding); check_value(operation, "element array buffer binding", GL_ELEMENT_ARRAY_BUFFER_BINDING, initial_element_array_buffer_binding); check_value(operation, "viewport", GL_VIEWPORT, initial_viewport); check_value(operation, "GL_CULL_FACE", GL_CULL_FACE, initial_cull_face); check_value(operation, "GL_DEPTH_TEST", GL_DEPTH_TEST, initial_cull_face); // Vertex array objects are only used by Halide if the OpenGL version >=3 if (gl_major_version >= 3) { check_value(operation, "vertex array binding", GL_VERTEX_ARRAY_BINDING, initial_vertex_array_binding); } for (int i=0; i<ntextures; i++) { char buf[100]; sprintf(buf, "bound texture (unit %d)", i); glActiveTexture(GL_TEXTURE0 + i); check_value(operation, buf, GL_TEXTURE_BINDING_2D, initial_bound_textures[i]); } for (int i=0; i < nvertex_attribs; i++) { int initial = initial_vertex_attrib_array_enabled[i]; GLint val; glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &val); if (val != initial) { fprintf(stderr, "%s did not restore boolean VertexAttributeArrayEnabled(%d): initial value was %s, current value is %s\n", operation, i, initial ? "true" : "false", val ? "true" : "false"); errors = true; } } } }; using namespace Halide; int main() { KnownState known_state; Image<uint8_t> input(255, 10, 3); Buffer out(UInt(8), 255, 10, 3); Var x, y, c; Func g; g(x, y, c) = input(x, y, c); g.bound(c, 0, 3); g.glsl(x, y, c); g.realize(out); // let Halide initialize OpenGL known_state.setup(true); g.realize(out); known_state.check("realize"); known_state.setup(true); out.copy_to_host(); known_state.check("copy_to_host"); known_state.setup(false); g.realize(out); known_state.check("realize"); known_state.setup(false); out.copy_to_host(); known_state.check("copy_to_host"); if (known_state.errors) { return 1; } printf("Success!\n"); return 0; } #endif
// Test doesn't build on windows, because OpenGL on windows is a nightmare. #ifdef _WIN32 #include <stdio.h> int main() { printf("Skipping test on Windows\n"); return 0; } #else #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <cstring> #include "../src/runtime/mini_opengl.h" #include "Halide.h" extern "C" void glGenTextures(GLsizei, GLuint *); extern "C" void glTexParameteri(GLenum, GLenum, GLint); extern "C" void glBindTexture(GLenum, GLuint); extern "C" void glTexImage2D(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *); extern "C" GLuint glCreateProgram(); extern "C" void glAttachShader(GLuint, GLuint); extern "C" void glLinkProgram(GLuint); extern "C" void glGetProgramiv(GLuint, GLenum, GLint *); extern "C" void glGetProgramInfoLog(GLuint, GLsizei, GLsizei *, GLchar *); extern "C" GLuint glCreateShader(GLenum); extern "C" void glShaderSource(GLuint, GLsizei, const GLchar **, const GLint *); extern "C" void glCompileShader(GLuint); extern "C" void glGetShaderiv(GLuint, GLenum, GLint *); extern "C" void glGetShaderInfoLog(GLuint, GLsizei, GLsizei *, GLchar *); extern "C" void glEnable(GLenum); extern "C" void glDisable(GLenum); extern "C" void glGetIntegerv(GLenum, GLint *); extern "C" void glGetBooleanv(GLenum, GLboolean *); extern "C" GLenum glGetError(); extern "C" void glActiveTexture(GLenum); extern "C" void glEnableVertexAttribArray(GLuint); extern "C" void glDisableVertexAttribArray(GLuint); extern "C" void glUseProgram(GLuint); extern "C" void glGenBuffers(GLsizei, GLuint *); extern "C" void glViewport(GLint, GLint, GLsizei, GLsizei); extern "C" void glGenFramebuffers(GLsizei, GLuint *); extern "C" void glBindBuffer(GLenum, GLuint); extern "C" void glBindFramebuffer(GLenum, GLuint); extern "C" void glGenVertexArrays(GLsizei, GLuint *); extern "C" void glBindVertexArray(GLuint); extern "C" void glGetVertexAttribiv(GLuint, GLenum, GLint *); extern "C" const GLubyte* glGetString(GLenum name); // Generates an arbitrary program. class Program { public: static GLuint handle() { const char *vertexShader = " \ attribute vec4 Position; \ attribute vec2 TexCoordIn; \ varying vec2 TexCoordOut; \ void main(void) { \ gl_Position = Position; \ TexCoordOut = TexCoordIn; \ }"; const char *fragmentShader = " \ varying vec2 TexCoordOut; \ uniform sampler2D Texture; \ void main(void) { \ gl_FragColor = texture2D(Texture, TexCoordOut); \ }"; GLuint handle = glCreateProgram(); glAttachShader(handle, compileShader("vertex", vertexShader, GL_VERTEX_SHADER)); glAttachShader(handle, compileShader("fragment", fragmentShader, GL_FRAGMENT_SHADER)); glLinkProgram(handle); GLint linkSuccess; glGetProgramiv(handle, GL_LINK_STATUS, &linkSuccess); if (linkSuccess == GL_FALSE) { GLchar messages[256]; glGetProgramInfoLog(handle, sizeof(messages), 0, messages); fprintf(stderr, "Error linking program: %s\n", messages); exit(1); } return handle; } private: static GLuint compileShader(const char *label, const char *shaderString, GLenum shaderType) { const GLuint handle = glCreateShader(shaderType); const int len = strlen(shaderString); glShaderSource(handle, 1, &shaderString, &len); glCompileShader(handle); GLint compileSuccess; glGetShaderiv(handle, GL_COMPILE_STATUS, &compileSuccess); if (compileSuccess == GL_FALSE) { GLchar messages[256]; glGetShaderInfoLog(handle, sizeof(messages), 0, messages); fprintf(stderr, "Error compiling %s shader: %s\n", label, messages); exit(1); } return handle; } }; // Encapsulates setting OpenGL's state to arbitrary values, and checking // whether the state matches those values. class KnownState { private: void gl_enable(GLenum cap, bool state) { (state ? glEnable : glDisable)(cap); } GLuint gl_gen(void (*fn)(GLsizei, GLuint *)) { GLuint val; (*fn)(1, &val); return val; } void check_value(const char *operation, const char *label, GLenum pname, GLint initial) { GLint val; glGetIntegerv(pname, &val); if (val != initial) { fprintf(stderr, "%s did not restore %s: initial value was %d (%#x), current value is %d (%#x)\n", operation, label, initial, initial, val, val); errors = true; } } void check_value(const char *operation, const char *label, GLenum pname, GLenum initial) { check_value(operation, label, pname, (GLint) initial); } void check_value(const char *operation, const char *label, GLenum pname, GLint initial[], int n=4) { GLint val[2048]; glGetIntegerv(pname, val); for (int i=0; i<n; i++) { if (val[i] != initial[i]) { fprintf(stderr, "%s did not restore %s: initial value was", operation, label); for (int j=0; j<n; j++) fprintf(stderr, " %d", initial[j]); fprintf(stderr, ", current value is"); for (int j=0; j<n; j++) fprintf(stderr, " %d", val[j]); fprintf(stderr, "\n"); errors = true; return; } } } void check_value(const char *operation, const char *label, GLenum pname, bool initial) { GLboolean val; glGetBooleanv(pname, &val); if (val != initial) { fprintf(stderr, "%s did not restore boolean %s: initial value was %s, current value is %s\n", operation, label, initial ? "true" : "false", val ? "true" : "false"); errors = true; } } void check_error(const char *label) { GLenum err = glGetError(); if (err != GL_NO_ERROR) { fprintf(stderr, "Error setting %s: OpenGL error %#x\n", label, err); errors = true; } } // version of OpenGL int gl_major_version; int gl_minor_version; GLenum initial_active_texture; GLint initial_viewport[4]; GLuint initial_array_buffer_binding; GLuint initial_element_array_buffer_binding; GLuint initial_current_program; GLuint initial_framebuffer_binding; static const int ntextures = 10; GLuint initial_bound_textures[ntextures]; bool initial_cull_face; bool initial_depth_test; static const int nvertex_attribs = 10; bool initial_vertex_attrib_array_enabled[nvertex_attribs]; // The next two functions are stolen from opengl.cpp // and are used to parse the major/minor version of OpenGL // to see if vertex array objects are supported const char *parse_int(const char *str, int *val) { int v = 0; size_t i = 0; while (str[i] >= '0' && str[i] <= '9') { v = 10 * v + (str[i] - '0'); i++; } if (i > 0) { *val = v; return &str[i]; } return NULL; } const char *parse_opengl_version(const char *str, int *major, int *minor) { str = parse_int(str, major); if (str == NULL || *str != '.') { return NULL; } return parse_int(str + 1, minor); } GLuint initial_vertex_array_binding; public: bool errors; // This sets most values to generated or arbitrary values, which the // halide calls would be unlikely to accidentally use. But for boolean // values, we want to be sure that halide is really restoring the // initial value, not just setting it to true or false. So we need to // be able to try both. void setup(bool boolval) { // parse the OpenGL version const char *version = (const char *)glGetString(GL_VERSION); parse_opengl_version(version, &gl_major_version, &gl_minor_version); glGenTextures(ntextures, initial_bound_textures); for (int i=0; i<ntextures; i++) { glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, initial_bound_textures[i]); } glActiveTexture(initial_active_texture = GL_TEXTURE3); for (int i=0; i<nvertex_attribs; i++) { if ( (initial_vertex_attrib_array_enabled[i] = boolval ) ) glEnableVertexAttribArray(i); else glDisableVertexAttribArray(i); char buf[256]; sprintf(buf, "vertex attrib array %d state", i); check_error(buf); } glUseProgram(initial_current_program = Program::handle()); glViewport(initial_viewport[0] = 111, initial_viewport[1] = 222, initial_viewport[2] = 333, initial_viewport[3] = 444); gl_enable(GL_CULL_FACE, initial_cull_face = boolval); gl_enable(GL_DEPTH_TEST, initial_depth_test = boolval); glBindBuffer(GL_ARRAY_BUFFER, initial_array_buffer_binding = gl_gen(glGenBuffers)); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, initial_element_array_buffer_binding = gl_gen(glGenBuffers)); glBindFramebuffer(GL_FRAMEBUFFER, initial_framebuffer_binding = gl_gen(glGenFramebuffers)); // Vertex array objects are only used by Halide if the OpenGL version >=3 if (gl_major_version >= 3) { glBindVertexArray(initial_vertex_array_binding = gl_gen(glGenVertexArrays)); } check_error("known state"); } void check(const char *operation) { check_value(operation, "ActiveTexture", GL_ACTIVE_TEXTURE, initial_active_texture); check_value(operation, "current program", GL_CURRENT_PROGRAM, initial_current_program); check_value(operation, "framebuffer binding", GL_FRAMEBUFFER_BINDING, initial_framebuffer_binding); check_value(operation, "array buffer binding", GL_ARRAY_BUFFER_BINDING, initial_array_buffer_binding); check_value(operation, "element array buffer binding", GL_ELEMENT_ARRAY_BUFFER_BINDING, initial_element_array_buffer_binding); check_value(operation, "viewport", GL_VIEWPORT, initial_viewport); check_value(operation, "GL_CULL_FACE", GL_CULL_FACE, initial_cull_face); check_value(operation, "GL_DEPTH_TEST", GL_DEPTH_TEST, initial_cull_face); // Vertex array objects are only used by Halide if the OpenGL version >=3 if (gl_major_version >= 3) { check_value(operation, "vertex array binding", GL_VERTEX_ARRAY_BINDING, initial_vertex_array_binding); } else { fprintf(stderr, "Skipping vertex array binding tests because OpenGL version is %d.%d (<3.0)\n", gl_major_version, gl_minor_version); } for (int i=0; i<ntextures; i++) { char buf[100]; sprintf(buf, "bound texture (unit %d)", i); glActiveTexture(GL_TEXTURE0 + i); check_value(operation, buf, GL_TEXTURE_BINDING_2D, initial_bound_textures[i]); } for (int i=0; i < nvertex_attribs; i++) { int initial = initial_vertex_attrib_array_enabled[i]; GLint val; glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &val); if (val != initial) { fprintf(stderr, "%s did not restore boolean VertexAttributeArrayEnabled(%d): initial value was %s, current value is %s\n", operation, i, initial ? "true" : "false", val ? "true" : "false"); errors = true; } } } }; using namespace Halide; int main() { KnownState known_state; Image<uint8_t> input(255, 10, 3); Buffer out(UInt(8), 255, 10, 3); Var x, y, c; Func g; g(x, y, c) = input(x, y, c); g.bound(c, 0, 3); g.glsl(x, y, c); g.realize(out); // let Halide initialize OpenGL known_state.setup(true); g.realize(out); known_state.check("realize"); known_state.setup(true); out.copy_to_host(); known_state.check("copy_to_host"); known_state.setup(false); g.realize(out); known_state.check("realize"); known_state.setup(false); out.copy_to_host(); known_state.check("copy_to_host"); if (known_state.errors) { return 1; } printf("Success!\n"); return 0; } #endif
Print a message if skipping tests
Print a message if skipping tests Also, move the check for initial state out of the conditional: it should be run no matter the OpenGL version.
C++
mit
psuriana/Halide,jiawen/Halide,psuriana/Halide,jiawen/Halide,jiawen/Halide,ronen/Halide,ronen/Halide,kgnk/Halide,kgnk/Halide,psuriana/Halide,ronen/Halide,kgnk/Halide,jiawen/Halide,kgnk/Halide,jiawen/Halide,ronen/Halide,ronen/Halide,ronen/Halide,kgnk/Halide,psuriana/Halide,ronen/Halide,psuriana/Halide,kgnk/Halide,ronen/Halide,jiawen/Halide,psuriana/Halide,psuriana/Halide,jiawen/Halide,kgnk/Halide,kgnk/Halide
8e0d4169eb4908bc697df0cf3aa36c8d70ce377f
demos/rlAxisControllerDemo/rlAxisControllerDemo.cpp
demos/rlAxisControllerDemo/rlAxisControllerDemo.cpp
// // Copyright (c) 2009, Markus Rickert // 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 <iostream> #include <stdexcept> #include <rl/hal/Coach.h> #include <rl/hal/Gnuplot.h> #include <rl/hal/MitsubishiH7.h> #include <rl/hal/UniversalRobotsRtde.h> #include <rl/math/Constants.h> #include <rl/math/Polynomial.h> #define COACH //#define GNUPLOT //#define MITSUBISHI //#define UNIVERSAL_ROBOTS_RTDE #define CUBIC //#define QUINTIC int main(int argc, char** argv) { try { #ifdef COACH rl::hal::Coach controller(6, std::chrono::microseconds(7110), 0, "localhost"); #endif // COACH #ifdef GNUPLOT rl::hal::Gnuplot controller(6, std::chrono::microseconds(7110), -10 * rl::math::constants::deg2rad, 10 * rl::math::constants::deg2rad); #endif // GNUPLOT #ifdef MITSUBISHI rl::hal::MitsubishiH7 controller(6, "left", "lefthost"); #endif // MITSUBISHI #ifdef UNIVERSAL_ROBOTS_RTDE rl::hal::UniversalRobotsRtde controller("localhost"); #endif // UNIVERSAL_ROBOTS_RTDE rl::math::Real updateRate = std::chrono::duration_cast<std::chrono::duration<rl::math::Real>>(controller.getUpdateRate()).count(); controller.open(); controller.start(); controller.step(); rl::math::Vector q0 = controller.getJointPosition(); rl::math::Vector q1 = q0 + rl::math::Vector::Constant(controller.getDof(), 5 * rl::math::constants::deg2rad); rl::math::Real te = updateRate * 300.0f; rl::math::Vector q(controller.getDof()); #ifdef CUBIC rl::math::Polynomial<rl::math::Vector> interpolator = rl::math::Polynomial<rl::math::Vector>::CubicFirst( q0, q1, rl::math::Vector::Zero(controller.getDof()), rl::math::Vector::Zero(controller.getDof()), te ); #endif // CUBIC #ifdef QUINTIC rl::math::Polynomial<rl::math::Vector> interpolator = rl::math::Polynomial<rl::math::Vector>::QuinticFirstSecond( q0, q1, rl::math::Vector::Zero(controller.getDof()), rl::math::Vector::Zero(controller.getDof()), rl::math::Vector::Zero(controller.getDof()), rl::math::Vector::Zero(controller.getDof()), te ); #endif // QUINTIC for (std::size_t i = 0; i <= std::ceil(te / updateRate); ++i) { q = interpolator(i * updateRate); controller.setJointPosition(q); controller.step(); } #ifdef CUBIC interpolator = rl::math::Polynomial<rl::math::Vector>::CubicFirst( q1, q0, rl::math::Vector::Zero(controller.getDof()), rl::math::Vector::Zero(controller.getDof()), te ); #endif // CUBIC #ifdef QUINTIC interpolator = rl::math::Polynomial<rl::math::Vector>::QuinticFirstSecond( q1, q0, rl::math::Vector::Zero(controller.getDof()), rl::math::Vector::Zero(controller.getDof()), rl::math::Vector::Zero(controller.getDof()), rl::math::Vector::Zero(controller.getDof()), te ); #endif // QUINTIC for (std::size_t i = 0; i <= std::ceil(te / updateRate); ++i) { q = interpolator(i * updateRate); controller.setJointPosition(q); controller.step(); } controller.stop(); controller.close(); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
// // Copyright (c) 2009, Markus Rickert // 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 <iostream> #include <stdexcept> #include <rl/hal/Coach.h> #include <rl/hal/Gnuplot.h> #include <rl/hal/MitsubishiH7.h> #include <rl/hal/UniversalRobotsRtde.h> #include <rl/math/Constants.h> #include <rl/math/Polynomial.h> #include <rl/math/Spline.h> #define COACH //#define GNUPLOT //#define MITSUBISHI //#define UNIVERSAL_ROBOTS_RTDE //#define CUBIC //#define QUINTIC //#define SEPTIC #define TRAPEZOIDAL int main(int argc, char** argv) { try { #ifdef COACH rl::hal::Coach controller(6, std::chrono::microseconds(7110), 0, "localhost"); #endif // COACH #ifdef GNUPLOT rl::hal::Gnuplot controller(6, std::chrono::microseconds(7110), -10 * rl::math::constants::deg2rad, 10 * rl::math::constants::deg2rad); #endif // GNUPLOT #ifdef MITSUBISHI rl::hal::MitsubishiH7 controller(6, "left", "lefthost"); #endif // MITSUBISHI #ifdef UNIVERSAL_ROBOTS_RTDE rl::hal::UniversalRobotsRtde controller("localhost"); #endif // UNIVERSAL_ROBOTS_RTDE rl::math::Real updateRate = std::chrono::duration_cast<std::chrono::duration<rl::math::Real>>(controller.getUpdateRate()).count(); rl::math::Vector vmax = rl::math::Vector::Constant(controller.getDof(), 5 * rl::math::constants::deg2rad); rl::math::Vector amax = rl::math::Vector::Constant(controller.getDof(), 15 * rl::math::constants::deg2rad); rl::math::Vector jmax = rl::math::Vector::Constant(controller.getDof(), 45 * rl::math::constants::deg2rad); controller.open(); controller.start(); controller.step(); rl::math::Vector q0 = controller.getJointPosition(); rl::math::Vector q1 = q0 + rl::math::Vector::Constant(controller.getDof(), 5 * rl::math::constants::deg2rad); rl::math::Vector q(controller.getDof()); #ifdef CUBIC rl::math::Polynomial<rl::math::Vector> interpolator = rl::math::Polynomial<rl::math::Vector>::CubicAtRest( #endif // CUBIC #ifdef QUINTIC rl::math::Polynomial<rl::math::Vector> interpolator = rl::math::Polynomial<rl::math::Vector>::QuinticAtRest( #endif // QUINTIC #ifdef SEPTIC rl::math::Polynomial<rl::math::Vector> interpolator = rl::math::Polynomial<rl::math::Vector>::SepticAtRest( #endif // SEPTIC #ifdef TRAPEZOIDAL rl::math::Spline<rl::math::Vector> interpolator = rl::math::Spline<rl::math::Vector>::TrapezoidalAccelerationAtRest( #endif // TRAPEZOIDAL q0, q1, vmax, amax, jmax ); std::size_t steps = static_cast<std::size_t>(std::ceil(interpolator.duration() / updateRate)) + 1; for (std::size_t i = 0; i < steps; ++i) { q = interpolator(i * updateRate); controller.setJointPosition(q); controller.step(); } #ifdef CUBIC interpolator = rl::math::Polynomial<rl::math::Vector>::CubicAtRest( #endif // CUBIC #ifdef QUINTIC interpolator = rl::math::Polynomial<rl::math::Vector>::QuinticAtRest( #endif // QUINTIC #ifdef SEPTIC interpolator = rl::math::Polynomial<rl::math::Vector>::SepticAtRest( #endif // SEPTIC #ifdef TRAPEZOIDAL interpolator = rl::math::Spline<rl::math::Vector>::TrapezoidalAccelerationAtRest( #endif // TRAPEZOIDAL q1, q0, vmax, amax, jmax ); steps = static_cast<std::size_t>(std::ceil(interpolator.duration() / updateRate)) + 1; for (std::size_t i = 0; i < steps; ++i) { q = interpolator(i * updateRate); controller.setJointPosition(q); controller.step(); } controller.stop(); controller.close(); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
Use max. velocity, acceleration, and jerk values for interpolators
Use max. velocity, acceleration, and jerk values for interpolators
C++
bsd-2-clause
roboticslibrary/rl
ec3f920477ec67a64cdcdad527a4dfe2d5fb718a
DeviceAdapters/TriggerScope/TriggerScope.cpp
DeviceAdapters/TriggerScope/TriggerScope.cpp
/////////////////////////////////////////////////////////////////////////////// // FILE: TriggerScope.h // PROJECT: Micro-Manager // SUBSYSTEM: DeviceAdapters //----------------------------------------------------------------------------- // DESCRIPTION: Implements the ARC TriggerScope device adapter. // See http://www.trggerscope.com // // AUTHOR: Austin Blanco, 5 Oct 2014 // // COPYRIGHT: Advanced Research Consulting. (2014) // // LICENSE: 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. // // 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. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // // 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 "TriggerScope.h" #include <cstdio> #include <string> #include <math.h> #include "..\..\MMDevice\ModuleInterface.h" #include "..\..\MMCore\Error.h" #include <sstream> #include <algorithm> #include <iostream> #include "TriggerScope.h" using namespace std; // External names used used by the rest of the system // to load particular device from the "TriggerScope.dll" library const char* g_TriggerScopeDeviceName = "TriggerScope"; const char* serial_terminator = "\n"; const unsigned char uc_serial_terminator = 10; const char* line_feed = "\n"; const char * g_TriggerScope_Version = "v1.0.2, 28/9/2014"; /////////////////////////////////////////////////////////////////////////////// // Exported MMDevice API /////////////////////////////////////////////////////////////////////////////// /** * List all suppoerted hardware devices here * Do not discover devices at runtime. To avoid warnings about missing DLLs, Micro-Manager * maintains a list of supported device (MMDeviceList.txt). This list is generated using * information supplied by this function, so runtime discovery will create problems. */ MODULE_API void InitializeModuleData() { RegisterDevice("TriggerScope", MM::GenericDevice, "TriggerScope"); } MODULE_API MM::Device* CreateDevice(const char* deviceName) { if (deviceName == 0) return 0; // decide which device class to create based on the deviceName parameter if (strcmp(deviceName, g_TriggerScopeDeviceName) == 0) { // create camera return new CTriggerScope(); } // ...supplied name not recognized return 0; } MODULE_API void DeleteDevice(MM::Device* pDevice) { delete pDevice; } /////////////////////////////////////////////////////////////////////////////// // CTriggerScope implementation // ~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * CTriggerScope constructor. * Setup default all variables and create device properties required to exist * before intialization. In this case, no such properties were required. All * properties will be created in the Initialize() method. * * As a general guideline Micro-Manager devices do not access hardware in the * the constructor. We should do as little as possible in the constructor and * perform most of the initialization in the Initialize() method. */ /////////////////////////////////////////////////////////////////////////////// // TriggerScope implementation // ~~~~~~~~~~~~~~~~~~~~~~~~~ CTriggerScope::CTriggerScope(void) : busy_(false), error_(0), timeOutTimer_(0), firmwareVer_(0.0), cmdInProgress_(0), initialized_(0) { // call the base class method to set-up default error codes/messages InitializeDefaultErrorMessages(); pResourceLock_ = new MMThreadLock(); //Com port CPropertyAction* pAct = new CPropertyAction (this, &CTriggerScope::OnCOMPort); //CreateProperty(MM::g_Keyword_BaudRate, "57600", MM::String, false); CreateProperty(MM::g_Keyword_Port, "", MM::String, false, pAct, true); } /** * CTriggerScope destructor. * If this device used as intended within the Micro-Manager system, * Shutdown() will be always called before the destructor. But in any case * we need to make sure that all resources are properly released even if * Shutdown() was not called. */ CTriggerScope::~CTriggerScope(void) { Shutdown(); delete pResourceLock_; } void CTriggerScope::GetName(char* Name) const { CDeviceUtils::CopyLimitedString(Name, g_TriggerScopeDeviceName); } int CTriggerScope::Initialize() { if (initialized_) return DEVICE_OK; LogMessage("Version: " + std::string(g_TriggerScope_Version)); zeroTime_ = GetCurrentMMTime(); // set property list // ----------------- // Name int ret = CreateProperty(MM::g_Keyword_Name, g_TriggerScopeDeviceName, MM::String, true); if (DEVICE_OK != ret) return ret; // Description ret = CreateProperty(MM::g_Keyword_Description, "TriggerScope", MM::String, true); if (DEVICE_OK != ret) return ret; ret = HandleErrors(); if (DEVICE_OK != ret) return ret; // Version char str[256]; cmdInProgress_ = 1; CPropertyAction* pAct = NULL; firmwareVer_ = 0.0; for(int ii=0;ii<10;ii++) { Sleep(1000); Purge(); Send("*"); ReceiveOneLine(1); if(buf_string_.length()>0) { size_t idx = buf_string_.find("ARC TRIGGERSCOPE"); if(idx!=string::npos) { idx = buf_string_.find("v."); firmwareVer_ = atof(&(buf_string_.c_str()[idx+2])); break; } } } if(firmwareVer_==0.0) return DEVICE_SERIAL_TIMEOUT; if(buf_string_.length()>0) sprintf_s(str, 256, "%s", buf_string_.c_str()); else { return DEVICE_SERIAL_TIMEOUT; } ret = CreateProperty("Firmware Version", str, MM::String, true); if (DEVICE_OK != ret) return ret; ret = CreateProperty("Software Version", g_TriggerScope_Version, MM::String, true); if (DEVICE_OK != ret) return ret; Send("STAT?"); ReceiveOneLine(1); if(buf_string_.length()>0) { } CreateProperty("COM Port", port_.c_str(), MM::String, true); pAct = new CPropertyAction (this, &CTriggerScope::OnTTL1); ret = CreateProperty("TTL 1", "0", MM::Integer, false, pAct); assert(ret == DEVICE_OK); ret = SetPropertyLimits("TTL 1", 0, 1); if (ret != DEVICE_OK) return ret; pAct = new CPropertyAction (this, &CTriggerScope::OnTTL2); ret = CreateProperty("TTL 2", "0", MM::Integer, false, pAct); assert(ret == DEVICE_OK); ret = SetPropertyLimits("TTL 2", 0, 1); if (ret != DEVICE_OK) return ret; pAct = new CPropertyAction (this, &CTriggerScope::OnDAC); ret = CreateProperty("Analog Out", "0", MM::Float, false, pAct); assert(ret == DEVICE_OK); ret = SetPropertyLimits("Analog Out", 0, 5); if (ret != DEVICE_OK) return ret; ret = UpdateStatus(); if (ret != DEVICE_OK) return ret; initialized_ = true; cmdInProgress_ = 0; //thd_->Start(); return DEVICE_OK; } /** * Shuts down (unloads) the device. * Required by the MM::Device API. * Ideally this method will completely unload the device and release all resources. * Shutdown() may be called multiple times in a row. * After Shutdown() we should be allowed to call Initialize() again to load the device * without causing problems. */ int CTriggerScope::Shutdown() { if (initialized_) { initialized_ = false; } return DEVICE_OK; } bool CTriggerScope::Busy() { if (timeOutTimer_ == 0) return false; if (timeOutTimer_->expired(GetCurrentMMTime())) { // delete(timeOutTimer_); return false; } return true; } int CTriggerScope::HandleErrors() { int lastError = error_; error_ = 0; return lastError; } /////////////////////////////////////////////////////////////////////////////// // Action handlers /////////////////////////////////////////////////////////////////////////////// // none implemented int CTriggerScope::OnCOMPort(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(port_.c_str()); } else if (eAct == MM::AfterSet) { if (initialized_) { // revert pProp->Set(port_.c_str()); } pProp->Get(port_); } return DEVICE_OK; } int CTriggerScope::OnTTL1(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(ttl1_); } else if (eAct == MM::AfterSet) { pProp->Get(ttl1_); char str[16]; sprintf_s(str, "TTL1,%d",ttl1_); Purge(); Send(str); ReceiveOneLine(); if(buf_string_.length()==0) { Purge(); Send(str); ReceiveOneLine(); } } return DEVICE_OK; } int CTriggerScope::OnTTL2(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(ttl2_); } else if (eAct == MM::AfterSet) { pProp->Get(ttl2_); char str[16]; sprintf_s(str, "TTL2,%d",ttl2_); Purge(); Send(str); ReceiveOneLine(); if(buf_string_.length()==0) { Purge(); Send(str); ReceiveOneLine(); } } return DEVICE_OK; } int CTriggerScope::OnDAC(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(dac_); } else if (eAct == MM::AfterSet) { pProp->Get(dac_); char str[16]; // 12 bit DAC, 5V max sprintf_s(str, "DAC,%d",int(4095.0*dac_/5.0)); Purge(); Send(str); ReceiveOneLine(); if(buf_string_.length()==0) { Purge(); Send(str); ReceiveOneLine(); } } return DEVICE_OK; } ///////////////////////////////////// // Communications ///////////////////////////////////// void CTriggerScope::Send(string cmd) { int ret = SendSerialCommand(port_.c_str(), cmd.c_str(), serial_terminator); if (ret!=DEVICE_OK) error_ = DEVICE_SERIAL_COMMAND_FAILED; } void CTriggerScope::SendSerialBytes(unsigned char* cmd, unsigned long len) { int ret = WriteToComPort(port_.c_str(), cmd, len); if (ret!=DEVICE_OK) error_ = DEVICE_SERIAL_COMMAND_FAILED; } void CTriggerScope::ReceiveOneLine(int nLoopMax) { buf_string_ = ""; int nLoop=0, nRet=-1; string buf_str; while(nRet!=0 && nLoop<nLoopMax) { nRet = GetSerialAnswer(port_.c_str(), serial_terminator, buf_str); nLoop++; if(buf_str.length()>0) buf_string_.append(buf_str); } if(nLoop>1) nLoop += 0; } void CTriggerScope::ReceiveSerialBytes(unsigned char* buf, unsigned long buflen, unsigned long bytesToRead, unsigned long &totalBytes) { buf_string_ = ""; int nLoop=0, nRet=0; unsigned long bytesRead=0; totalBytes=0; buf[0] = NULL; MM::MMTime timeStart, timeNow; timeStart = GetCurrentMMTime(); while(nRet==0 && totalBytes < bytesToRead && (timeNow.getMsec()-timeStart.getMsec()) < 5000) { nRet = ReadFromComPort(port_.c_str(), &buf[totalBytes], buflen-totalBytes, bytesRead); nLoop++; totalBytes += bytesRead; timeNow = GetCurrentMMTime(); Sleep(1); } if(nLoop>1) nLoop += 0; } void CTriggerScope::FlushSerialBytes(unsigned char* buf, unsigned long buflen) { buf_string_ = ""; int nRet=0; unsigned long bytesRead=0; buf[0] = NULL; nRet = ReadFromComPort(port_.c_str(), buf, buflen, bytesRead); } void CTriggerScope::Purge() { int ret = PurgeComPort(port_.c_str()); if (ret!=0) error_ = DEVICE_SERIAL_COMMAND_FAILED; }
/////////////////////////////////////////////////////////////////////////////// // FILE: TriggerScope.h // PROJECT: Micro-Manager // SUBSYSTEM: DeviceAdapters //----------------------------------------------------------------------------- // DESCRIPTION: Implements the ARC TriggerScope device adapter. // See http://www.trggerscope.com // // AUTHOR: Austin Blanco, 5 Oct 2014 // // COPYRIGHT: Advanced Research Consulting. (2014) // // LICENSE: 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. // // 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. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // // 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 "TriggerScope.h" #include "ModuleInterface.h" #include <algorithm> #include <cstdio> #include <iostream> #include <cmath> #include <sstream> #include <string> using namespace std; // External names used used by the rest of the system // to load particular device from the "TriggerScope.dll" library const char* g_TriggerScopeDeviceName = "TriggerScope"; const char* serial_terminator = "\n"; const unsigned char uc_serial_terminator = 10; const char* line_feed = "\n"; const char * g_TriggerScope_Version = "v1.0.2, 28/9/2014"; /////////////////////////////////////////////////////////////////////////////// // Exported MMDevice API /////////////////////////////////////////////////////////////////////////////// /** * List all suppoerted hardware devices here * Do not discover devices at runtime. To avoid warnings about missing DLLs, Micro-Manager * maintains a list of supported device (MMDeviceList.txt). This list is generated using * information supplied by this function, so runtime discovery will create problems. */ MODULE_API void InitializeModuleData() { RegisterDevice("TriggerScope", MM::GenericDevice, "TriggerScope"); } MODULE_API MM::Device* CreateDevice(const char* deviceName) { if (deviceName == 0) return 0; // decide which device class to create based on the deviceName parameter if (strcmp(deviceName, g_TriggerScopeDeviceName) == 0) { // create camera return new CTriggerScope(); } // ...supplied name not recognized return 0; } MODULE_API void DeleteDevice(MM::Device* pDevice) { delete pDevice; } /////////////////////////////////////////////////////////////////////////////// // CTriggerScope implementation // ~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * CTriggerScope constructor. * Setup default all variables and create device properties required to exist * before intialization. In this case, no such properties were required. All * properties will be created in the Initialize() method. * * As a general guideline Micro-Manager devices do not access hardware in the * the constructor. We should do as little as possible in the constructor and * perform most of the initialization in the Initialize() method. */ /////////////////////////////////////////////////////////////////////////////// // TriggerScope implementation // ~~~~~~~~~~~~~~~~~~~~~~~~~ CTriggerScope::CTriggerScope(void) : busy_(false), error_(0), timeOutTimer_(0), firmwareVer_(0.0), cmdInProgress_(0), initialized_(0) { // call the base class method to set-up default error codes/messages InitializeDefaultErrorMessages(); pResourceLock_ = new MMThreadLock(); //Com port CPropertyAction* pAct = new CPropertyAction (this, &CTriggerScope::OnCOMPort); //CreateProperty(MM::g_Keyword_BaudRate, "57600", MM::String, false); CreateProperty(MM::g_Keyword_Port, "", MM::String, false, pAct, true); } /** * CTriggerScope destructor. * If this device used as intended within the Micro-Manager system, * Shutdown() will be always called before the destructor. But in any case * we need to make sure that all resources are properly released even if * Shutdown() was not called. */ CTriggerScope::~CTriggerScope(void) { Shutdown(); delete pResourceLock_; } void CTriggerScope::GetName(char* Name) const { CDeviceUtils::CopyLimitedString(Name, g_TriggerScopeDeviceName); } int CTriggerScope::Initialize() { if (initialized_) return DEVICE_OK; LogMessage("Version: " + std::string(g_TriggerScope_Version)); zeroTime_ = GetCurrentMMTime(); // set property list // ----------------- // Name int ret = CreateProperty(MM::g_Keyword_Name, g_TriggerScopeDeviceName, MM::String, true); if (DEVICE_OK != ret) return ret; // Description ret = CreateProperty(MM::g_Keyword_Description, "TriggerScope", MM::String, true); if (DEVICE_OK != ret) return ret; ret = HandleErrors(); if (DEVICE_OK != ret) return ret; // Version cmdInProgress_ = 1; firmwareVer_ = 0.0; for(int ii=0;ii<10;ii++) { CDeviceUtils::SleepMs(1000); Purge(); Send("*"); ReceiveOneLine(1); if(buf_string_.length()>0) { size_t idx = buf_string_.find("ARC TRIGGERSCOPE"); if(idx!=string::npos) { idx = buf_string_.find("v."); firmwareVer_ = atof(&(buf_string_.c_str()[idx+2])); break; } } } if(firmwareVer_==0.0) return DEVICE_SERIAL_TIMEOUT; std::string versionString; if(buf_string_.length()>0) { versionString = buf_string_.substr(0, 255); } else { return DEVICE_SERIAL_TIMEOUT; } ret = CreateProperty("Firmware Version", versionString.c_str(), MM::String, true); if (DEVICE_OK != ret) return ret; ret = CreateProperty("Software Version", g_TriggerScope_Version, MM::String, true); if (DEVICE_OK != ret) return ret; Send("STAT?"); ReceiveOneLine(1); if(buf_string_.length()>0) { } CreateProperty("COM Port", port_.c_str(), MM::String, true); CPropertyAction* pAct = NULL; pAct = new CPropertyAction (this, &CTriggerScope::OnTTL1); ret = CreateProperty("TTL 1", "0", MM::Integer, false, pAct); assert(ret == DEVICE_OK); ret = SetPropertyLimits("TTL 1", 0, 1); if (ret != DEVICE_OK) return ret; pAct = new CPropertyAction (this, &CTriggerScope::OnTTL2); ret = CreateProperty("TTL 2", "0", MM::Integer, false, pAct); assert(ret == DEVICE_OK); ret = SetPropertyLimits("TTL 2", 0, 1); if (ret != DEVICE_OK) return ret; pAct = new CPropertyAction (this, &CTriggerScope::OnDAC); ret = CreateProperty("Analog Out", "0", MM::Float, false, pAct); assert(ret == DEVICE_OK); ret = SetPropertyLimits("Analog Out", 0, 5); if (ret != DEVICE_OK) return ret; ret = UpdateStatus(); if (ret != DEVICE_OK) return ret; initialized_ = true; cmdInProgress_ = 0; //thd_->Start(); return DEVICE_OK; } /** * Shuts down (unloads) the device. * Required by the MM::Device API. * Ideally this method will completely unload the device and release all resources. * Shutdown() may be called multiple times in a row. * After Shutdown() we should be allowed to call Initialize() again to load the device * without causing problems. */ int CTriggerScope::Shutdown() { if (initialized_) { initialized_ = false; } return DEVICE_OK; } bool CTriggerScope::Busy() { if (timeOutTimer_ == 0) return false; if (timeOutTimer_->expired(GetCurrentMMTime())) { // delete(timeOutTimer_); return false; } return true; } int CTriggerScope::HandleErrors() { int lastError = error_; error_ = 0; return lastError; } /////////////////////////////////////////////////////////////////////////////// // Action handlers /////////////////////////////////////////////////////////////////////////////// // none implemented int CTriggerScope::OnCOMPort(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(port_.c_str()); } else if (eAct == MM::AfterSet) { if (initialized_) { // revert pProp->Set(port_.c_str()); } pProp->Get(port_); } return DEVICE_OK; } int CTriggerScope::OnTTL1(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(ttl1_); } else if (eAct == MM::AfterSet) { pProp->Get(ttl1_); std::ostringstream oss; oss << "TTL1," << ttl1_; std::string command = oss.str(); Purge(); Send(command); ReceiveOneLine(); if(buf_string_.length()==0) { Purge(); Send(command); ReceiveOneLine(); } } return DEVICE_OK; } int CTriggerScope::OnTTL2(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(ttl2_); } else if (eAct == MM::AfterSet) { pProp->Get(ttl2_); std::ostringstream oss; oss << "TTL2," << ttl2_; std::string command = oss.str(); Purge(); Send(command); ReceiveOneLine(); if(buf_string_.length()==0) { Purge(); Send(command); ReceiveOneLine(); } } return DEVICE_OK; } int CTriggerScope::OnDAC(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(dac_); } else if (eAct == MM::AfterSet) { pProp->Get(dac_); // 12 bit DAC, 5V max std::ostringstream oss; oss << "DAC," << int(4095.0*dac_/5.0); std::string command = oss.str(); Purge(); Send(command); ReceiveOneLine(); if(buf_string_.length()==0) { Purge(); Send(command); ReceiveOneLine(); } } return DEVICE_OK; } ///////////////////////////////////// // Communications ///////////////////////////////////// void CTriggerScope::Send(string cmd) { int ret = SendSerialCommand(port_.c_str(), cmd.c_str(), serial_terminator); if (ret!=DEVICE_OK) error_ = DEVICE_SERIAL_COMMAND_FAILED; } void CTriggerScope::SendSerialBytes(unsigned char* cmd, unsigned long len) { int ret = WriteToComPort(port_.c_str(), cmd, len); if (ret!=DEVICE_OK) error_ = DEVICE_SERIAL_COMMAND_FAILED; } void CTriggerScope::ReceiveOneLine(int nLoopMax) { buf_string_ = ""; int nLoop=0, nRet=-1; string buf_str; while(nRet!=0 && nLoop<nLoopMax) { nRet = GetSerialAnswer(port_.c_str(), serial_terminator, buf_str); nLoop++; if(buf_str.length()>0) buf_string_.append(buf_str); } if(nLoop>1) nLoop += 0; } void CTriggerScope::ReceiveSerialBytes(unsigned char* buf, unsigned long buflen, unsigned long bytesToRead, unsigned long &totalBytes) { buf_string_ = ""; int nLoop=0, nRet=0; unsigned long bytesRead=0; totalBytes=0; buf[0] = NULL; MM::MMTime timeStart, timeNow; timeStart = GetCurrentMMTime(); while(nRet==0 && totalBytes < bytesToRead && (timeNow.getMsec()-timeStart.getMsec()) < 5000) { nRet = ReadFromComPort(port_.c_str(), &buf[totalBytes], buflen-totalBytes, bytesRead); nLoop++; totalBytes += bytesRead; timeNow = GetCurrentMMTime(); CDeviceUtils::SleepMs(1); } if(nLoop>1) nLoop += 0; } void CTriggerScope::FlushSerialBytes(unsigned char* buf, unsigned long buflen) { buf_string_ = ""; int nRet=0; unsigned long bytesRead=0; buf[0] = NULL; nRet = ReadFromComPort(port_.c_str(), buf, buflen, bytesRead); } void CTriggerScope::Purge() { int ret = PurgeComPort(port_.c_str()); if (ret!=0) error_ = DEVICE_SERIAL_COMMAND_FAILED; }
Remove use of Microsoft-only functions
TriggerScope: Remove use of Microsoft-only functions git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@14961 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
C++
mit
kmdouglass/Micro-Manager,kmdouglass/Micro-Manager
2dede8bfbab5d353f91acc5f5fa7c21b1b1a4fea
sal/osl/unx/mutex.cxx
sal/osl/unx/mutex.cxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ #if defined LINUX // to define __USE_UNIX98, via _XOPEN_SOURCE, enabling pthread_mutexattr_settype #ifndef _GNU_SOURCE #define _GNU_SOURCE 1 #endif #endif #include "system.hxx" #include <osl/mutex.h> #include <osl/diagnose.h> #include <pthread.h> #include <stdlib.h> typedef struct _oslMutexImpl { pthread_mutex_t mutex; } oslMutexImpl; /*****************************************************************************/ /* osl_createMutex */ /*****************************************************************************/ oslMutex SAL_CALL osl_createMutex() { oslMutexImpl* pMutex = static_cast<oslMutexImpl*>(malloc(sizeof(oslMutexImpl))); pthread_mutexattr_t aMutexAttr; int nRet=0; OSL_ASSERT(pMutex); if ( pMutex == 0 ) { return 0; } pthread_mutexattr_init(&aMutexAttr); nRet = pthread_mutexattr_settype(&aMutexAttr, PTHREAD_MUTEX_RECURSIVE); if( nRet == 0 ) nRet = pthread_mutex_init(&(pMutex->mutex), &aMutexAttr); if ( nRet != 0 ) { OSL_TRACE("osl_createMutex : mutex init/setattr failed. Errno: %d; %s\n", nRet, strerror(nRet)); free(pMutex); pMutex = 0; } pthread_mutexattr_destroy(&aMutexAttr); return pMutex; } void SAL_CALL osl_destroyMutex(oslMutexImpl *pMutex) { OSL_ASSERT(pMutex); if ( pMutex != 0 ) { int nRet=0; nRet = pthread_mutex_destroy(&(pMutex->mutex)); if ( nRet != 0 ) { OSL_TRACE("osl_destroyMutex : mutex destroy failed. Errno: %d; %s\n", nRet, strerror(nRet)); } free(pMutex); } return; } sal_Bool SAL_CALL osl_acquireMutex(oslMutexImpl *pMutex) { OSL_ASSERT(pMutex); if ( pMutex != 0 ) { int nRet=0; nRet = pthread_mutex_lock(&(pMutex->mutex)); if ( nRet != 0 ) { OSL_TRACE("osl_acquireMutex : mutex lock failed. Errno: %d; %s\n", nRet, strerror(nRet)); return sal_False; } return sal_True; } /* not initialized */ return sal_False; } sal_Bool SAL_CALL osl_tryToAcquireMutex(oslMutexImpl *pMutex) { OSL_ASSERT(pMutex); if ( pMutex ) { int nRet = 0; nRet = pthread_mutex_trylock(&(pMutex->mutex)); if ( nRet != 0 ) return sal_False; return sal_True; } /* not initialized */ return sal_False; } sal_Bool SAL_CALL osl_releaseMutex(oslMutexImpl *pMutex) { OSL_ASSERT(pMutex); if ( pMutex ) { int nRet=0; nRet = pthread_mutex_unlock(&(pMutex->mutex)); if ( nRet != 0 ) { OSL_TRACE("osl_releaseMutex : mutex unlock failed. Errno: %d; %s\n", nRet, strerror(nRet)); return sal_False; } return sal_True; } /* not initialized */ return sal_False; } static oslMutexImpl globalMutexImpl; static void globalMutexInitImpl(void) { pthread_mutexattr_t attr; if (pthread_mutexattr_init(&attr) != 0 || pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) || pthread_mutex_init(&globalMutexImpl.mutex, &attr) != 0 || pthread_mutexattr_destroy(&attr) != 0) { abort(); } } oslMutex * SAL_CALL osl_getGlobalMutex() { /* necessary to get a "oslMutex *" */ static oslMutex globalMutex = (oslMutex) &globalMutexImpl; static pthread_once_t once = PTHREAD_ONCE_INIT; if (pthread_once(&once, &globalMutexInitImpl) != 0) { abort(); } return &globalMutex; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ #if defined LINUX // to define __USE_UNIX98, via _XOPEN_SOURCE, enabling pthread_mutexattr_settype #ifndef _GNU_SOURCE #define _GNU_SOURCE 1 #endif #endif #include "system.hxx" #include <sal/log.hxx> #include <osl/mutex.h> #include <pthread.h> #include <stdlib.h> typedef struct _oslMutexImpl { pthread_mutex_t mutex; } oslMutexImpl; oslMutex SAL_CALL osl_createMutex() { oslMutexImpl* pMutex = static_cast<oslMutexImpl*>(malloc(sizeof(oslMutexImpl))); pthread_mutexattr_t aMutexAttr; int nRet=0; SAL_WARN_IF(!pMutex, "sal.osl.mutex", "null pMutex"); if ( pMutex == 0 ) { return 0; } pthread_mutexattr_init(&aMutexAttr); nRet = pthread_mutexattr_settype(&aMutexAttr, PTHREAD_MUTEX_RECURSIVE); if( nRet == 0 ) nRet = pthread_mutex_init(&(pMutex->mutex), &aMutexAttr); if ( nRet != 0 ) { SAL_WARN("sal.osl.mutex", "pthread_muxex_init failed: " << strerror(nRet)); free(pMutex); pMutex = 0; } pthread_mutexattr_destroy(&aMutexAttr); SAL_INFO("sal.osl.mutex", "osl_createMutex(): " << pMutex); return pMutex; } void SAL_CALL osl_destroyMutex(oslMutexImpl *pMutex) { SAL_WARN_IF(!pMutex, "sal.osl.mutex", "null pMutex"); SAL_INFO("sal.osl.mutex", "osl_destroyMutex(" << pMutex << ")"); if ( pMutex != 0 ) { int nRet=0; nRet = pthread_mutex_destroy(&(pMutex->mutex)); if ( nRet != 0 ) { SAL_WARN("sal.osl.mutex", "pthread_mutex_destroy failed: " << strerror(nRet)); } free(pMutex); } return; } sal_Bool SAL_CALL osl_acquireMutex(oslMutexImpl *pMutex) { SAL_WARN_IF(!pMutex, "sal.osl.mutex", "null pMutex"); SAL_INFO("sal.osl.mutex", "osl_acquireMutex(" << pMutex << ")"); if ( pMutex != 0 ) { int nRet=0; nRet = pthread_mutex_lock(&(pMutex->mutex)); if ( nRet != 0 ) { SAL_WARN("sal.osl.mutex", "pthread_mutex_lock failed: " << strerror(nRet)); return sal_False; } return sal_True; } /* not initialized */ return sal_False; } sal_Bool SAL_CALL osl_tryToAcquireMutex(oslMutexImpl *pMutex) { sal_Bool result = sal_False; SAL_WARN_IF(!pMutex, "sal.osl.mutex", "null pMutex"); if ( pMutex ) { int nRet = 0; nRet = pthread_mutex_trylock(&(pMutex->mutex)); if ( nRet == 0 ) result = sal_True; } SAL_INFO("sal.osl.mutex", "osl_tryToAcquireMutex(" << pMutex << "): " << (result ? "YES" : "NO")); return result; } sal_Bool SAL_CALL osl_releaseMutex(oslMutexImpl *pMutex) { SAL_WARN_IF(!pMutex, "sal.osl.mutex", "null pMutex"); SAL_INFO("sal.osl.mutex", "osl_releaseMutex(" << pMutex << ")"); if ( pMutex ) { int nRet=0; nRet = pthread_mutex_unlock(&(pMutex->mutex)); if ( nRet != 0 ) { SAL_WARN("sal.osl.mutex", "pthread_mutex_unlock failed: " << strerror(nRet)); return sal_False; } return sal_True; } /* not initialized */ return sal_False; } static oslMutexImpl globalMutexImpl; static void globalMutexInitImpl(void) { pthread_mutexattr_t attr; if (pthread_mutexattr_init(&attr) != 0 || pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) || pthread_mutex_init(&globalMutexImpl.mutex, &attr) != 0 || pthread_mutexattr_destroy(&attr) != 0) { abort(); } } oslMutex * SAL_CALL osl_getGlobalMutex() { /* necessary to get a "oslMutex *" */ static oslMutex globalMutex = (oslMutex) &globalMutexImpl; static pthread_once_t once = PTHREAD_ONCE_INIT; if (pthread_once(&once, &globalMutexInitImpl) != 0) { abort(); } return &globalMutex; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
Change from <osl/diagnose.h> to <sal/log.hxx> and add more logging
Change from <osl/diagnose.h> to <sal/log.hxx> and add more logging Change-Id: Iee8c093f5aa8306c3e5336d6dd5e801df6df87a4
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
593d202efa21266934edf5cb5d4c68077d67fe16
external/grpc/src/core/lib/gpr/thd_posix.cc
external/grpc/src/core/lib/gpr/thd_posix.cc
/* * * Copyright 2015 gRPC authors. * * 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. * */ /* Posix implementation for gpr threads. */ #include <grpc/support/port_platform.h> #ifdef GPR_POSIX_SYNC #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/sync.h> #include <grpc/support/thd.h> #include <grpc/support/useful.h> #include <pthread.h> #include <stdlib.h> #include <string.h> #include "src/core/lib/gpr/fork.h" static gpr_mu g_mu; static gpr_cv g_cv; static int g_thread_count; static int g_awaiting_threads; struct thd_arg { void (*body)(void* arg); /* body of a thread */ void* arg; /* argument to a thread */ const char* name; /* name of thread. Can be nullptr. */ }; static void inc_thd_count(); static void dec_thd_count(); /* Body of every thread started via gpr_thd_new. */ static void* thread_body(void* v) { struct thd_arg a = *(struct thd_arg*)v; free(v); if (a.name != nullptr) { #if GPR_APPLE_PTHREAD_NAME /* Apple supports 64 characters, and will truncate if it's longer. */ pthread_setname_np(a.name); #elif GPR_TIZENRT_PTHREAD_NAME pthread_setname_np(pthread_self(), a.name); #elif GPR_LINUX_PTHREAD_NAME /* Linux supports 16 characters max, and will error if it's longer. */ char buf[16]; size_t buf_len = GPR_ARRAY_SIZE(buf) - 1; strncpy(buf, a.name, buf_len); buf[buf_len] = '\0'; pthread_setname_np(pthread_self(), buf); #endif // GPR_APPLE_PTHREAD_NAME } (*a.body)(a.arg); dec_thd_count(); return nullptr; } #ifndef GRPC_THD_CLIENT_STACK_SIZE #ifdef __TizenRT__ #include <tinyara/config.h> #define GRPC_THD_CLIENT_STACK_SIZE CONFIG_GRPC_PTHREAD_SIZE #else #define GRPC_THD_CLIENT_STACK_SIZE 10240 #endif #endif int gpr_thd_new(gpr_thd_id* t, const char* thd_name, void (*thd_body)(void* arg), void* arg, const gpr_thd_options* options) { int thread_started; pthread_attr_t attr; pthread_t p; /* don't use gpr_malloc as we may cause an infinite recursion with * the profiling code */ struct thd_arg* a = (struct thd_arg*)malloc(sizeof(*a)); GPR_ASSERT(a != nullptr); a->body = thd_body; a->arg = arg; a->name = thd_name; inc_thd_count(); GPR_ASSERT(pthread_attr_init(&attr) == 0); // TODO(TizenRT) #ifndef __TizenRT__ if (gpr_thd_options_is_detached(options)) { GPR_ASSERT(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) == 0); } else { GPR_ASSERT(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE) == 0); } #else int r; if ((r = pthread_attr_setstacksize(&attr, GRPC_THD_CLIENT_STACK_SIZE)) != 0) { return -1; } #endif thread_started = (pthread_create(&p, &attr, &thread_body, a) == 0); GPR_ASSERT(pthread_attr_destroy(&attr) == 0); if (!thread_started) { /* don't use gpr_free, as this was allocated using malloc (see above) */ free(a); dec_thd_count(); } else { pthread_setname_np(thread_started, a->name); } *t = (gpr_thd_id)p; return thread_started; } gpr_thd_id gpr_thd_currentid(void) { return (gpr_thd_id)pthread_self(); } void gpr_thd_join(gpr_thd_id t) { pthread_join((pthread_t)t, nullptr); } /***************************************** * Only used when fork support is enabled */ static void inc_thd_count() { if (grpc_fork_support_enabled()) { gpr_mu_lock(&g_mu); g_thread_count++; gpr_mu_unlock(&g_mu); } } static void dec_thd_count() { if (grpc_fork_support_enabled()) { gpr_mu_lock(&g_mu); g_thread_count--; if (g_awaiting_threads && g_thread_count == 0) { gpr_cv_signal(&g_cv); } gpr_mu_unlock(&g_mu); } } void gpr_thd_init() { gpr_mu_init(&g_mu); gpr_cv_init(&g_cv); g_thread_count = 0; g_awaiting_threads = 0; } int gpr_await_threads(gpr_timespec deadline) { gpr_mu_lock(&g_mu); g_awaiting_threads = 1; int res = 0; if (g_thread_count > 0) { res = gpr_cv_wait(&g_cv, &g_mu, deadline); } g_awaiting_threads = 0; gpr_mu_unlock(&g_mu); return res == 0; } #endif /* GPR_POSIX_SYNC */
/* * * Copyright 2015 gRPC authors. * * 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. * */ /* Posix implementation for gpr threads. */ #include <grpc/support/port_platform.h> #ifdef GPR_POSIX_SYNC #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/sync.h> #include <grpc/support/thd.h> #include <grpc/support/useful.h> #include <pthread.h> #include <stdlib.h> #include <string.h> #include "src/core/lib/gpr/fork.h" static gpr_mu g_mu; static gpr_cv g_cv; static int g_thread_count; static int g_awaiting_threads; struct thd_arg { void (*body)(void* arg); /* body of a thread */ void* arg; /* argument to a thread */ const char* name; /* name of thread. Can be nullptr. */ }; static void inc_thd_count(); static void dec_thd_count(); /* Body of every thread started via gpr_thd_new. */ static void* thread_body(void* v) { struct thd_arg a = *(struct thd_arg*)v; free(v); if (a.name != nullptr) { #if GPR_APPLE_PTHREAD_NAME /* Apple supports 64 characters, and will truncate if it's longer. */ pthread_setname_np(a.name); #elif GPR_TIZENRT_PTHREAD_NAME pthread_setname_np(pthread_self(), a.name); #elif GPR_LINUX_PTHREAD_NAME /* Linux supports 16 characters max, and will error if it's longer. */ char buf[16]; size_t buf_len = GPR_ARRAY_SIZE(buf) - 1; strncpy(buf, a.name, buf_len); buf[buf_len] = '\0'; pthread_setname_np(pthread_self(), buf); #endif // GPR_APPLE_PTHREAD_NAME } (*a.body)(a.arg); dec_thd_count(); return nullptr; } #ifndef GRPC_THD_CLIENT_STACK_SIZE #ifdef __TizenRT__ #include <tinyara/config.h> #define GRPC_THD_CLIENT_STACK_SIZE CONFIG_GRPC_PTHREAD_SIZE #else #define GRPC_THD_CLIENT_STACK_SIZE 10240 #endif #endif int gpr_thd_new(gpr_thd_id* t, const char* thd_name, void (*thd_body)(void* arg), void* arg, const gpr_thd_options* options) { int thread_started; pthread_attr_t attr; pthread_t p; /* don't use gpr_malloc as we may cause an infinite recursion with * the profiling code */ struct thd_arg* a = (struct thd_arg*)malloc(sizeof(*a)); GPR_ASSERT(a != nullptr); a->body = thd_body; a->arg = arg; a->name = thd_name; inc_thd_count(); GPR_ASSERT(pthread_attr_init(&attr) == 0); // TODO(TizenRT) #ifndef __TizenRT__ if (gpr_thd_options_is_detached(options)) { GPR_ASSERT(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) == 0); } else { GPR_ASSERT(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE) == 0); } #else int r; if ((r = pthread_attr_setstacksize(&attr, GRPC_THD_CLIENT_STACK_SIZE)) != 0) { return -1; } #endif thread_started = (pthread_create(&p, &attr, &thread_body, a) == 0); GPR_ASSERT(pthread_attr_destroy(&attr) == 0); if (!thread_started) { /* don't use gpr_free, as this was allocated using malloc (see above) */ free(a); dec_thd_count(); } else { pthread_setname_np(p, a->name); } *t = (gpr_thd_id)p; return thread_started; } gpr_thd_id gpr_thd_currentid(void) { return (gpr_thd_id)pthread_self(); } void gpr_thd_join(gpr_thd_id t) { pthread_join((pthread_t)t, nullptr); } /***************************************** * Only used when fork support is enabled */ static void inc_thd_count() { if (grpc_fork_support_enabled()) { gpr_mu_lock(&g_mu); g_thread_count++; gpr_mu_unlock(&g_mu); } } static void dec_thd_count() { if (grpc_fork_support_enabled()) { gpr_mu_lock(&g_mu); g_thread_count--; if (g_awaiting_threads && g_thread_count == 0) { gpr_cv_signal(&g_cv); } gpr_mu_unlock(&g_mu); } } void gpr_thd_init() { gpr_mu_init(&g_mu); gpr_cv_init(&g_cv); g_thread_count = 0; g_awaiting_threads = 0; } int gpr_await_threads(gpr_timespec deadline) { gpr_mu_lock(&g_mu); g_awaiting_threads = 1; int res = 0; if (g_thread_count > 0) { res = gpr_cv_wait(&g_cv, &g_mu, deadline); } g_awaiting_threads = 0; gpr_mu_unlock(&g_mu); return res == 0; } #endif /* GPR_POSIX_SYNC */
fix grpc thread name
external/grpc: fix grpc thread name - fix grpc thread naming issue
C++
apache-2.0
jeongchanKim/TizenRT,pillip8282/TizenRT,JeonginKim/TizenRT,sunghan-chang/TizenRT,jsdosa/TizenRT,junmin-kim/TizenRT,jeongchanKim/TizenRT,jeongarmy/TizenRT,sunghan-chang/TizenRT,HONGCHAEHEE/TizenRT,Samsung/TizenRT,davidfather/TizenRT,pillip8282/TizenRT,pillip8282/TizenRT,jeongarmy/TizenRT,chanijjani/TizenRT,junmin-kim/TizenRT,an4967/TizenRT,chanijjani/TizenRT,Samsung/TizenRT,JeonginKim/TizenRT,Samsung/TizenRT,davidfather/TizenRT,an4967/TizenRT,an4967/TizenRT,JeonginKim/TizenRT,jsdosa/TizenRT,sunghan-chang/TizenRT,jeongchanKim/TizenRT,jsdosa/TizenRT,junmin-kim/TizenRT,jsdosa/TizenRT,HONGCHAEHEE/TizenRT,jsdosa/TizenRT,HONGCHAEHEE/TizenRT,JeonginKim/TizenRT,jeongarmy/TizenRT,sunghan-chang/TizenRT,an4967/TizenRT,junmin-kim/TizenRT,chanijjani/TizenRT,davidfather/TizenRT,sunghan-chang/TizenRT,an4967/TizenRT,junmin-kim/TizenRT,chanijjani/TizenRT,pillip8282/TizenRT,jeongchanKim/TizenRT,jeongchanKim/TizenRT,HONGCHAEHEE/TizenRT,JeonginKim/TizenRT,Samsung/TizenRT,davidfather/TizenRT,Samsung/TizenRT,pillip8282/TizenRT,jeongchanKim/TizenRT,davidfather/TizenRT,jeongchanKim/TizenRT,junmin-kim/TizenRT,davidfather/TizenRT,JeonginKim/TizenRT,pillip8282/TizenRT,jeongarmy/TizenRT,chanijjani/TizenRT,chanijjani/TizenRT,jsdosa/TizenRT,davidfather/TizenRT,jsdosa/TizenRT,jeongarmy/TizenRT,jeongarmy/TizenRT,HONGCHAEHEE/TizenRT,an4967/TizenRT,Samsung/TizenRT,sunghan-chang/TizenRT,Samsung/TizenRT,jeongarmy/TizenRT,an4967/TizenRT,chanijjani/TizenRT,HONGCHAEHEE/TizenRT,junmin-kim/TizenRT,sunghan-chang/TizenRT,pillip8282/TizenRT
1da7fc4c6ade06ce0a458b56531c26b3cd0366a3
Source/Drivers/PS1080/Sensor/XnBayerImageProcessor.cpp
Source/Drivers/PS1080/Sensor/XnBayerImageProcessor.cpp
/***************************************************************************** * * * OpenNI 2.x Alpha * * Copyright (C) 2012 PrimeSense Ltd. * * * * This file is part of OpenNI. * * * * 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. * * * *****************************************************************************/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include "XnBayerImageProcessor.h" #include "Uncomp.h" #include "Bayer.h" #include <XnProfiling.h> //--------------------------------------------------------------------------- // Code //--------------------------------------------------------------------------- XnBayerImageProcessor::XnBayerImageProcessor(XnSensorImageStream* pStream, XnSensorStreamHelper* pHelper, XnFrameBufferManager* pBufferManager) : XnImageProcessor(pStream, pHelper, pBufferManager) { } XnBayerImageProcessor::~XnBayerImageProcessor() { } XnStatus XnBayerImageProcessor::Init() { XnStatus nRetVal = XN_STATUS_OK; nRetVal = XnImageProcessor::Init(); XN_IS_STATUS_OK(nRetVal); XN_VALIDATE_BUFFER_ALLOCATE(m_ContinuousBuffer, GetExpectedOutputSize()); switch (GetStream()->GetOutputFormat()) { case ONI_PIXEL_FORMAT_GRAY8: break; case ONI_PIXEL_FORMAT_RGB888: XN_VALIDATE_BUFFER_ALLOCATE(m_UncompressedBayerBuffer, GetExpectedOutputSize()); break; default: XN_LOG_WARNING_RETURN(XN_STATUS_ERROR, XN_MASK_SENSOR_PROTOCOL_IMAGE, "Unsupported image output format: %d", GetStream()->GetOutputFormat()); } return (XN_STATUS_OK); } void XnBayerImageProcessor::ProcessFramePacketChunk(const XnSensorProtocolResponseHeader* pHeader, const XnUChar* pData, XnUInt32 nDataOffset, XnUInt32 nDataSize) { XN_PROFILING_START_SECTION("XnBayerImageProcessor::ProcessFramePacketChunk") // if output format is Gray8, we can write directly to output buffer. otherwise, we need // to write to a temp buffer. XnBuffer* pWriteBuffer = (GetStream()->GetOutputFormat() == ONI_PIXEL_FORMAT_GRAY8) ? GetWriteBuffer() : &m_UncompressedBayerBuffer; const XnUChar* pBuf = NULL; XnUInt32 nBufSize = 0; // check if we have bytes stored from previous calls if (m_ContinuousBuffer.GetSize() > 0) { // we have no choice. We need to append current buffer to previous bytes if (m_ContinuousBuffer.GetFreeSpaceInBuffer() < nDataSize) { xnLogWarning(XN_MASK_SENSOR_PROTOCOL_DEPTH, "Bad overflow image! %d", m_ContinuousBuffer.GetSize()); FrameIsCorrupted(); } else { m_ContinuousBuffer.UnsafeWrite(pData, nDataSize); } pBuf = m_ContinuousBuffer.GetData(); nBufSize = m_ContinuousBuffer.GetSize(); } else { // we can process the data directly pBuf = pData; nBufSize = nDataSize; } XnUInt32 nOutputSize = pWriteBuffer->GetFreeSpaceInBuffer(); XnUInt32 nWrittenOutput = nOutputSize; XnUInt32 nActualRead = 0; XnBool bLastPart = pHeader->nType == XN_SENSOR_PROTOCOL_RESPONSE_IMAGE_END && (nDataOffset + nDataSize) == pHeader->nBufSize; XnStatus nRetVal = XnStreamUncompressImageNew(pBuf, nBufSize, pWriteBuffer->GetUnsafeWritePointer(), &nWrittenOutput, (XnUInt16)GetActualXRes(), &nActualRead, bLastPart); if (nRetVal != XN_STATUS_OK) { xnLogWarning(XN_MASK_SENSOR_PROTOCOL_IMAGE, "Image decompression failed: %s (%d of %d, requested %d, last %d)", xnGetStatusString(nRetVal), nWrittenOutput, nBufSize, nOutputSize, bLastPart); FrameIsCorrupted(); return; } pWriteBuffer->UnsafeUpdateSize(nWrittenOutput); nBufSize -= nActualRead; m_ContinuousBuffer.Reset(); // if we have any bytes left, keep them for next time if (nBufSize > 0) { pBuf += nActualRead; m_ContinuousBuffer.UnsafeWrite(pBuf, nBufSize); } XN_PROFILING_END_SECTION } void XnBayerImageProcessor::OnStartOfFrame(const XnSensorProtocolResponseHeader* pHeader) { XnImageProcessor::OnStartOfFrame(pHeader); m_ContinuousBuffer.Reset(); } void XnBayerImageProcessor::OnEndOfFrame(const XnSensorProtocolResponseHeader* pHeader) { XN_PROFILING_START_SECTION("XnBayerImageProcessor::OnEndOfFrame") // if data was written to temp buffer, convert it now switch (GetStream()->GetOutputFormat()) { case ONI_PIXEL_FORMAT_GRAY8: break; case ONI_PIXEL_FORMAT_RGB888: { Bayer2RGB888(m_UncompressedBayerBuffer.GetData(), GetWriteBuffer()->GetUnsafeWritePointer(), GetActualXRes(), GetActualYRes(), 1); GetWriteBuffer()->UnsafeUpdateSize(GetActualXRes()*GetActualYRes()*3); m_UncompressedBayerBuffer.Reset(); } break; default: assert(0); return; } XnImageProcessor::OnEndOfFrame(pHeader); m_ContinuousBuffer.Reset(); XN_PROFILING_END_SECTION }
/***************************************************************************** * * * OpenNI 2.x Alpha * * Copyright (C) 2012 PrimeSense Ltd. * * * * This file is part of OpenNI. * * * * 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. * * * *****************************************************************************/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include "XnBayerImageProcessor.h" #include "Uncomp.h" #include "Bayer.h" #include <XnProfiling.h> //--------------------------------------------------------------------------- // Code //--------------------------------------------------------------------------- XnBayerImageProcessor::XnBayerImageProcessor(XnSensorImageStream* pStream, XnSensorStreamHelper* pHelper, XnFrameBufferManager* pBufferManager) : XnImageProcessor(pStream, pHelper, pBufferManager) { } XnBayerImageProcessor::~XnBayerImageProcessor() { } XnStatus XnBayerImageProcessor::Init() { XnStatus nRetVal = XN_STATUS_OK; nRetVal = XnImageProcessor::Init(); XN_IS_STATUS_OK(nRetVal); XN_VALIDATE_BUFFER_ALLOCATE(m_ContinuousBuffer, GetExpectedOutputSize()); switch (GetStream()->GetOutputFormat()) { case ONI_PIXEL_FORMAT_GRAY8: break; case ONI_PIXEL_FORMAT_RGB888: XN_VALIDATE_BUFFER_ALLOCATE(m_UncompressedBayerBuffer, GetExpectedOutputSize()); break; default: XN_LOG_WARNING_RETURN(XN_STATUS_ERROR, XN_MASK_SENSOR_PROTOCOL_IMAGE, "Unsupported image output format: %d", GetStream()->GetOutputFormat()); } return (XN_STATUS_OK); } void XnBayerImageProcessor::ProcessFramePacketChunk(const XnSensorProtocolResponseHeader* pHeader, const XnUChar* pData, XnUInt32 nDataOffset, XnUInt32 nDataSize) { XN_PROFILING_START_SECTION("XnBayerImageProcessor::ProcessFramePacketChunk") // if output format is Gray8, we can write directly to output buffer. otherwise, we need // to write to a temp buffer. XnBuffer* pWriteBuffer = (GetStream()->GetOutputFormat() == ONI_PIXEL_FORMAT_GRAY8) ? GetWriteBuffer() : &m_UncompressedBayerBuffer; const XnUChar* pBuf = NULL; XnUInt32 nBufSize = 0; // check if we have bytes stored from previous calls if (m_ContinuousBuffer.GetSize() > 0) { // we have no choice. We need to append current buffer to previous bytes if (m_ContinuousBuffer.GetFreeSpaceInBuffer() < nDataSize) { xnLogWarning(XN_MASK_SENSOR_PROTOCOL_DEPTH, "Bad overflow image! %d", m_ContinuousBuffer.GetSize()); FrameIsCorrupted(); } else { m_ContinuousBuffer.UnsafeWrite(pData, nDataSize); } pBuf = m_ContinuousBuffer.GetData(); nBufSize = m_ContinuousBuffer.GetSize(); } else { // we can process the data directly pBuf = pData; nBufSize = nDataSize; } XnUInt32 nOutputSize = pWriteBuffer->GetFreeSpaceInBuffer(); XnUInt32 nWrittenOutput = nOutputSize; XnUInt32 nActualRead = 0; XnBool bLastPart = pHeader->nType == XN_SENSOR_PROTOCOL_RESPONSE_IMAGE_END && (nDataOffset + nDataSize) == pHeader->nBufSize; XnStatus nRetVal = XnStreamUncompressImageNew(pBuf, nBufSize, pWriteBuffer->GetUnsafeWritePointer(), &nWrittenOutput, (XnUInt16)GetActualXRes(), &nActualRead, bLastPart); if (nRetVal != XN_STATUS_OK) { xnLogWarning(XN_MASK_SENSOR_PROTOCOL_IMAGE, "Image decompression failed: %s (%d of %d, requested %d, last %d)", xnGetStatusString(nRetVal), nWrittenOutput, nBufSize, nOutputSize, bLastPart); FrameIsCorrupted(); return; } pWriteBuffer->UnsafeUpdateSize(nWrittenOutput); nBufSize -= nActualRead; m_ContinuousBuffer.Reset(); // if we have any bytes left, keep them for next time if (nBufSize > 0) { pBuf += nActualRead; m_ContinuousBuffer.UnsafeWrite(pBuf, nBufSize); } XN_PROFILING_END_SECTION } void XnBayerImageProcessor::OnStartOfFrame(const XnSensorProtocolResponseHeader* pHeader) { XnImageProcessor::OnStartOfFrame(pHeader); m_ContinuousBuffer.Reset(); m_UncompressedBayerBuffer.Reset(); } void XnBayerImageProcessor::OnEndOfFrame(const XnSensorProtocolResponseHeader* pHeader) { XN_PROFILING_START_SECTION("XnBayerImageProcessor::OnEndOfFrame") // if data was written to temp buffer, convert it now switch (GetStream()->GetOutputFormat()) { case ONI_PIXEL_FORMAT_GRAY8: break; case ONI_PIXEL_FORMAT_RGB888: { Bayer2RGB888(m_UncompressedBayerBuffer.GetData(), GetWriteBuffer()->GetUnsafeWritePointer(), GetActualXRes(), GetActualYRes(), 1); GetWriteBuffer()->UnsafeUpdateSize(GetActualXRes()*GetActualYRes()*3); m_UncompressedBayerBuffer.Reset(); } break; default: assert(0); return; } XnImageProcessor::OnEndOfFrame(pHeader); m_ContinuousBuffer.Reset(); XN_PROFILING_END_SECTION }
Reduce number of corrupt frames on BAYER input
Reduce number of corrupt frames on BAYER input
C++
apache-2.0
mediastanza/OpenNI2,vaughamhong/OpenNI2,medengineer/OpenNI2,cmcmurrough/OpenNI2,klpanagi/OpenNI2,mediastanza/OpenNI2,aldebaran/openni2,mediastanza/OpenNI2,mediastanza/OpenNI2,danielelic/OpenNI2,vamsirajendra/OpenNI2,nh2/OpenNI2,tomburtonwood/OpenNI2,corlab/OpenNI2,orbbec/OpenNI2,MasWag/OpenNI2,danielelic/OpenNI2,vaughamhong/OpenNI2,vaughamhong/OpenNI2,vamsirajendra/OpenNI2,SethGibson/OpenNI2,corlab/OpenNI2,MasWag/OpenNI2,cmcmurrough/OpenNI2,tomburtonwood/OpenNI2,nh2/OpenNI2,penyatree/OpenNI2,jabjoe/debian-openni2,kipr/OpenNI2,kipr/OpenNI2,nh2/OpenNI2,tfoote/OpenNI2,Weijing/OpenNI2,orbbec/OpenNI2,danielelic/OpenNI2,penyatree/OpenNI2,medengineer/OpenNI2,Windowsfreak/OpenNI2,erdincay/OpenNI2,zodsoft/OpenNI2,klpanagi/OpenNI2,nh2/OpenNI2,vaughamhong/OpenNI2,jabjoe/debian-openni2,zodsoft/OpenNI2,occipital/OpenNI2,Weijing/OpenNI2,vamsirajendra/OpenNI2,YanyangChen/OpenNI2,tfoote/OpenNI2,SethGibson/OpenNI2,aldebaran/openni2,Weijing/OpenNI2,OpenNI/OpenNI2,OpenNI/OpenNI2,tfoote/OpenNI2,medengineer/OpenNI2,danielelic/OpenNI2,Windowsfreak/OpenNI2,occipital/OpenNI2,nh2/OpenNI2,SethGibson/OpenNI2,tomburtonwood/OpenNI2,penyatree/OpenNI2,aldebaran/openni2,YanyangChen/OpenNI2,OpenNI/OpenNI2,Windowsfreak/OpenNI2,penyatree/OpenNI2,tomburtonwood/OpenNI2,SethGibson/OpenNI2,aldebaran/openni2,occipital/OpenNI2,klpanagi/OpenNI2,occipital/OpenNI2,vaughamhong/OpenNI2,klpanagi/OpenNI2,danielelic/OpenNI2,Windowsfreak/OpenNI2,klpanagi/OpenNI2,aldebaran/openni2,orbbec/OpenNI2,corlab/OpenNI2,orbbec/OpenNI2,medengineer/OpenNI2,corlab/OpenNI2,Weijing/OpenNI2,cmcmurrough/OpenNI2,erdincay/OpenNI2,kipr/OpenNI2,tfoote/OpenNI2,occipital/OpenNI2,jabjoe/debian-openni2,YanyangChen/OpenNI2,MasWag/OpenNI2,erdincay/OpenNI2,kipr/OpenNI2,tfoote/OpenNI2,erdincay/OpenNI2,Windowsfreak/OpenNI2,SethGibson/OpenNI2,vamsirajendra/OpenNI2,jabjoe/debian-openni2,kipr/OpenNI2,YanyangChen/OpenNI2,MasWag/OpenNI2,zodsoft/OpenNI2,MasWag/OpenNI2,vamsirajendra/OpenNI2,OpenNI/OpenNI2,mediastanza/OpenNI2,erdincay/OpenNI2,orbbec/OpenNI2,jabjoe/debian-openni2,tomburtonwood/OpenNI2,zodsoft/OpenNI2,penyatree/OpenNI2,cmcmurrough/OpenNI2,Weijing/OpenNI2,YanyangChen/OpenNI2,OpenNI/OpenNI2,corlab/OpenNI2,cmcmurrough/OpenNI2,medengineer/OpenNI2,zodsoft/OpenNI2
20051781444a46a29244bf179313010e3297c397
test/t_widget_resolver.cxx
test/t_widget_resolver.cxx
#include "widget_resolver.hxx" #include "widget_registry.hxx" #include "async.hxx" #include "widget.hxx" #include "widget_class.hxx" #include "pool.hxx" #include "RootPool.hxx" #include "event/Loop.hxx" #include "util/Cast.hxx" #include <assert.h> struct Context { struct { struct async_operation_ref async_ref; bool finished; /** abort in the callback? */ bool abort; } first, second; struct { bool requested, finished, aborted; struct async_operation operation; WidgetRegistryCallback callback; } registry; }; static Context *global; const WidgetView * widget_view_lookup(const WidgetView *view, gcc_unused const char *name) { return view; } static void data_init(Context *data) { data->first.finished = false; data->first.abort = false; data->second.finished = false; data->second.abort = false; data->registry.requested = false; data->registry.finished = false; data->registry.aborted = false; data->registry.callback = nullptr; global = data; } static void widget_resolver_callback1(void *ctx) { Context *data = (Context *)ctx; assert(!data->first.finished); assert(!data->second.finished); data->first.finished = true; if (data->first.abort) data->second.async_ref.Abort(); } static void widget_resolver_callback2(void *ctx) { Context *data = (Context *)ctx; assert(data->first.finished); assert(!data->second.finished); assert(!data->second.abort); data->second.finished = true; } /* * async operation * */ static Context * async_to_data(struct async_operation *ao) { return ContainerCast(ao, Context, registry.operation); } static void widget_registry_abort(struct async_operation *ao __attr_unused) { Context *data = async_to_data(ao); data->registry.aborted = true; } static const struct async_operation_class widget_registry_operation = { .abort = widget_registry_abort, }; /* * widget-registry.c emulation * */ void widget_class_lookup(gcc_unused struct pool &pool, gcc_unused struct pool &widget_pool, gcc_unused struct tcache &translate_cache, gcc_unused const char *widget_type, WidgetRegistryCallback callback, struct async_operation_ref &async_ref) { Context *data = global; assert(!data->registry.requested); assert(!data->registry.finished); assert(!data->registry.aborted); assert(!data->registry.callback); data->registry.requested = true; data->registry.callback = callback; data->registry.operation.Init(widget_registry_operation); async_ref.Set(data->registry.operation); } static void widget_registry_finish(Context *data) { assert(data->registry.requested); assert(!data->registry.finished); assert(!data->registry.aborted); assert(data->registry.callback); data->registry.finished = true; static const WidgetClass cls = WidgetClass(WidgetClass::Root()); data->registry.callback(&cls); } /* * tests * */ static void test_normal(struct pool *pool) { Context data; data_init(&data); pool = pool_new_linear(pool, "test", 8192); auto widget = NewFromPool<Widget>(*pool); widget->Init(*pool, nullptr); widget->class_name = "foo"; ResolveWidget(*pool, *widget, *(struct tcache *)(size_t)0x1, widget_resolver_callback1, &data, data.first.async_ref); assert(!data.first.finished); assert(!data.second.finished); assert(data.registry.requested); assert(!data.registry.finished); assert(!data.registry.aborted); widget_registry_finish(&data); assert(data.first.finished); assert(!data.second.finished); assert(data.registry.requested); assert(data.registry.finished); assert(!data.registry.aborted); pool_unref(pool); pool_commit(); } static void test_abort(struct pool *pool) { Context data; data_init(&data); pool = pool_new_linear(pool, "test", 8192); auto widget = NewFromPool<Widget>(*pool); widget->Init(*pool, nullptr); widget->class_name = "foo"; ResolveWidget(*pool, *widget, *(struct tcache *)(size_t)0x1, widget_resolver_callback1, &data, data.first.async_ref); assert(!data.first.finished); assert(!data.second.finished); assert(data.registry.requested); assert(!data.registry.finished); assert(!data.registry.aborted); data.first.async_ref.Abort(); assert(!data.first.finished); assert(!data.second.finished); assert(data.registry.requested); assert(!data.registry.finished); assert(data.registry.aborted); pool_unref(pool); pool_commit(); } static void test_two_clients(struct pool *pool) { Context data; data_init(&data); pool = pool_new_linear(pool, "test", 8192); auto widget = NewFromPool<Widget>(*pool); widget->Init(*pool, nullptr); widget->class_name = "foo"; ResolveWidget(*pool, *widget, *(struct tcache *)(size_t)0x1, widget_resolver_callback1, &data, data.first.async_ref); ResolveWidget(*pool, *widget, *(struct tcache *)(size_t)0x1, widget_resolver_callback2, &data, data.second.async_ref); assert(!data.first.finished); assert(!data.second.finished); assert(data.registry.requested); assert(!data.registry.finished); assert(!data.registry.aborted); widget_registry_finish(&data); assert(data.first.finished); assert(data.second.finished); assert(data.registry.requested); assert(data.registry.finished); assert(!data.registry.aborted); pool_unref(pool); pool_commit(); } static void test_two_abort(struct pool *pool) { Context data; data_init(&data); data.first.abort = true; pool = pool_new_linear(pool, "test", 8192); auto widget = NewFromPool<Widget>(*pool); widget->Init(*pool, nullptr); widget->class_name = "foo"; ResolveWidget(*pool, *widget, *(struct tcache *)(size_t)0x1, widget_resolver_callback1, &data, data.first.async_ref); ResolveWidget(*pool, *widget, *(struct tcache *)(size_t)0x1, widget_resolver_callback2, &data, data.second.async_ref); assert(!data.first.finished); assert(!data.second.finished); assert(data.registry.requested); assert(!data.registry.finished); assert(!data.registry.aborted); widget_registry_finish(&data); assert(data.first.finished); assert(!data.second.finished); assert(data.registry.requested); assert(data.registry.finished); assert(!data.registry.aborted); pool_unref(pool); pool_commit(); } /* * main * */ int main(int argc __attr_unused, char **argv __attr_unused) { EventLoop event_loop; /* run test suite */ test_normal(RootPool()); test_abort(RootPool()); test_two_clients(RootPool()); test_two_abort(RootPool()); }
#include "widget_resolver.hxx" #include "widget_registry.hxx" #include "async.hxx" #include "widget.hxx" #include "widget_class.hxx" #include "pool.hxx" #include "RootPool.hxx" #include "event/Loop.hxx" #include "util/Cast.hxx" #include <assert.h> static struct Context *global; struct Context { struct { struct async_operation_ref async_ref; bool finished = false; /** abort in the callback? */ bool abort = false; } first, second; struct { bool requested = false, finished = false, aborted = false; struct async_operation operation; WidgetRegistryCallback callback = nullptr; } registry; Context() { global = this; } }; const WidgetView * widget_view_lookup(const WidgetView *view, gcc_unused const char *name) { return view; } static void widget_resolver_callback1(void *ctx) { Context *data = (Context *)ctx; assert(!data->first.finished); assert(!data->second.finished); data->first.finished = true; if (data->first.abort) data->second.async_ref.Abort(); } static void widget_resolver_callback2(void *ctx) { Context *data = (Context *)ctx; assert(data->first.finished); assert(!data->second.finished); assert(!data->second.abort); data->second.finished = true; } /* * async operation * */ static Context * async_to_data(struct async_operation *ao) { return ContainerCast(ao, Context, registry.operation); } static void widget_registry_abort(struct async_operation *ao __attr_unused) { Context *data = async_to_data(ao); data->registry.aborted = true; } static const struct async_operation_class widget_registry_operation = { .abort = widget_registry_abort, }; /* * widget-registry.c emulation * */ void widget_class_lookup(gcc_unused struct pool &pool, gcc_unused struct pool &widget_pool, gcc_unused struct tcache &translate_cache, gcc_unused const char *widget_type, WidgetRegistryCallback callback, struct async_operation_ref &async_ref) { Context *data = global; assert(!data->registry.requested); assert(!data->registry.finished); assert(!data->registry.aborted); assert(!data->registry.callback); data->registry.requested = true; data->registry.callback = callback; data->registry.operation.Init(widget_registry_operation); async_ref.Set(data->registry.operation); } static void widget_registry_finish(Context *data) { assert(data->registry.requested); assert(!data->registry.finished); assert(!data->registry.aborted); assert(data->registry.callback); data->registry.finished = true; static const WidgetClass cls = WidgetClass(WidgetClass::Root()); data->registry.callback(&cls); } /* * tests * */ static void test_normal(struct pool *pool) { Context data; pool = pool_new_linear(pool, "test", 8192); auto widget = NewFromPool<Widget>(*pool); widget->Init(*pool, nullptr); widget->class_name = "foo"; ResolveWidget(*pool, *widget, *(struct tcache *)(size_t)0x1, widget_resolver_callback1, &data, data.first.async_ref); assert(!data.first.finished); assert(!data.second.finished); assert(data.registry.requested); assert(!data.registry.finished); assert(!data.registry.aborted); widget_registry_finish(&data); assert(data.first.finished); assert(!data.second.finished); assert(data.registry.requested); assert(data.registry.finished); assert(!data.registry.aborted); pool_unref(pool); pool_commit(); } static void test_abort(struct pool *pool) { Context data; pool = pool_new_linear(pool, "test", 8192); auto widget = NewFromPool<Widget>(*pool); widget->Init(*pool, nullptr); widget->class_name = "foo"; ResolveWidget(*pool, *widget, *(struct tcache *)(size_t)0x1, widget_resolver_callback1, &data, data.first.async_ref); assert(!data.first.finished); assert(!data.second.finished); assert(data.registry.requested); assert(!data.registry.finished); assert(!data.registry.aborted); data.first.async_ref.Abort(); assert(!data.first.finished); assert(!data.second.finished); assert(data.registry.requested); assert(!data.registry.finished); assert(data.registry.aborted); pool_unref(pool); pool_commit(); } static void test_two_clients(struct pool *pool) { Context data; pool = pool_new_linear(pool, "test", 8192); auto widget = NewFromPool<Widget>(*pool); widget->Init(*pool, nullptr); widget->class_name = "foo"; ResolveWidget(*pool, *widget, *(struct tcache *)(size_t)0x1, widget_resolver_callback1, &data, data.first.async_ref); ResolveWidget(*pool, *widget, *(struct tcache *)(size_t)0x1, widget_resolver_callback2, &data, data.second.async_ref); assert(!data.first.finished); assert(!data.second.finished); assert(data.registry.requested); assert(!data.registry.finished); assert(!data.registry.aborted); widget_registry_finish(&data); assert(data.first.finished); assert(data.second.finished); assert(data.registry.requested); assert(data.registry.finished); assert(!data.registry.aborted); pool_unref(pool); pool_commit(); } static void test_two_abort(struct pool *pool) { Context data; data.first.abort = true; pool = pool_new_linear(pool, "test", 8192); auto widget = NewFromPool<Widget>(*pool); widget->Init(*pool, nullptr); widget->class_name = "foo"; ResolveWidget(*pool, *widget, *(struct tcache *)(size_t)0x1, widget_resolver_callback1, &data, data.first.async_ref); ResolveWidget(*pool, *widget, *(struct tcache *)(size_t)0x1, widget_resolver_callback2, &data, data.second.async_ref); assert(!data.first.finished); assert(!data.second.finished); assert(data.registry.requested); assert(!data.registry.finished); assert(!data.registry.aborted); widget_registry_finish(&data); assert(data.first.finished); assert(!data.second.finished); assert(data.registry.requested); assert(data.registry.finished); assert(!data.registry.aborted); pool_unref(pool); pool_commit(); } /* * main * */ int main(int argc __attr_unused, char **argv __attr_unused) { EventLoop event_loop; /* run test suite */ test_normal(RootPool()); test_abort(RootPool()); test_two_clients(RootPool()); test_two_abort(RootPool()); }
add constructor
test/t_widget_resolver: add constructor
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
b28076cc364cfd37cae3a1690e11baf70a28c6be
modules/prediction/prediction.cc
modules/prediction/prediction.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/prediction.h" #include <algorithm> #include <cmath> #include <vector> #include "boost/filesystem.hpp" #include "boost/range/iterator_range.hpp" #include "rosbag/bag.h" #include "rosbag/view.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/math/vec2d.h" #include "modules/common/time/time.h" #include "modules/common/util/file.h" #include "modules/prediction/common/feature_output.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_map.h" #include "modules/prediction/common/validation_checker.h" #include "modules/prediction/container/container_manager.h" #include "modules/prediction/container/obstacles/obstacles_container.h" #include "modules/prediction/container/pose/pose_container.h" #include "modules/prediction/evaluator/evaluator_manager.h" #include "modules/prediction/predictor/predictor_manager.h" #include "modules/prediction/proto/prediction_obstacle.pb.h" namespace apollo { namespace prediction { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::adapter::AdapterConfig; using apollo::common::adapter::AdapterManager; using apollo::common::math::Vec2d; using apollo::common::time::Clock; using apollo::common::util::DirectoryExists; using apollo::common::util::Glob; using apollo::localization::LocalizationEstimate; using apollo::perception::PerceptionObstacle; using apollo::perception::PerceptionObstacles; std::string Prediction::Name() const { return FLAGS_prediction_module_name; } void GetBagFiles(const boost::filesystem::path& p, std::vector<std::string>* bag_files) { CHECK(bag_files); if (!boost::filesystem::exists(p)) { return; } if (boost::filesystem::is_regular_file(p)) { const auto ext = p.extension(); if (ext == ".bag" || ext == ".BAG") { AINFO << "Found bag file: " << p.c_str(); bag_files->push_back(p.c_str()); } return; } if (boost::filesystem::is_directory(p)) { for (auto& entry : boost::make_iterator_range( boost::filesystem::directory_iterator(p), {})) { GetBagFiles(entry.path(), bag_files); } } } void Prediction::ProcessRosbag(const std::string& filename) { const std::vector<std::string> topics{FLAGS_perception_obstacle_topic, FLAGS_localization_topic}; rosbag::Bag bag; try { bag.open(filename, rosbag::bagmode::Read); } catch (const rosbag::BagIOException& e) { AERROR << "BagIOException when open bag: " << filename << " Exception: " << e.what(); bag.close(); return; } catch (...) { AERROR << "Failed to open bag: " << filename; bag.close(); return; } rosbag::View view(bag, rosbag::TopicQuery(topics)); for (auto it = view.begin(); it != view.end(); ++it) { if (it->getTopic() == FLAGS_localization_topic) { OnLocalization(*(it->instantiate<LocalizationEstimate>())); } else if (it->getTopic() == FLAGS_perception_obstacle_topic) { RunOnce(*(it->instantiate<PerceptionObstacles>())); } } bag.close(); } Status Prediction::Init() { start_time_ = Clock::NowInSeconds(); // Load prediction conf prediction_conf_.Clear(); if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file, &prediction_conf_)) { return OnError("Unable to load prediction conf file: " + FLAGS_prediction_conf_file); } else { ADEBUG << "Prediction config file is loaded into: " << prediction_conf_.ShortDebugString(); } adapter_conf_.Clear(); if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename, &adapter_conf_)) { return OnError("Unable to load adapter conf file: " + FLAGS_prediction_adapter_config_filename); } else { ADEBUG << "Adapter config file is loaded into: " << adapter_conf_.ShortDebugString(); } // Initialization of all managers AdapterManager::Init(adapter_conf_); ContainerManager::Instance()->Init(adapter_conf_); EvaluatorManager::Instance()->Init(prediction_conf_); PredictorManager::Instance()->Init(prediction_conf_); CHECK(AdapterManager::GetLocalization()) << "Localization is not registered."; CHECK(AdapterManager::GetPerceptionObstacles()) << "Perception is not registered."; // Set localization callback function AdapterManager::AddLocalizationCallback(&Prediction::OnLocalization, this); // Set planning callback function AdapterManager::AddPlanningCallback(&Prediction::OnPlanning, this); // Set perception obstacle callback function AdapterManager::AddPerceptionObstaclesCallback(&Prediction::RunOnce, this); if (!FLAGS_use_navigation_mode && !PredictionMap::Ready()) { return OnError("Map cannot be loaded."); } if (FLAGS_prediction_offline_mode) { if (!FeatureOutput::Ready()) { return OnError("Feature output is not ready."); } if (FLAGS_prediction_offline_bags.empty()) { return Status::OK(); // use listen to ROS topic mode } std::vector<std::string> inputs; apollo::common::util::split(FLAGS_prediction_offline_bags, ':', &inputs); for (const auto& input : inputs) { std::vector<std::string> offline_bags; GetBagFiles(boost::filesystem::path(input), &offline_bags); std::sort(offline_bags.begin(), offline_bags.end()); AINFO << "For input " << input << ", found " << offline_bags.size() << " rosbags to process"; for (std::size_t i = 0; i < offline_bags.size(); ++i) { AINFO << "\tProcessing: [ " << i << " / " << offline_bags.size() << " ]: " << offline_bags[i]; ProcessRosbag(offline_bags[i]); } } Stop(); ros::shutdown(); } return Status::OK(); } Status Prediction::Start() { return Status::OK(); } void Prediction::Stop() { if (FLAGS_prediction_offline_mode) { FeatureOutput::Close(); } } void Prediction::OnLocalization(const LocalizationEstimate& localization) { PoseContainer* pose_container = dynamic_cast<PoseContainer*>( ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION)); CHECK_NOTNULL(pose_container); pose_container->Insert(localization); ADEBUG << "Received a localization message [" << localization.ShortDebugString() << "]."; } void Prediction::OnPlanning(const planning::ADCTrajectory& adc_trajectory) { ADCTrajectoryContainer* adc_trajectory_container = dynamic_cast<ADCTrajectoryContainer*>( ContainerManager::Instance()->GetContainer( AdapterConfig::PLANNING_TRAJECTORY)); CHECK_NOTNULL(adc_trajectory_container); adc_trajectory_container->Insert(adc_trajectory); ADEBUG << "Received a planning message [" << adc_trajectory.ShortDebugString() << "]."; } void Prediction::RunOnce(const PerceptionObstacles& perception_obstacles) { if (FLAGS_prediction_test_mode && FLAGS_prediction_test_duration > 0.0 && (Clock::NowInSeconds() - start_time_ > FLAGS_prediction_test_duration)) { AINFO << "Prediction finished running in test mode"; ros::shutdown(); } // Update relative map if needed AdapterManager::Observe(); if (FLAGS_use_navigation_mode && !PredictionMap::Ready()) { AERROR << "Relative map is empty."; return; } double start_timestamp = Clock::NowInSeconds(); // Insert obstacle ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>( ContainerManager::Instance()->GetContainer( AdapterConfig::PERCEPTION_OBSTACLES)); CHECK_NOTNULL(obstacles_container); obstacles_container->Insert(perception_obstacles); ADEBUG << "Received a perception message [" << perception_obstacles.ShortDebugString() << "]."; // Update ADC status PoseContainer* pose_container = dynamic_cast<PoseContainer*>( ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION)); ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>( ContainerManager::Instance()->GetContainer( AdapterConfig::PLANNING_TRAJECTORY)); CHECK_NOTNULL(pose_container); CHECK_NOTNULL(adc_container); PerceptionObstacle* adc = pose_container->ToPerceptionObstacle(); if (adc != nullptr) { obstacles_container->InsertPerceptionObstacle(*adc, adc->timestamp()); double x = adc->position().x(); double y = adc->position().y(); ADEBUG << "Get ADC position [" << std::fixed << std::setprecision(6) << x << ", " << std::fixed << std::setprecision(6) << y << "]."; Vec2d adc_position(x, y); adc_container->SetPosition(adc_position); } // Make evaluations EvaluatorManager::Instance()->Run(perception_obstacles); // No prediction for offline mode if (FLAGS_prediction_offline_mode) { return; } // Make predictions PredictorManager::Instance()->Run(perception_obstacles); auto prediction_obstacles = PredictorManager::Instance()->prediction_obstacles(); prediction_obstacles.set_start_timestamp(start_timestamp); prediction_obstacles.set_end_timestamp(Clock::NowInSeconds()); prediction_obstacles.mutable_header()->set_lidar_timestamp( perception_obstacles.header().lidar_timestamp()); prediction_obstacles.mutable_header()->set_camera_timestamp( perception_obstacles.header().camera_timestamp()); prediction_obstacles.mutable_header()->set_radar_timestamp( perception_obstacles.header().radar_timestamp()); if (FLAGS_prediction_test_mode) { for (auto const& prediction_obstacle : prediction_obstacles.prediction_obstacle()) { for (auto const& trajectory : prediction_obstacle.trajectory()) { for (auto const& trajectory_point : trajectory.trajectory_point()) { if (!ValidationChecker::ValidTrajectoryPoint(trajectory_point)) { AERROR << "Invalid trajectory point [" << trajectory_point.ShortDebugString() << "]"; return; } } } } } Publish(&prediction_obstacles); } Status Prediction::OnError(const std::string& error_msg) { return Status(ErrorCode::PREDICTION_ERROR, error_msg); } } // namespace prediction } // namespace apollo
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/prediction.h" #include <algorithm> #include <cmath> #include <vector> #include "boost/filesystem.hpp" #include "boost/range/iterator_range.hpp" #include "rosbag/bag.h" #include "rosbag/view.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/math/vec2d.h" #include "modules/common/time/time.h" #include "modules/common/util/file.h" #include "modules/prediction/common/feature_output.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_map.h" #include "modules/prediction/common/validation_checker.h" #include "modules/prediction/container/container_manager.h" #include "modules/prediction/container/obstacles/obstacles_container.h" #include "modules/prediction/container/pose/pose_container.h" #include "modules/prediction/evaluator/evaluator_manager.h" #include "modules/prediction/predictor/predictor_manager.h" #include "modules/prediction/proto/prediction_obstacle.pb.h" namespace apollo { namespace prediction { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::adapter::AdapterConfig; using apollo::common::adapter::AdapterManager; using apollo::common::math::Vec2d; using apollo::common::time::Clock; using apollo::common::util::DirectoryExists; using apollo::common::util::Glob; using apollo::localization::LocalizationEstimate; using apollo::perception::PerceptionObstacle; using apollo::perception::PerceptionObstacles; std::string Prediction::Name() const { return FLAGS_prediction_module_name; } void GetBagFiles(const boost::filesystem::path& p, std::vector<std::string>* bag_files) { CHECK(bag_files); if (!boost::filesystem::exists(p)) { return; } if (boost::filesystem::is_regular_file(p)) { const auto ext = p.extension(); if (ext == ".bag" || ext == ".BAG") { AINFO << "Found bag file: " << p.c_str(); bag_files->push_back(p.c_str()); } return; } if (boost::filesystem::is_directory(p)) { for (auto& entry : boost::make_iterator_range( boost::filesystem::directory_iterator(p), {})) { GetBagFiles(entry.path(), bag_files); } } } void Prediction::ProcessRosbag(const std::string& filename) { const std::vector<std::string> topics{FLAGS_perception_obstacle_topic, FLAGS_localization_topic}; rosbag::Bag bag; try { bag.open(filename, rosbag::bagmode::Read); } catch (const rosbag::BagIOException& e) { AERROR << "BagIOException when open bag: " << filename << " Exception: " << e.what(); bag.close(); return; } catch (...) { AERROR << "Failed to open bag: " << filename; bag.close(); return; } rosbag::View view(bag, rosbag::TopicQuery(topics)); for (auto it = view.begin(); it != view.end(); ++it) { if (it->getTopic() == FLAGS_localization_topic) { OnLocalization(*(it->instantiate<LocalizationEstimate>())); } else if (it->getTopic() == FLAGS_perception_obstacle_topic) { RunOnce(*(it->instantiate<PerceptionObstacles>())); } } bag.close(); } Status Prediction::Init() { start_time_ = Clock::NowInSeconds(); // Load prediction conf prediction_conf_.Clear(); if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file, &prediction_conf_)) { return OnError("Unable to load prediction conf file: " + FLAGS_prediction_conf_file); } else { ADEBUG << "Prediction config file is loaded into: " << prediction_conf_.ShortDebugString(); } adapter_conf_.Clear(); if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename, &adapter_conf_)) { return OnError("Unable to load adapter conf file: " + FLAGS_prediction_adapter_config_filename); } else { ADEBUG << "Adapter config file is loaded into: " << adapter_conf_.ShortDebugString(); } // Initialization of all managers AdapterManager::Init(adapter_conf_); ContainerManager::Instance()->Init(adapter_conf_); EvaluatorManager::Instance()->Init(prediction_conf_); PredictorManager::Instance()->Init(prediction_conf_); CHECK(AdapterManager::GetLocalization()) << "Localization is not registered."; CHECK(AdapterManager::GetPerceptionObstacles()) << "Perception is not registered."; /* TODO(kechxu) recover callbacks according to cybertron // Set localization callback function AdapterManager::AddLocalizationCallback(&Prediction::OnLocalization, this); // Set planning callback function AdapterManager::AddPlanningCallback(&Prediction::OnPlanning, this); // Set perception obstacle callback function AdapterManager::AddPerceptionObstaclesCallback(&Prediction::RunOnce, this); */ if (!FLAGS_use_navigation_mode && !PredictionMap::Ready()) { return OnError("Map cannot be loaded."); } if (FLAGS_prediction_offline_mode) { if (!FeatureOutput::Ready()) { return OnError("Feature output is not ready."); } if (FLAGS_prediction_offline_bags.empty()) { return Status::OK(); // use listen to ROS topic mode } std::vector<std::string> inputs; apollo::common::util::split(FLAGS_prediction_offline_bags, ':', &inputs); for (const auto& input : inputs) { std::vector<std::string> offline_bags; GetBagFiles(boost::filesystem::path(input), &offline_bags); std::sort(offline_bags.begin(), offline_bags.end()); AINFO << "For input " << input << ", found " << offline_bags.size() << " rosbags to process"; for (std::size_t i = 0; i < offline_bags.size(); ++i) { AINFO << "\tProcessing: [ " << i << " / " << offline_bags.size() << " ]: " << offline_bags[i]; ProcessRosbag(offline_bags[i]); } } Stop(); // TODO(kechxu) accord to cybertron // ros::shutdown(); } return Status::OK(); } Status Prediction::Start() { return Status::OK(); } void Prediction::Stop() { if (FLAGS_prediction_offline_mode) { FeatureOutput::Close(); } } void Prediction::OnLocalization(const LocalizationEstimate& localization) { PoseContainer* pose_container = dynamic_cast<PoseContainer*>( ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION)); CHECK_NOTNULL(pose_container); pose_container->Insert(localization); ADEBUG << "Received a localization message [" << localization.ShortDebugString() << "]."; } void Prediction::OnPlanning(const planning::ADCTrajectory& adc_trajectory) { ADCTrajectoryContainer* adc_trajectory_container = dynamic_cast<ADCTrajectoryContainer*>( ContainerManager::Instance()->GetContainer( AdapterConfig::PLANNING_TRAJECTORY)); CHECK_NOTNULL(adc_trajectory_container); adc_trajectory_container->Insert(adc_trajectory); ADEBUG << "Received a planning message [" << adc_trajectory.ShortDebugString() << "]."; } void Prediction::RunOnce(const PerceptionObstacles& perception_obstacles) { if (FLAGS_prediction_test_mode && FLAGS_prediction_test_duration > 0.0 && (Clock::NowInSeconds() - start_time_ > FLAGS_prediction_test_duration)) { AINFO << "Prediction finished running in test mode"; // TODO(kechxu) accord to cybertron // ros::shutdown(); } // Update relative map if needed AdapterManager::Observe(); if (FLAGS_use_navigation_mode && !PredictionMap::Ready()) { AERROR << "Relative map is empty."; return; } double start_timestamp = Clock::NowInSeconds(); // Insert obstacle ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>( ContainerManager::Instance()->GetContainer( AdapterConfig::PERCEPTION_OBSTACLES)); CHECK_NOTNULL(obstacles_container); obstacles_container->Insert(perception_obstacles); ADEBUG << "Received a perception message [" << perception_obstacles.ShortDebugString() << "]."; // Update ADC status PoseContainer* pose_container = dynamic_cast<PoseContainer*>( ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION)); ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>( ContainerManager::Instance()->GetContainer( AdapterConfig::PLANNING_TRAJECTORY)); CHECK_NOTNULL(pose_container); CHECK_NOTNULL(adc_container); PerceptionObstacle* adc = pose_container->ToPerceptionObstacle(); if (adc != nullptr) { obstacles_container->InsertPerceptionObstacle(*adc, adc->timestamp()); double x = adc->position().x(); double y = adc->position().y(); ADEBUG << "Get ADC position [" << std::fixed << std::setprecision(6) << x << ", " << std::fixed << std::setprecision(6) << y << "]."; Vec2d adc_position(x, y); adc_container->SetPosition(adc_position); } // Make evaluations EvaluatorManager::Instance()->Run(perception_obstacles); // No prediction for offline mode if (FLAGS_prediction_offline_mode) { return; } // Make predictions PredictorManager::Instance()->Run(perception_obstacles); auto prediction_obstacles = PredictorManager::Instance()->prediction_obstacles(); prediction_obstacles.set_start_timestamp(start_timestamp); prediction_obstacles.set_end_timestamp(Clock::NowInSeconds()); prediction_obstacles.mutable_header()->set_lidar_timestamp( perception_obstacles.header().lidar_timestamp()); prediction_obstacles.mutable_header()->set_camera_timestamp( perception_obstacles.header().camera_timestamp()); prediction_obstacles.mutable_header()->set_radar_timestamp( perception_obstacles.header().radar_timestamp()); if (FLAGS_prediction_test_mode) { for (auto const& prediction_obstacle : prediction_obstacles.prediction_obstacle()) { for (auto const& trajectory : prediction_obstacle.trajectory()) { for (auto const& trajectory_point : trajectory.trajectory_point()) { if (!ValidationChecker::ValidTrajectoryPoint(trajectory_point)) { AERROR << "Invalid trajectory point [" << trajectory_point.ShortDebugString() << "]"; return; } } } } } Publish(&prediction_obstacles); } Status Prediction::OnError(const std::string& error_msg) { return Status(ErrorCode::PREDICTION_ERROR, error_msg); } } // namespace prediction } // namespace apollo
make prediction module compile by disabling some interface functions temporarily
Prediction: make prediction module compile by disabling some interface functions temporarily
C++
apache-2.0
xiaoxq/apollo,ycool/apollo,jinghaomiao/apollo,jinghaomiao/apollo,xiaoxq/apollo,ycool/apollo,ApolloAuto/apollo,ycool/apollo,wanglei828/apollo,xiaoxq/apollo,wanglei828/apollo,ycool/apollo,jinghaomiao/apollo,ApolloAuto/apollo,ApolloAuto/apollo,ycool/apollo,jinghaomiao/apollo,jinghaomiao/apollo,jinghaomiao/apollo,wanglei828/apollo,xiaoxq/apollo,wanglei828/apollo,ApolloAuto/apollo,wanglei828/apollo,xiaoxq/apollo,xiaoxq/apollo,ApolloAuto/apollo,ycool/apollo,wanglei828/apollo,ApolloAuto/apollo
e300f7a4096ab9f73ccda8b52ac22068cd3855d8
testPlugins/s_Dustbust.cpp
testPlugins/s_Dustbust.cpp
static const char* const CLASS = "s_Dustbust"; static const char* const HELP = "s_Dustbust tries to remove dust in an" "intelligent way, using simple math and" "motionvectors."; // Standard plug-in include files. #include "DDImage/Iop.h" #include "DDImage/Row.h" #include "DDImage/Tile.h" #include "DDImage/Knobs.h" #include "DDImage/MultiTile.h" #include "DDImage/Pixel.h" #include "DDImage/Vector2.h" #include "DDImage/Thread.h" #include "DDImage/NukeWrapper.h" using namespace DD::Image; #include <algorithm> #include <vector> using namespace std; class s_Dustbust : public Iop { private: Channel uv[4]; ChannelSet prevFrame, nextFrame; Channel _prevFrame[3]; Channel _nextFrame[3]; bool _firstTime; Lock _lock; int _size; public: //! Constructor. Initialize user controls to their default values. s_Dustbust (Node* node) : Iop (node) { uv[0] = uv[1] = uv[2] = uv[3] = Chan_Black; prevFrame = nextFrame = Mask_None; _prevFrame[0] = getChannel("_prevFrame.r"); _prevFrame[1] = getChannel("_prevFrame.g"); _prevFrame[2] = getChannel("_prevFrame.b"); _nextFrame[0] = getChannel("_nextFrame.r"); _nextFrame[1] = getChannel("_nextFrame.g"); _nextFrame[2] = getChannel("_nextFrame.b"); _firstTime = true; _size = 2; } ~s_Dustbust () {} int maximum_inputs() const { return 1; } int minimum_inputs() const { return 1; } int split_input(int n) const { return 3; } const OutputContext& inputContext(int, int, OutputContext&) const; void _validate(bool) { copy_info(); prevFrame.insert(_prevFrame, 3); nextFrame.insert(_nextFrame, 3); } void in_channels(int, ChannelSet& mask) const { for(int i = 0; i < 4; i++) mask += (uv[i]); for(int i = 0; i < 3; i++) { mask += _prevFrame[i]; mask += _nextFrame[i]; } } void _request(int x, int y, int r, int t, ChannelMask channels, int count) { ChannelSet c(channels); in_channels(0, c); int X = input0().info().x(); int Y = input0().info().y(); int R = input0().info().r(); int T = input0().info().t(); for(int i = 0; i <= 2; i++) input(i)->request( X, Y, R, T, c, count*2 ); } mFnDDImageMultiTileGenerateEngineInline(input0()) template<class TileType> void doEngine(int, int, int, ChannelMask, Row&); virtual void knobs(Knob_Callback); //! Return the name of the class. const char* Class() const { return CLASS; } const char* node_help() const { return HELP; } private: //! Information to the plug-in manager of DDNewImage/NUKE. static const Iop::Description d; }; const OutputContext& s_Dustbust::inputContext(int i, int n, OutputContext& context) const { context = outputContext(); switch(n) { case 0: break; case 1: context.setFrame(context.frame() - 1); break; case 2: context.setFrame(context.frame() + 1); break; } return context; } static Iop* build(Node* node) { return (new NukeWrapper( new s_Dustbust(node)))->noMix()->noMask(); } const Iop::Description s_Dustbust::d ( CLASS, "Filter/s_Dustbust", build ); template<class TileType> void s_Dustbust::doEngine(int y, int x, int r, ChannelMask channels, Row& out) { int X = x; ChannelSet c(channels); in_channels(0, c); TileType tile(*input(0), x - 1, y - 1, r + 1, y + 2, c); // *input(0) = input0() { Guard guard(_lock); if (_firstTime) { if (aborted()) return; // forward motionvectors Channel fw_uu = uv[0]; Channel fw_vv = uv[1]; if(!intersect(tile.channels(), fw_uu)) fw_uu = Chan_Black; if(!intersect(tile.channels(), fw_vv)) fw_vv = Chan_Black; // backward motionvectors Channel bw_uu = uv[2]; Channel bw_vv = uv[3]; if(!intersect(tile.channels(), bw_uu)) bw_uu = Chan_Black; if(!intersect(tile.channels(), bw_vv)) bw_vv = Chan_Black; //foreach(z, channels) out.writable(z); InterestRatchet interestRatchet; Pixel fw_pixel(channels), bw_pixel(channels); fw_pixel.setInterestRatchet(&interestRatchet); bw_pixel.setInterestRatchet(&interestRatchet); for (; x < r; x++) { if (aborted()) break; int xx = x + 1; if (xx >= info_.r()) xx = info_.r() - 1; Vector2 bw_center(tile[bw_uu][y][x] + x + 0.5f, tile[bw_vv][y][x] + y + 0.5f); Vector2 bw_du(tile[bw_uu][y][xx] - tile[bw_uu][y][x] + 1, tile[bw_vv][y][xx] - tile[bw_vv][y][x]); Vector2 bw_dv(tile[bw_uu][tile.clampy(y + 1)][x] - tile[bw_uu][y][x], tile[bw_vv][tile.clampy(y + 1)][x] - tile[bw_vv][y][x] + 1); input(1)->sample(bw_center, bw_du, bw_dv, bw_pixel); Vector2 fw_center(tile[fw_uu][y][x] + x + 0.5f, tile[fw_vv][y][x] + y + 0.5f); Vector2 fw_du(tile[fw_uu][y][xx] - tile[fw_uu][y][x] + 1, tile[fw_vv][y][xx] - tile[fw_vv][y][x]); Vector2 fw_dv(tile[fw_uu][tile.clampy(y + 1)][x] - tile[fw_uu][y][x], tile[fw_vv][tile.clampy(y + 1)][x] - tile[fw_vv][y][x] + 1); input(2)->sample(fw_center, fw_du, fw_dv, fw_pixel); ChannelSet m(Mask_RGB); foreach(z, m) { *(out.writable( _prevFrame[colourIndex(z)] ) + x) = bw_pixel[z]; *(out.writable( _nextFrame[colourIndex(z)] ) + x) = fw_pixel[z]; } } _firstTime = false; } } // end of lock //reset loop x = X; for (; x < r; x++) { foreach(z, channels) { *(out.writable(z) + x) = 0.5f; } } } void s_Dustbust::knobs(Knob_Callback f) { Input_Channel_knob(f, uv, 4, 0, "vectors", "Motion Vectors"); }
static const char* const CLASS = "s_Dustbust"; static const char* const HELP = "s_Dustbust tries to remove dust in an" "intelligent way, using simple math and" "motionvectors."; // Standard plug-in include files. #include "DDImage/Iop.h" #include "DDImage/Row.h" #include "DDImage/Tile.h" #include "DDImage/Knobs.h" #include "DDImage/MultiTile.h" #include "DDImage/Pixel.h" #include "DDImage/Vector2.h" #include "DDImage/Thread.h" #include "DDImage/NukeWrapper.h" using namespace DD::Image; #include <algorithm> #include <vector> using namespace std; class s_Dustbust : public Iop { private: Channel uv[4]; ChannelSet prevFrame, nextFrame; Channel _prevFrame[3]; Channel _nextFrame[3]; bool _firstTime; Lock _lock; int _size; public: //! Constructor. Initialize user controls to their default values. s_Dustbust (Node* node) : Iop (node) { uv[0] = uv[1] = uv[2] = uv[3] = Chan_Black; prevFrame = nextFrame = Mask_None; _prevFrame[0] = getChannel("_prevFrame.r"); _prevFrame[1] = getChannel("_prevFrame.g"); _prevFrame[2] = getChannel("_prevFrame.b"); _nextFrame[0] = getChannel("_nextFrame.r"); _nextFrame[1] = getChannel("_nextFrame.g"); _nextFrame[2] = getChannel("_nextFrame.b"); _firstTime = true; _size = 2; } ~s_Dustbust () {} int maximum_inputs() const { return 1; } int minimum_inputs() const { return 1; } int split_input(int n) const { return 3; } const OutputContext& inputContext(int, int, OutputContext&) const; void _validate(bool) { copy_info(); prevFrame.insert(_prevFrame, 3); nextFrame.insert(_nextFrame, 3); } void in_channels(int, ChannelSet& mask) const { for(int i = 0; i < 4; i++) mask += (uv[i]); for(int i = 0; i < 3; i++) { mask += _prevFrame[i]; mask += _nextFrame[i]; } } void _request(int x, int y, int r, int t, ChannelMask channels, int count) { ChannelSet c(channels); in_channels(0, c); int X = input0().info().x(); int Y = input0().info().y(); int R = input0().info().r(); int T = input0().info().t(); for(int i = 0; i <= 2; i++) input(i)->request( X, Y, R, T, c, count*2 ); } mFnDDImageMultiTileGenerateEngineInline(input0()) template<class TileType> void doEngine(int, int, int, ChannelMask, Row&); virtual void knobs(Knob_Callback); //! Return the name of the class. const char* Class() const { return CLASS; } const char* node_help() const { return HELP; } private: //! Information to the plug-in manager of DDNewImage/NUKE. static const Iop::Description d; }; const OutputContext& s_Dustbust::inputContext(int i, int n, OutputContext& context) const { context = outputContext(); switch(n) { case 0: break; case 1: context.setFrame(context.frame() - 1); break; case 2: context.setFrame(context.frame() + 1); break; } return context; } static Iop* build(Node* node) { return (new NukeWrapper( new s_Dustbust(node)))->noMix()->noMask(); } const Iop::Description s_Dustbust::d ( CLASS, "Filter/s_Dustbust", build ); template<class TileType> void s_Dustbust::doEngine(int y, int x, int r, ChannelMask channels, Row& out) { int X = x; ChannelSet c(channels); in_channels(0, c); TileType tile(*input(0), x - 1, y - 1, r + 1, y + 2, c); // *input(0) = input0() { Guard guard(_lock); if (_firstTime) { if (aborted()) return; // forward motionvectors Channel fw_uu = uv[0]; Channel fw_vv = uv[1]; if(!intersect(tile.channels(), fw_uu)) fw_uu = Chan_Black; if(!intersect(tile.channels(), fw_vv)) fw_vv = Chan_Black; // backward motionvectors Channel bw_uu = uv[2]; Channel bw_vv = uv[3]; if(!intersect(tile.channels(), bw_uu)) bw_uu = Chan_Black; if(!intersect(tile.channels(), bw_vv)) bw_vv = Chan_Black; //foreach(z, channels) out.writable(z); InterestRatchet interestRatchet; Pixel fw_pixel(channels), bw_pixel(channels); fw_pixel.setInterestRatchet(&interestRatchet); bw_pixel.setInterestRatchet(&interestRatchet); for (; x < r; x++) { if (aborted()) break; int xx = x + 1; if (xx >= info_.r()) xx = info_.r() - 1; Vector2 bw_center(tile[bw_uu][y][x] + x + 0.5f, tile[bw_vv][y][x] + y + 0.5f); Vector2 bw_du(tile[bw_uu][y][xx] - tile[bw_uu][y][x] + 1, tile[bw_vv][y][xx] - tile[bw_vv][y][x]); Vector2 bw_dv(tile[bw_uu][tile.clampy(y + 1)][x] - tile[bw_uu][y][x], tile[bw_vv][tile.clampy(y + 1)][x] - tile[bw_vv][y][x] + 1); input(1)->sample(bw_center, bw_du, bw_dv, bw_pixel); Vector2 fw_center(tile[fw_uu][y][x] + x + 0.5f, tile[fw_vv][y][x] + y + 0.5f); Vector2 fw_du(tile[fw_uu][y][xx] - tile[fw_uu][y][x] + 1, tile[fw_vv][y][xx] - tile[fw_vv][y][x]); Vector2 fw_dv(tile[fw_uu][tile.clampy(y + 1)][x] - tile[fw_uu][y][x], tile[fw_vv][tile.clampy(y + 1)][x] - tile[fw_vv][y][x] + 1); input(2)->sample(fw_center, fw_du, fw_dv, fw_pixel); ChannelSet m(Mask_RGB); foreach(z, m) { *(out.writable( _prevFrame[colourIndex(z)] ) + x) = bw_pixel[z]; *(out.writable( _nextFrame[colourIndex(z)] ) + x) = fw_pixel[z]; } } _firstTime = false; } } // end of lock //reset loop x = X; foreach(z, channels) { if (colourIndex(z) < 3) { for (; x < r; x++) *(out.writable(z) + x) = 0.5f; } else input(0)->get(y, x, r, z, out); } } void s_Dustbust::knobs(Knob_Callback f) { Input_Channel_knob(f, uv, 4, 0, "vectors", "Motion Vectors"); }
Update s_Dustbust.cpp
Update s_Dustbust.cpp
C++
apache-2.0
zeemzoet/nuke,zeemzoet/nuke
c36a96b0697d45d2a07a537b6ebc13ec377ef685
net/http/http_network_session.cc
net/http/http_network_session.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/http/http_network_session.h" #include "base/logging.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/url_security_manager.h" #include "net/spdy/spdy_session_pool.h" namespace net { // static int HttpNetworkSession::max_sockets_ = 100; // static int HttpNetworkSession::max_sockets_per_group_ = 6; // static uint16 HttpNetworkSession::g_fixed_http_port = 0; uint16 HttpNetworkSession::g_fixed_https_port = 0; // TODO(vandebo) when we've completely converted to pools, the base TCP // pool name should get changed to TCP instead of Transport. HttpNetworkSession::HttpNetworkSession( NetworkChangeNotifier* network_change_notifier, HostResolver* host_resolver, ProxyService* proxy_service, ClientSocketFactory* client_socket_factory, SSLConfigService* ssl_config_service, SpdySessionPool* spdy_session_pool, HttpAuthHandlerFactory* http_auth_handler_factory) : network_change_notifier_(network_change_notifier), tcp_socket_pool_(new TCPClientSocketPool( max_sockets_, max_sockets_per_group_, "Transport", host_resolver, client_socket_factory, network_change_notifier_)), socks_socket_pool_(new SOCKSClientSocketPool( max_sockets_, max_sockets_per_group_, "SOCKS", host_resolver, new TCPClientSocketPool(max_sockets_, max_sockets_per_group_, "TCPForSOCKS", host_resolver, client_socket_factory, network_change_notifier_), network_change_notifier_)), socket_factory_(client_socket_factory), host_resolver_(host_resolver), proxy_service_(proxy_service), ssl_config_service_(ssl_config_service), spdy_session_pool_(spdy_session_pool), http_auth_handler_factory_(http_auth_handler_factory) { DCHECK(proxy_service); DCHECK(ssl_config_service); } HttpNetworkSession::~HttpNetworkSession() { } // static void HttpNetworkSession::set_max_sockets_per_group(int socket_count) { DCHECK(0 < socket_count); // The following is a sanity check... but we should NEVER be near this value. DCHECK(100 > socket_count); max_sockets_per_group_ = socket_count; } // TODO(vandebo) when we've completely converted to pools, the base TCP // pool name should get changed to TCP instead of Transport. void HttpNetworkSession::ReplaceTCPSocketPool() { tcp_socket_pool_ = new TCPClientSocketPool(max_sockets_, max_sockets_per_group_, "Transport", host_resolver_, socket_factory_, network_change_notifier_); } } // namespace net
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/http/http_network_session.h" #include "base/logging.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/url_security_manager.h" #include "net/spdy/spdy_session_pool.h" namespace net { // static int HttpNetworkSession::max_sockets_ = 256; // static int HttpNetworkSession::max_sockets_per_group_ = 6; // static uint16 HttpNetworkSession::g_fixed_http_port = 0; uint16 HttpNetworkSession::g_fixed_https_port = 0; // TODO(vandebo) when we've completely converted to pools, the base TCP // pool name should get changed to TCP instead of Transport. HttpNetworkSession::HttpNetworkSession( NetworkChangeNotifier* network_change_notifier, HostResolver* host_resolver, ProxyService* proxy_service, ClientSocketFactory* client_socket_factory, SSLConfigService* ssl_config_service, SpdySessionPool* spdy_session_pool, HttpAuthHandlerFactory* http_auth_handler_factory) : network_change_notifier_(network_change_notifier), tcp_socket_pool_(new TCPClientSocketPool( max_sockets_, max_sockets_per_group_, "Transport", host_resolver, client_socket_factory, network_change_notifier_)), socks_socket_pool_(new SOCKSClientSocketPool( max_sockets_, max_sockets_per_group_, "SOCKS", host_resolver, new TCPClientSocketPool(max_sockets_, max_sockets_per_group_, "TCPForSOCKS", host_resolver, client_socket_factory, network_change_notifier_), network_change_notifier_)), socket_factory_(client_socket_factory), host_resolver_(host_resolver), proxy_service_(proxy_service), ssl_config_service_(ssl_config_service), spdy_session_pool_(spdy_session_pool), http_auth_handler_factory_(http_auth_handler_factory) { DCHECK(proxy_service); DCHECK(ssl_config_service); } HttpNetworkSession::~HttpNetworkSession() { } // static void HttpNetworkSession::set_max_sockets_per_group(int socket_count) { DCHECK(0 < socket_count); // The following is a sanity check... but we should NEVER be near this value. DCHECK(100 > socket_count); max_sockets_per_group_ = socket_count; } // TODO(vandebo) when we've completely converted to pools, the base TCP // pool name should get changed to TCP instead of Transport. void HttpNetworkSession::ReplaceTCPSocketPool() { tcp_socket_pool_ = new TCPClientSocketPool(max_sockets_, max_sockets_per_group_, "Transport", host_resolver_, socket_factory_, network_change_notifier_); } } // namespace net
Increase the global TCP socket limit. It's too low. wtc likes powers of 2, so I chose 256 as we discussed earlier. We need to experiment more in the future. BUG=41289
Increase the global TCP socket limit. It's too low. wtc likes powers of 2, so I chose 256 as we discussed earlier. We need to experiment more in the future. BUG=41289 Review URL: http://codereview.chromium.org/1692008 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@45600 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
dednal/chromium.src,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,robclark/chromium,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,dushu1203/chromium.src,ChromiumWebApps/chromium,hujiajie/pa-chromium,hgl888/chromium-crosswalk,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,Just-D/chromium-1,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,ondra-novak/chromium.src,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,anirudhSK/chromium,ondra-novak/chromium.src,jaruba/chromium.src,M4sse/chromium.src,keishi/chromium,TheTypoMaster/chromium-crosswalk,keishi/chromium,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,rogerwang/chromium,hujiajie/pa-chromium,littlstar/chromium.src,littlstar/chromium.src,Jonekee/chromium.src,Chilledheart/chromium,ltilve/chromium,bright-sparks/chromium-spacewalk,rogerwang/chromium,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,patrickm/chromium.src,jaruba/chromium.src,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,keishi/chromium,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,nacl-webkit/chrome_deps,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,axinging/chromium-crosswalk,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,dushu1203/chromium.src,anirudhSK/chromium,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,Chilledheart/chromium,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,keishi/chromium,littlstar/chromium.src,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,keishi/chromium,hgl888/chromium-crosswalk,rogerwang/chromium,fujunwei/chromium-crosswalk,dednal/chromium.src,dednal/chromium.src,pozdnyakov/chromium-crosswalk,fujunwei/chromium-crosswalk,markYoungH/chromium.src,ChromiumWebApps/chromium,littlstar/chromium.src,anirudhSK/chromium,chuan9/chromium-crosswalk,rogerwang/chromium,hgl888/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,Just-D/chromium-1,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,rogerwang/chromium,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,dushu1203/chromium.src,keishi/chromium,dednal/chromium.src,robclark/chromium,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,robclark/chromium,hujiajie/pa-chromium,ltilve/chromium,dushu1203/chromium.src,markYoungH/chromium.src,anirudhSK/chromium,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,Just-D/chromium-1,chuan9/chromium-crosswalk,Jonekee/chromium.src,M4sse/chromium.src,dednal/chromium.src,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,ChromiumWebApps/chromium,markYoungH/chromium.src,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,robclark/chromium,Chilledheart/chromium,ChromiumWebApps/chromium,anirudhSK/chromium,Just-D/chromium-1,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,robclark/chromium,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,robclark/chromium,M4sse/chromium.src,hujiajie/pa-chromium,Chilledheart/chromium,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,ltilve/chromium,PeterWangIntel/chromium-crosswalk,keishi/chromium,fujunwei/chromium-crosswalk,rogerwang/chromium,dednal/chromium.src,zcbenz/cefode-chromium,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,ChromiumWebApps/chromium,rogerwang/chromium,Chilledheart/chromium,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,Jonekee/chromium.src,M4sse/chromium.src,littlstar/chromium.src,nacl-webkit/chrome_deps,ltilve/chromium,dushu1203/chromium.src,hujiajie/pa-chromium,keishi/chromium,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,robclark/chromium,hujiajie/pa-chromium,anirudhSK/chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,axinging/chromium-crosswalk,dednal/chromium.src,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,rogerwang/chromium,ondra-novak/chromium.src,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,M4sse/chromium.src,ltilve/chromium,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,dednal/chromium.src,patrickm/chromium.src,dednal/chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,keishi/chromium,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dednal/chromium.src,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,Chilledheart/chromium,Jonekee/chromium.src,ltilve/chromium,patrickm/chromium.src,markYoungH/chromium.src,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,ondra-novak/chromium.src,zcbenz/cefode-chromium,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,axinging/chromium-crosswalk,jaruba/chromium.src,krieger-od/nwjs_chromium.src,rogerwang/chromium,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,keishi/chromium,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,rogerwang/chromium,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,Jonekee/chromium.src,ltilve/chromium,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,littlstar/chromium.src,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,robclark/chromium,Fireblend/chromium-crosswalk,dednal/chromium.src,patrickm/chromium.src,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,ltilve/chromium,ChromiumWebApps/chromium,hujiajie/pa-chromium,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,Chilledheart/chromium,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,M4sse/chromium.src,M4sse/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,nacl-webkit/chrome_deps,robclark/chromium,mogoweb/chromium-crosswalk,robclark/chromium,keishi/chromium,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,chuan9/chromium-crosswalk,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish
a2e6629766bc712e26192d55a852199a60bb34fb
tree.hpp
tree.hpp
#include <stdlib.h> #include <stdio.h> #include "node.hpp" using namespace std; class Tree { public: Tree(); ~Tree(); void insert(string key, int value); Node *search(string key); void destroy_tree(); void print(); private: int string_to_hash(string key); void destroy_tree(Node *leaf); void insert(int key, int value, Node *leaf); void print(Node *leaf); Node *search(int key, Node *leaf); Node *root; }; Tree::Tree() { root = NULL; } Tree::~Tree() { destroy_tree(); } int Tree::string_to_hash(string key) { /* TODO: Use a more robust hashing algorithm */ hash<string> str_hash; return str_hash(key); } void Tree::insert(int key, int value, Node *leaf) { Node * new_node; if(key < leaf->get_key()) { if(leaf->get_left() != NULL) { insert(key, value, leaf->get_left()); } else { new_node = new Node(); new_node->set_key(key); new_node->set_value(value); leaf->set_left(new_node); } } else if(key > leaf->get_key()) { if(leaf->get_right() != NULL) { insert(key, value, leaf->get_right()); } else { new_node = new Node(); new_node->set_key(key); new_node->set_value(value); leaf->set_right(new_node); } } else if(key == leaf->get_key()) { leaf->set_value(value); } } Node *Tree::search(int key, Node *leaf) { if(leaf != NULL) { if(key == leaf->get_key()) { return leaf; } else if (key < leaf->get_key()) { return search(key, leaf->get_left()); } return search(key, leaf->get_right()); } return NULL; } void Tree:: insert(string key, int value) { int hash_key = string_to_hash(key); if(root != NULL) { insert(hash_key, value, root); } else { root = new Node(); root->set_value(value); root->set_key(hash_key); } } Node *Tree::search(string key) { int hash_key = string_to_hash(key); return search(hash_key, root); } void Tree::destroy_tree() { delete root; } void Tree::print(Node *leaf) { if(leaf->get_left() != NULL) { print(leaf->get_left()); } if(leaf->get_right() != NULL) { print(leaf->get_right()); } } void Tree::print() { print(root); }
#include <stdlib.h> #include <stdio.h> #include "node.hpp" using namespace std; class Tree { public: Tree(); ~Tree(); void insert(string key, int value); Node *search(string key); void destroy_tree(); void print(); private: int string_to_hash(string key); void destroy_tree(Node *leaf); void insert(int key, int value, Node *leaf); void print(Node *leaf); Node *search(int key, Node *leaf); Node *root; }; Tree::Tree() { root = NULL; } Tree::~Tree() { destroy_tree(); } int Tree::string_to_hash(string key) { /* TODO: Use a more robust hashing algorithm */ hash<string> str_hash; return str_hash(key); } /* Tree insert takes a key, a value, and a Node pointer * Returns void. * * This function is a tail recursive depth first insert * algorithm. The time complexity in the worst case is * O(N). On average it will be O(log(N)) assuming the * tree is reasonably balanced. */ void Tree::insert(int key, int value, Node *leaf) { Node * new_node; if(key < leaf->get_key()) { if(leaf->get_left() != NULL) { return insert(key, value, leaf->get_left()); } else { new_node = new Node(); new_node->set_key(key); new_node->set_value(value); leaf->set_left(new_node); } } else if(key > leaf->get_key()) { if(leaf->get_right() != NULL) { return insert(key, value, leaf->get_right()); } else { new_node = new Node(); new_node->set_key(key); new_node->set_value(value); leaf->set_right(new_node); } } else if(key == leaf->get_key()) { leaf->set_value(value); } } /* Tree search takes a key, and a Node pointer * Returns a Node *. * * This function is a tail recursive depth first search * algorithm. The time complexity in the worst case is * O(N). On average it will be O(log(N)) assuming the * tree is reasonably balanced. */ Node *Tree::search(int key, Node *leaf) { if(leaf != NULL) { if(key == leaf->get_key()) { return leaf; } else if (key < leaf->get_key()) { return search(key, leaf->get_left()); } return search(key, leaf->get_right()); } return NULL; } void Tree:: insert(string key, int value) { int hash_key = string_to_hash(key); if(root != NULL) { insert(hash_key, value, root); } else { root = new Node(); root->set_value(value); root->set_key(hash_key); } } Node *Tree::search(string key) { int hash_key = string_to_hash(key); return search(hash_key, root); } void Tree::destroy_tree() { delete root; } void Tree::print(Node *leaf) { if(leaf->get_left() != NULL) { print(leaf->get_left()); } if(leaf->get_right() != NULL) { print(leaf->get_right()); } } void Tree::print() { print(root); }
Document depth first insert & depths first search
Document depth first insert & depths first search
C++
mit
kahnjw/treepp,kahnjw/treepp
ca23d656187c33f480b433e38009e0ae182d8c9f
search/closedlist.hpp
search/closedlist.hpp
#pragma once #include <cstdio> #include <typeinfo> #include <cstring> void dfpair(FILE *, const char *key, const char *fmt, ...); // utils.hpp enum { FillFact = 0 }; template<typename Node, typename D> struct ClosedEntry { Node *nxt; }; template<typename Ops, typename Node, typename D> struct ClosedList { enum { Defsz = 1024, Growfact = 2, Fillfact = 0, }; typedef typename D::PackedState PackedState; ClosedList(unsigned long szhint) : fill(0), ncollide(0), nresize(0), nbins(0), bins(NULL) { resize(szhint); nresize = 0; // don't count the initial resize } void init(D &d) { dom = &d; } void clear() { fill = ncollide = 0; nresize = 0; for (unsigned int i = 0; i < nbins; i++) bins[i] = NULL; } void add(Node *n) { add(n, dom->hash(Ops::key(n))); } void add(Node *n, unsigned long h) { if (fill * Fillfact >= nbins) resize(nbins == 0 ? Defsz : nbins * Growfact); add(bins, nbins, n, h); fill++; } Node *find(PackedState &k) { return find(k, dom->hash(k)); } Node *find(PackedState &k, unsigned long h) { for (Node *p = bins[h % nbins]; p; p = Ops::closedentry(p).nxt) { if (Ops::key(p) == k) return p; } return NULL; } void prstats(FILE *out, const char *prefix) { dfpair(out, "closed list type", "%s", "hash table"); char key[strlen(prefix) + strlen("collisions") + 1]; strcpy(key, prefix); strcat(key+strlen(prefix), "fill"); dfpair(out, key, "%lu", fill); strcpy(key+strlen(prefix), "collisions"); dfpair(out, key, "%lu", ncollide); strcpy(key+strlen(prefix), "resizes"); dfpair(out, key, "%lu", nresize); strcpy(key+strlen(prefix), "buckets"); dfpair(out, key, "%lu", nbins); } private: void add(Node *b[], unsigned int n, Node *e, unsigned long h) { unsigned int i = h % n; if (b[i]) ncollide++; Ops::closedentry(e).nxt = b[i]; b[i] = e; } void resize(unsigned int sz) { Node **b = new Node*[sz]; for (unsigned int i = 0; i < sz; i++) b[i] = NULL; for (unsigned int i = 0; i < nbins; i++) { for (Node *p = bins[i]; p; p = Ops::closedentry(p).nxt) add(b, sz, p, dom->hash(Ops::key(p))); } if (bins) delete[] bins; bins = b; nbins = sz; nresize++; } D *dom; unsigned long fill, ncollide; unsigned int nresize, nbins; Node** bins; };
#pragma once #include <cstdio> #include <typeinfo> #include <cstring> void dfpair(FILE *, const char *key, const char *fmt, ...); // utils.hpp enum { FillFact = 0 }; template<typename Node, typename D> struct ClosedEntry { Node *nxt; }; template<typename Ops, typename Node, typename D> struct ClosedList { enum { Defsz = 1024, Growfact = 2, Fillfact = 0, }; typedef typename D::PackedState PackedState; ClosedList(unsigned long szhint) : fill(0), ncollide(0), nresize(0), nbins(0), bins(NULL) { resize(szhint); nresize = 0; // don't count the initial resize } ~ClosedList() { if (bins) delete []bins; } void init(D &d) { dom = &d; } void clear() { fill = ncollide = 0; nresize = 0; for (unsigned int i = 0; i < nbins; i++) bins[i] = NULL; } void add(Node *n) { add(n, dom->hash(Ops::key(n))); } void add(Node *n, unsigned long h) { if (fill * Fillfact >= nbins) resize(nbins == 0 ? Defsz : nbins * Growfact); add(bins, nbins, n, h); fill++; } Node *find(PackedState &k) { return find(k, dom->hash(k)); } Node *find(PackedState &k, unsigned long h) { for (Node *p = bins[h % nbins]; p; p = Ops::closedentry(p).nxt) { if (Ops::key(p) == k) return p; } return NULL; } void prstats(FILE *out, const char *prefix) { dfpair(out, "closed list type", "%s", "hash table"); char key[strlen(prefix) + strlen("collisions") + 1]; strcpy(key, prefix); strcat(key+strlen(prefix), "fill"); dfpair(out, key, "%lu", fill); strcpy(key+strlen(prefix), "collisions"); dfpair(out, key, "%lu", ncollide); strcpy(key+strlen(prefix), "resizes"); dfpair(out, key, "%lu", nresize); strcpy(key+strlen(prefix), "buckets"); dfpair(out, key, "%lu", nbins); } private: void add(Node *b[], unsigned int n, Node *e, unsigned long h) { unsigned int i = h % n; if (b[i]) ncollide++; Ops::closedentry(e).nxt = b[i]; b[i] = e; } void resize(unsigned int sz) { Node **b = new Node*[sz]; for (unsigned int i = 0; i < sz; i++) b[i] = NULL; for (unsigned int i = 0; i < nbins; i++) { for (Node *p = bins[i]; p; p = Ops::closedentry(p).nxt) add(b, sz, p, dom->hash(Ops::key(p))); } if (bins) delete[] bins; bins = b; nbins = sz; nresize++; } D *dom; unsigned long fill, ncollide; unsigned int nresize, nbins; Node** bins; };
Add a destructor for ClosedList.
Add a destructor for ClosedList.
C++
mit
eaburns/search,eaburns/search,skiesel/search,skiesel/search,eaburns/search,skiesel/search
19636d28c3b15c930f8c7ebeae96372fb9a86427
sensors/BM1422GMV.cpp
sensors/BM1422GMV.cpp
#ifndef _BM1422GMV_CPP #define _BM1422GMV_CPP //BM1422GMV register map #define BM1422GMV_REG_INFO_LSB 0x0D #define BM1422GMV_REG_INFO_MSB 0x0E #define BM1422GMV_REG_WHO_AM_I 0x0F #define BM1422GMV_REG_DATA_X_LSB 0x10 #define BM1422GMV_REG_DATA_X_MSB 0x11 #define BM1422GMV_REG_DATA_Y_LSB 0x12 #define BM1422GMV_REG_DATA_Y_MSB 0x13 #define BM1422GMV_REG_DATA_Z_LSB 0x14 #define BM1422GMV_REG_DATA_Z_MSB 0x15 #define BM1422GMV_REG_STA_1 0x18 #define BM1422GMV_REG_CNTL_1 0x1B #define BM1422GMV_REG_CNTL_2 0x1C #define BM1422GMV_REG_CNTL_3 0x1D #define BM1422GMV_REG_PRET 0x30 #define BM1422GMV_REG_AVE_A 0x40 #define BM1422GMV_REG_CNTL_4_LSB 0x5C #define BM1422GMV_REG_CNTL_4_MSB 0x5D #define BM1422GMV_REG_TEMP_LSB 0x60 #define BM1422GMV_REG_TEMP_MSB 0x61 #define BM1422GMV_REG_OFF_X 0x6C #define BM1422GMV_REG_OFF_Y 0x72 #define BM1422GMV_REG_OFF_Z 0x78 #define BM1422GMV_REG_FINEOUTPUT_X_LSB 0x90 #define BM1422GMV_REG_FINEOUTPUT_X_MSB 0x91 #define BM1422GMV_REG_FINEOUTPUT_Y_LSB 0x92 #define BM1422GMV_REG_FINEOUTPUT_Y_MSB 0x93 #define BM1422GMV_REG_FINEOUTPUT_Z_LSB 0x94 #define BM1422GMV_REG_FINEOUTPUT_Z_MSB 0x95 #define BM1422GMV_REG_GAIN_PARA_X_TO_Z 0x9C #define BM1422GMV_REG_GAIN_PARA_X_TO_Y 0x9D #define BM1422GMV_REG_GAIN_PARA_Y_TO_Z 0x9E #define BM1422GMV_REG_GAIN_PARA_Y_TO_X 0x9F #define BM1422GMV_REG_GAIN_PARA_Z_TO_Y 0xA0 #define BM1422GMV_REG_GAIN_PARA_Z_TO_X 0xA1 //BM1422GMV default values #define BM1422GMV_DEVICE_ADDRESS_L 0x0E #define BM1422GMV_DEVICE_ADDRESS_H 0x0F #define BM1422GMV_WHO_AM_I 0x41 #define INT_0 0x00 #define INT_1 0x01 //BM1422GMV settings //BM1422GMV_REG_STA_1 MSB LSB DESCRIPTION #define BM1422GMV_DRDY_NOT_READY 0b00000000 // 6 6 measured data not ready #define BM1422GMV_DRDY_READY 0b01000000 // 6 6 measured data ready //BM1422GMV_REG_CNTL_1 #define BM1422GMV_POWER_DOWN 0b00000000 // 7 7 power control: power down #define BM1422GMV_ACTIVE 0b10000000 // 7 7 active #define BM1422GMV_OUTPUT_12_BIT 0b00000000 // 6 6 output: 12-bit #define BM1422GMV_OUTPUT_14_BIT 0b01000000 // 6 6 14-bit #define BM1422GMV_RESET_RELEASE 0b00000000 // 5 5 reset logic: reset release #define BM1422GMV_RESET 0b00100000 // 5 5 reset #define BM1422GMV_OUTPUT_RATE_10_HZ 0b00000000 // 4 3 data output rate: 10 Hz #define BM1422GMV_OUTPUT_RATE_20_HZ 0b00000000 // 4 3 20 Hz #define BM1422GMV_OUTPUT_RATE_100_HZ 0b00000000 // 4 3 100 Hz #define BM1422GMV_OUTPUT_RATE_1_KHZ 0b00000000 // 4 3 1 kHz #define BM1422GMV_MODE_CONTINUOUS 0b00000000 // 1 1 continuous measurement mode #define BM1422GMV_MODE_SINGLE 0b00000010 // 1 1 single measurement mode //BM1422GMV_REG_CNTL_2 #define BM1422GMV_DRDY_OFF 0b00000000 // 3 3 DRDY output disabled #define BM1422GMV_DRDY_ON 0b00001000 // 3 3 DRDY output enabled #define BM1422GMV_DRDY_ACTIVE_LOW 0b00000000 // 2 2 DRDY active low #define BM1422GMV_DRDY_ACTIVE_HIGH 0b00000100 // 2 2 DRDY active high //BM1422GMV_REG_CNTL_3 #define BM1422GMV_FORCE_MEASUREMENT 0b01000000 // 6 6 force start new measurement or restart running //BM1422GMV_REG_AVE_A #define BM1422GMV_AVERAGE_1 0b00000100 // 4 2 number of measurements to average: 1 #define BM1422GMV_AVERAGE_2 0b00001000 // 4 2 2 #define BM1422GMV_AVERAGE_4 0b00000000 // 4 2 4 #define BM1422GMV_AVERAGE_8 0b00001100 // 4 2 8 #define BM1422GMV_AVERAGE_16 0b00010000 // 4 2 16 class BM1422GMV { public: BM1422GMV(uint8_t intNum = INT_0, uint8_t address = BM1422GMV_DEVICE_ADDRESS_L) { _intNum = intNum; _address = address; } int init(void (*f)(), uint8_t mode = BM1422GMV_MODE_SINGLE, uint8_t rate = BM1422GMV_OUTPUT_RATE_10_HZ, uint8_t output = BM1422GMV_OUTPUT_14_BIT, uint8_t avg = BM1422GMV_AVERAGE_4) { if(_utils.getRegValue(_address, BM1422GMV_REG_WHO_AM_I) != BM1422GMV_WHO_AM_I) { return(-1); } _flagDrdy = 0; if(output == BM1422GMV_OUTPUT_14_BIT) { _outputSens = 24; } else if(output == BM1422GMV_OUTPUT_12_BIT) { _outputSens = 6; } _utils.setRegValue(_address, BM1422GMV_REG_CNTL_4_MSB, 0x00); _utils.setRegValue(_address, BM1422GMV_REG_CNTL_4_LSB, 0x00); _utils.setRegValue(_address, BM1422GMV_REG_CNTL_1, BM1422GMV_ACTIVE | output | mode); _utils.setRegValue(_address, BM1422GMV_REG_CNTL_2, BM1422GMV_DRDY_ON | BM1422GMV_DRDY_ACTIVE_LOW, 3, 2); _utils.setRegValue(_address, BM1422GMV_REG_AVE_A, BM1422GMV_AVERAGE_4, 4, 2); attachInterrupt(_intNum, f, FALLING); return(0); } float* measure(void) { float* value = new float[3]; _utils.setRegValue(_address, BM1422GMV_REG_CNTL_3, BM1422GMV_FORCE_MEASUREMENT, 6, 6); while(_flagDrdy == 0) { delayMicroseconds(200); digitalWrite(12, HIGH); //no idea why this works, seems like it has to do something here, otherwise the interrupt never arrives } _flagDrdy = 0; value[0] = (float)(((int16_t)_utils.getRegValue(_address, BM1422GMV_REG_DATA_X_MSB) << 8) | _utils.getRegValue(_address, BM1422GMV_REG_DATA_X_LSB)) / _outputSens; value[1] = (float)(((int16_t)_utils.getRegValue(_address, BM1422GMV_REG_DATA_Y_MSB) << 8) | _utils.getRegValue(_address, BM1422GMV_REG_DATA_Y_LSB)) / _outputSens; value[2] = (float)(((int16_t)_utils.getRegValue(_address, BM1422GMV_REG_DATA_Z_MSB) << 8) | _utils.getRegValue(_address, BM1422GMV_REG_DATA_Z_LSB)) / _outputSens; return(value); } void setFlagDrdy(void) { _flagDrdy = 1; } private: utilities _utils; uint8_t _address, _intNum, _outputSens, _flagDrdy; }; #endif
#ifndef _BM1422GMV_CPP #define _BM1422GMV_CPP //BM1422GMV register map #define BM1422GMV_REG_INFO_LSB 0x0D #define BM1422GMV_REG_INFO_MSB 0x0E #define BM1422GMV_REG_WHO_AM_I 0x0F #define BM1422GMV_REG_DATA_X_LSB 0x10 #define BM1422GMV_REG_DATA_X_MSB 0x11 #define BM1422GMV_REG_DATA_Y_LSB 0x12 #define BM1422GMV_REG_DATA_Y_MSB 0x13 #define BM1422GMV_REG_DATA_Z_LSB 0x14 #define BM1422GMV_REG_DATA_Z_MSB 0x15 #define BM1422GMV_REG_STA_1 0x18 #define BM1422GMV_REG_CNTL_1 0x1B #define BM1422GMV_REG_CNTL_2 0x1C #define BM1422GMV_REG_CNTL_3 0x1D #define BM1422GMV_REG_PRET 0x30 #define BM1422GMV_REG_AVE_A 0x40 #define BM1422GMV_REG_CNTL_4_LSB 0x5C #define BM1422GMV_REG_CNTL_4_MSB 0x5D #define BM1422GMV_REG_TEMP_LSB 0x60 #define BM1422GMV_REG_TEMP_MSB 0x61 #define BM1422GMV_REG_OFF_X 0x6C #define BM1422GMV_REG_OFF_Y 0x72 #define BM1422GMV_REG_OFF_Z 0x78 #define BM1422GMV_REG_FINEOUTPUT_X_LSB 0x90 #define BM1422GMV_REG_FINEOUTPUT_X_MSB 0x91 #define BM1422GMV_REG_FINEOUTPUT_Y_LSB 0x92 #define BM1422GMV_REG_FINEOUTPUT_Y_MSB 0x93 #define BM1422GMV_REG_FINEOUTPUT_Z_LSB 0x94 #define BM1422GMV_REG_FINEOUTPUT_Z_MSB 0x95 #define BM1422GMV_REG_GAIN_PARA_X_TO_Z 0x9C #define BM1422GMV_REG_GAIN_PARA_X_TO_Y 0x9D #define BM1422GMV_REG_GAIN_PARA_Y_TO_Z 0x9E #define BM1422GMV_REG_GAIN_PARA_Y_TO_X 0x9F #define BM1422GMV_REG_GAIN_PARA_Z_TO_Y 0xA0 #define BM1422GMV_REG_GAIN_PARA_Z_TO_X 0xA1 //BM1422GMV default values #define BM1422GMV_DEVICE_ADDRESS_L 0x0E #define BM1422GMV_DEVICE_ADDRESS_H 0x0F #define BM1422GMV_WHO_AM_I 0x41 #define INT_0 0x00 #define INT_1 0x01 //BM1422GMV settings //BM1422GMV_REG_STA_1 MSB LSB DESCRIPTION #define BM1422GMV_DRDY_NOT_READY 0b00000000 // 6 6 measured data not ready #define BM1422GMV_DRDY_READY 0b01000000 // 6 6 measured data ready //BM1422GMV_REG_CNTL_1 #define BM1422GMV_POWER_DOWN 0b00000000 // 7 7 power control: power down #define BM1422GMV_ACTIVE 0b10000000 // 7 7 active #define BM1422GMV_OUTPUT_12_BIT 0b00000000 // 6 6 output: 12-bit #define BM1422GMV_OUTPUT_14_BIT 0b01000000 // 6 6 14-bit #define BM1422GMV_RESET_RELEASE 0b00000000 // 5 5 reset logic: reset release #define BM1422GMV_RESET 0b00100000 // 5 5 reset #define BM1422GMV_OUTPUT_RATE_10_HZ 0b00000000 // 4 3 data output rate: 10 Hz #define BM1422GMV_OUTPUT_RATE_20_HZ 0b00000000 // 4 3 20 Hz #define BM1422GMV_OUTPUT_RATE_100_HZ 0b00000000 // 4 3 100 Hz #define BM1422GMV_OUTPUT_RATE_1_KHZ 0b00000000 // 4 3 1 kHz #define BM1422GMV_MODE_CONTINUOUS 0b00000000 // 1 1 continuous measurement mode #define BM1422GMV_MODE_SINGLE 0b00000010 // 1 1 single measurement mode //BM1422GMV_REG_CNTL_2 #define BM1422GMV_DRDY_OFF 0b00000000 // 3 3 DRDY output disabled #define BM1422GMV_DRDY_ON 0b00001000 // 3 3 DRDY output enabled #define BM1422GMV_DRDY_ACTIVE_LOW 0b00000000 // 2 2 DRDY active low #define BM1422GMV_DRDY_ACTIVE_HIGH 0b00000100 // 2 2 DRDY active high //BM1422GMV_REG_CNTL_3 #define BM1422GMV_FORCE_MEASUREMENT 0b01000000 // 6 6 force start new measurement or restart running //BM1422GMV_REG_AVE_A #define BM1422GMV_AVERAGE_1 0b00000100 // 4 2 number of measurements to average: 1 #define BM1422GMV_AVERAGE_2 0b00001000 // 4 2 2 #define BM1422GMV_AVERAGE_4 0b00000000 // 4 2 4 #define BM1422GMV_AVERAGE_8 0b00001100 // 4 2 8 #define BM1422GMV_AVERAGE_16 0b00010000 // 4 2 16 class BM1422GMV { public: BM1422GMV(uint8_t intNum = INT_0, uint8_t address = BM1422GMV_DEVICE_ADDRESS_L) { _intNum = intNum; _address = address; } int init(void func(void), uint8_t mode = BM1422GMV_MODE_SINGLE, uint8_t rate = BM1422GMV_OUTPUT_RATE_10_HZ, uint8_t output = BM1422GMV_OUTPUT_14_BIT, uint8_t avg = BM1422GMV_AVERAGE_4) { if(_utils.getRegValue(_address, BM1422GMV_REG_WHO_AM_I) != BM1422GMV_WHO_AM_I) { return(-1); } _flagDrdy = 0; if(output == BM1422GMV_OUTPUT_14_BIT) { _outputSens = 24; } else if(output == BM1422GMV_OUTPUT_12_BIT) { _outputSens = 6; } _utils.setRegValue(_address, BM1422GMV_REG_CNTL_4_MSB, 0x00); _utils.setRegValue(_address, BM1422GMV_REG_CNTL_4_LSB, 0x00); _utils.setRegValue(_address, BM1422GMV_REG_CNTL_1, BM1422GMV_ACTIVE | output | mode); _utils.setRegValue(_address, BM1422GMV_REG_CNTL_2, BM1422GMV_DRDY_ON | BM1422GMV_DRDY_ACTIVE_LOW, 3, 2); _utils.setRegValue(_address, BM1422GMV_REG_AVE_A, BM1422GMV_AVERAGE_4, 4, 2); attachInterrupt(_intNum, func, FALLING); return(0); } float* measure(void) { float* value = new float[3]; _utils.setRegValue(_address, BM1422GMV_REG_CNTL_3, BM1422GMV_FORCE_MEASUREMENT, 6, 6); while(_flagDrdy == 0) { delayMicroseconds(200); digitalWrite(12, HIGH); //no idea why this works, seems like it has to do something here, otherwise the interrupt never arrives } _flagDrdy = 0; value[0] = (float)(((int16_t)_utils.getRegValue(_address, BM1422GMV_REG_DATA_X_MSB) << 8) | _utils.getRegValue(_address, BM1422GMV_REG_DATA_X_LSB)) / _outputSens; value[1] = (float)(((int16_t)_utils.getRegValue(_address, BM1422GMV_REG_DATA_Y_MSB) << 8) | _utils.getRegValue(_address, BM1422GMV_REG_DATA_Y_LSB)) / _outputSens; value[2] = (float)(((int16_t)_utils.getRegValue(_address, BM1422GMV_REG_DATA_Z_MSB) << 8) | _utils.getRegValue(_address, BM1422GMV_REG_DATA_Z_LSB)) / _outputSens; return(value); } void setFlagDrdy(void) { _flagDrdy = 1; } private: utilities _utils; uint8_t _address, _intNum, _outputSens, _flagDrdy; }; #endif
Update BM1422GMV.cpp
Update BM1422GMV.cpp
C++
mit
jgromes/RohmMultiSensor
6d0813609edc4b7df74aeec68ad55c0c7a43ea4a
ch14/ex14_16_StrBlob.cpp
ch14/ex14_16_StrBlob.cpp
#include "ex14_16_StrBlob.h" //================================================================== // // operators // //================================================================== bool operator==(const StrBlob& lhs, const StrBlob& rhs) { return *lhs.data == *rhs.data; } bool operator!=(const StrBlob& lhs, const StrBlob& rhs) { return !(lhs == rhs); } bool operator==(const StrBlobPtr& lhs, const StrBlobPtr& rhs) { return lhs.curr == rhs.curr; } bool operator!=(const StrBlobPtr& lhs, const StrBlobPtr& rhs) { return !(lhs == rhs); } bool operator==(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { return lhs.curr == rhs.curr; } bool operator!=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { return !(lhs == rhs); } //================================================================== // // copy assignment operator and move assignment operator. // //================================================================== StrBlob& StrBlob::operator=(const StrBlob& lhs) { data = make_shared<vector<string>>(*lhs.data); return *this; } StrBlob& StrBlob::operator=(StrBlob&& rhs) NOEXCEPT { if (this != &rhs) { data = std::move(rhs.data); rhs.data = nullptr; } return *this; } //================================================================== // // members // //================================================================== StrBlobPtr StrBlob::begin() { return StrBlobPtr(*this); } StrBlobPtr StrBlob::end() { return StrBlobPtr(*this, data->size()); } ConstStrBlobPtr StrBlob::cbegin() const { return ConstStrBlobPtr(*this); } ConstStrBlobPtr StrBlob::cend() const { return ConstStrBlobPtr(*this, data->size()); }
#include <algorithm> #include "ex14_16_StrBlob.h" //================================================================== // // StrBlob - operators // //================================================================== bool operator==(const StrBlob& lhs, const StrBlob& rhs) { return *lhs.data == *rhs.data; } bool operator!=(const StrBlob& lhs, const StrBlob& rhs) { return !(lhs == rhs); } //================================================================ // // StrBlobPtr - operators // //================================================================ bool operator==(const StrBlobPtr& lhs, const StrBlobPtr& rhs) { return lhs.curr == rhs.curr; } bool operator!=(const StrBlobPtr& lhs, const StrBlobPtr& rhs) { return !(lhs == rhs); } //================================================================ // // ConstStrBlobPtr - operators // //================================================================ bool operator==(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { return lhs.curr == rhs.curr; } bool operator!=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs) { return !(lhs == rhs); } //================================================================== // // copy assignment operator and move assignment operator // //================================================================== StrBlob& StrBlob::operator=(const StrBlob& lhs) { data = make_shared<vector<string>>(*lhs.data); return *this; } StrBlob& StrBlob::operator=(StrBlob&& rhs) noexcept { if (this != &rhs) { data = move(rhs.data); rhs.data = nullptr; } return *this; } //================================================================== // // members // //================================================================== StrBlobPtr StrBlob::begin() { return StrBlobPtr(*this); } StrBlobPtr StrBlob::end() { return StrBlobPtr(*this, data->size()); } ConstStrBlobPtr StrBlob::cbegin() const { return ConstStrBlobPtr(*this); } ConstStrBlobPtr StrBlob::cend() const { return ConstStrBlobPtr(*this, data->size()); }
Update ex14_16_StrBlob.cpp
Update ex14_16_StrBlob.cpp
C++
cc0-1.0
zhangzhizhongz3/CppPrimer,zhangzhizhongz3/CppPrimer
86558c9b877428d18350803927a51e6acd0b52f0
source/thewizardplusplus/wizard-basic-3/process_command_line_arguments.cpp
source/thewizardplusplus/wizard-basic-3/process_command_line_arguments.cpp
#include "process_command_line_arguments.h" #include <iostream> #include <boost/program_options.hpp> #include <boost/format.hpp> using namespace boost; using namespace boost::program_options; const auto POSITIONAL_ARGUMENT_SIGNLE_REPETITION = 1; const auto POSITIONAL_ARGUMENT_UNLIMITED_REPETITIONS = -1; namespace thewizardplusplus { namespace wizard_basic_3 { auto ProcessCommandLineArguments( const int number_of_arguments, char* arguments[] ) -> CommandLineArguments { auto interpreter_arguments_description = options_description("Options"); interpreter_arguments_description.add_options() ("version,v", "- show version;") ("help,h", "- show help;") ( "final-stage,s", value<std::string>(), R"(- set final stage (allowed: "code", "ast" and "ir").)" ) ("script-file", value<std::string>(), "script file") ( "script-arguments", value<StringGroup>()->composing(), "script arguments" ); auto script_arguments_description = positional_options_description(); script_arguments_description.add( "script-file", POSITIONAL_ARGUMENT_SIGNLE_REPETITION ); script_arguments_description.add( "script-arguments", POSITIONAL_ARGUMENT_UNLIMITED_REPETITIONS ); auto arguments_map = variables_map(); store( command_line_parser(number_of_arguments, arguments) .options(interpreter_arguments_description) .positional(script_arguments_description) .run(), arguments_map ); notify(arguments_map); if (arguments_map.count("version")) { std::cout << "Wizard Basic 3 interpreter, v1.0\n" "(c) thewizardplusplus, 2014\n"; std::exit(EXIT_SUCCESS); } if (arguments_map.count("help")) { std::cout << "Usage: wb3i [options] <script-file> [<script-arguments>]\n" << interpreter_arguments_description; std::exit(EXIT_SUCCESS); } auto command_line_arguments = CommandLineArguments(); if (arguments_map.count("final-stage")) { const auto final_stage = arguments_map["final-stage"].as<std::string>(); if (final_stage == "code") { command_line_arguments.final_stage = FinalStage::CODE; } else if (final_stage == "ast") { command_line_arguments.final_stage = FinalStage::AST; } else if (final_stage == "ir") { command_line_arguments.final_stage = FinalStage::IR; } else { throw std::runtime_error( (format(R"(unknown final stage "%s")") % final_stage).str() ); } } if (arguments_map.count("script-file")) { command_line_arguments.script_file = arguments_map["script-file"].as<std::string>(); } else { throw std::runtime_error("script file not specified"); } if (arguments_map.count("script-arguments")) { command_line_arguments.script_arguments = arguments_map["script-arguments"].as<StringGroup>(); } return command_line_arguments; } } }
#include "process_command_line_arguments.h" #include <iostream> #include <boost/program_options.hpp> #include <boost/format.hpp> using namespace boost; using namespace boost::program_options; const auto POSITIONAL_ARGUMENT_SIGNLE_REPETITION = 1; const auto POSITIONAL_ARGUMENT_UNLIMITED_REPETITIONS = -1; namespace thewizardplusplus { namespace wizard_basic_3 { auto ProcessCommandLineArguments( const int number_of_arguments, char* arguments[] ) -> CommandLineArguments { auto interpreter_arguments_description = options_description("Options"); interpreter_arguments_description.add_options() ("version,v", "- show version;") ("help,h", "- show help;") ( "final-stage,s", value<std::string>(), R"(- set final stage (allowed: "code", "ast" and "ir");)" ) ("script-file", value<std::string>(), "- script file;") ( "script-arguments", value<StringGroup>()->composing(), "- script arguments." ); auto script_arguments_description = positional_options_description(); script_arguments_description.add( "script-file", POSITIONAL_ARGUMENT_SIGNLE_REPETITION ); script_arguments_description.add( "script-arguments", POSITIONAL_ARGUMENT_UNLIMITED_REPETITIONS ); auto arguments_map = variables_map(); store( command_line_parser(number_of_arguments, arguments) .options(interpreter_arguments_description) .positional(script_arguments_description) .run(), arguments_map ); notify(arguments_map); if (arguments_map.count("version")) { std::cout << "Wizard Basic 3 interpreter, v1.0\n" "(c) thewizardplusplus, 2014\n"; std::exit(EXIT_SUCCESS); } if (arguments_map.count("help")) { std::cout << "Usage: wb3i [options] <script-file> [<script-arguments>]\n" << interpreter_arguments_description; std::exit(EXIT_SUCCESS); } auto command_line_arguments = CommandLineArguments(); if (arguments_map.count("final-stage")) { const auto final_stage = arguments_map["final-stage"].as<std::string>(); if (final_stage == "code") { command_line_arguments.final_stage = FinalStage::CODE; } else if (final_stage == "ast") { command_line_arguments.final_stage = FinalStage::AST; } else if (final_stage == "ir") { command_line_arguments.final_stage = FinalStage::IR; } else { throw std::runtime_error( (format(R"(unknown final stage "%s")") % final_stage).str() ); } } if (arguments_map.count("script-file")) { command_line_arguments.script_file = arguments_map["script-file"].as<std::string>(); } else { throw std::runtime_error("script file not specified"); } if (arguments_map.count("script-arguments")) { command_line_arguments.script_arguments = arguments_map["script-arguments"].as<StringGroup>(); } return command_line_arguments; } } }
Correct of command line argument description.
Correct of command line argument description.
C++
mit
thewizardplusplus/wizard-basic-3,thewizardplusplus/wizard-basic-3
7f96eae10c91e45fc2ac7d9a47c88c4e5c2b824d
tutorial/lesson_01_basics.cpp
tutorial/lesson_01_basics.cpp
// Halide tutorial lesson 1. // This lesson demonstrates basic usage of Halide as a JIT compiler for imaging. // This lesson can be built by invoking the command: // make tutorial_lesson_01_basics // in a shell with the current directory at the top of the halide source tree. // Otherwise, see the platform-specific compiler invocations below. // On linux, you can compile and run it like so: // g++ lesson_01*.cpp -g -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_01 // LD_LIBRARY_PATH=../bin ./lesson_01 // On os x: // g++ lesson_01*.cpp -g -I ../include -L ../bin -lHalide -o lesson_01 // DYLD_LIBRARY_PATH=../bin ./lesson_01 // The only Halide header file you need is Halide.h. It includes all of Halide. #include "Halide.h" // We'll also include stdio for printf. #include <stdio.h> int main(int argc, char **argv) { // This program defines a single-stage imaging pipeline that // outputs a grayscale diagonal gradient. // A 'Func' object represents a pipeline stage. It's a pure // function that defines what value each pixel should have. You // can think of it as a computed image. Halide::Func gradient; // Var objects are names to use as variables in the definition of // a Func. They have no meaning by themselves. Halide::Var x, y; // We typically use Vars named 'x' and 'y' to correspond to the x // and y axes of an image, and we write them in that order. If // you're used to thinking of images as having rows and columns, // then x is the column index, and y is the row index. // Funcs are defined at any integer coordinate of its variables as // an Expr in terms of those variables and other functions. // Here, we'll define an Expr which has the value x + y. Vars have // appropriate operator overloading so that expressions like // 'x + y' become 'Expr' objects. Halide::Expr e = x + y; // Now we'll add a definition for the Func object. At pixel x, y, // the image will have the value of the Expr e. On the left hand // side we have the Func we're defining and some Vars. On the right // hand side we have some Expr object that uses those same Vars. gradient(x, y) = e; // This is the same as writing: // // gradient(x, y) = x + y; // // which is the more common form, but we are showing the // intermediate Expr here for completeness. // That line of code defined the Func, but it didn't actually // compute the output image yet. At this stage it's just Funcs, // Exprs, and Vars in memory, representing the structure of our // imaging pipeline. We're meta-programming. This C++ program is // constructing a Halide program in memory. Actually computing // pixel data comes next. // Now we 'realize' the Func, which JIT compiles some code that // implements the pipeline we've defined, and then runs it. We // also need to tell Halide the domain over which to evaluate the // Func, which determines the range of x and y above, and the // resolution of the output image. Halide.h also provides a basic // templatized Image type we can use. We'll make an 800 x 600 // image. Halide::Image<int32_t> output = gradient.realize(800, 600); // Halide does type inference for you. Var objects represent // 32-bit integers, so the Expr object 'x + y' also represents a // 32-bit integer, and so 'gradient' defines a 32-bit image, and // so we got a 32-bit signed integer image out when we call // 'realize'. Halide types and type-casting rules are equivalent // to C. // Let's check everything worked, and we got the output we were // expecting: for (int j = 0; j < output.height(); j++) { for (int i = 0; i < output.width(); i++) { // We can access a pixel of an Image object using similar // syntax to defining and using functions. if (output(i, j) != i + j) { printf("Something went wrong!\n" "Pixel %d, %d was supposed to be %d, but instead it's %d\n", i, j, i+j, output(i, j)); return -1; } } } // Everything worked! We defined a Func, then called 'realize' on // it to generate and run machine code that produced an Image. printf("Success!\n"); return 0; }
// Halide tutorial lesson 1. // This lesson demonstrates basic usage of Halide as a JIT compiler for imaging. // This lesson can be built by invoking the command: // make tutorial_lesson_01_basics // in a shell with the current directory at the top of the halide source tree. // Otherwise, see the platform-specific compiler invocations below. // On linux, you can compile and run it like so: // g++ lesson_01*.cpp -g -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_01 -std=c++1 // LD_LIBRARY_PATH=../bin ./lesson_01 // On os x: // g++ lesson_01*.cpp -g -I ../include -L ../bin -lHalide -o lesson_01 // DYLD_LIBRARY_PATH=../bin ./lesson_01 // The only Halide header file you need is Halide.h. It includes all of Halide. #include "Halide.h" // We'll also include stdio for printf. #include <stdio.h> int main(int argc, char **argv) { // This program defines a single-stage imaging pipeline that // outputs a grayscale diagonal gradient. // A 'Func' object represents a pipeline stage. It's a pure // function that defines what value each pixel should have. You // can think of it as a computed image. Halide::Func gradient; // Var objects are names to use as variables in the definition of // a Func. They have no meaning by themselves. Halide::Var x, y; // We typically use Vars named 'x' and 'y' to correspond to the x // and y axes of an image, and we write them in that order. If // you're used to thinking of images as having rows and columns, // then x is the column index, and y is the row index. // Funcs are defined at any integer coordinate of its variables as // an Expr in terms of those variables and other functions. // Here, we'll define an Expr which has the value x + y. Vars have // appropriate operator overloading so that expressions like // 'x + y' become 'Expr' objects. Halide::Expr e = x + y; // Now we'll add a definition for the Func object. At pixel x, y, // the image will have the value of the Expr e. On the left hand // side we have the Func we're defining and some Vars. On the right // hand side we have some Expr object that uses those same Vars. gradient(x, y) = e; // This is the same as writing: // // gradient(x, y) = x + y; // // which is the more common form, but we are showing the // intermediate Expr here for completeness. // That line of code defined the Func, but it didn't actually // compute the output image yet. At this stage it's just Funcs, // Exprs, and Vars in memory, representing the structure of our // imaging pipeline. We're meta-programming. This C++ program is // constructing a Halide program in memory. Actually computing // pixel data comes next. // Now we 'realize' the Func, which JIT compiles some code that // implements the pipeline we've defined, and then runs it. We // also need to tell Halide the domain over which to evaluate the // Func, which determines the range of x and y above, and the // resolution of the output image. Halide.h also provides a basic // templatized Image type we can use. We'll make an 800 x 600 // image. Halide::Image<int32_t> output = gradient.realize(800, 600); // Halide does type inference for you. Var objects represent // 32-bit integers, so the Expr object 'x + y' also represents a // 32-bit integer, and so 'gradient' defines a 32-bit image, and // so we got a 32-bit signed integer image out when we call // 'realize'. Halide types and type-casting rules are equivalent // to C. // Let's check everything worked, and we got the output we were // expecting: for (int j = 0; j < output.height(); j++) { for (int i = 0; i < output.width(); i++) { // We can access a pixel of an Image object using similar // syntax to defining and using functions. if (output(i, j) != i + j) { printf("Something went wrong!\n" "Pixel %d, %d was supposed to be %d, but instead it's %d\n", i, j, i+j, output(i, j)); return -1; } } } // Everything worked! We defined a Func, then called 'realize' on // it to generate and run machine code that produced an Image. printf("Success!\n"); return 0; }
Update lesson_01_basics.cpp
Update lesson_01_basics.cpp Fix compile command on linux
C++
mit
dougkwan/Halide,psuriana/Halide,dougkwan/Halide,adasworks/Halide,dan-tull/Halide,ayanazmat/Halide,kgnk/Halide,ronen/Halide,fengzhyuan/Halide,fengzhyuan/Halide,adasworks/Halide,damienfir/Halide,damienfir/Halide,smxlong/Halide,dan-tull/Halide,psuriana/Halide,lglucin/Halide,aam/Halide,tdenniston/Halide,lglucin/Halide,adasworks/Halide,delcypher/Halide,psuriana/Halide,mcanthony/Halide,dougkwan/Halide,myrtleTree33/Halide,dan-tull/Halide,kgnk/Halide,lglucin/Halide,psuriana/Halide,kenkuang1213/Halide,jiawen/Halide,aam/Halide,ayanazmat/Halide,mcanthony/Halide,dan-tull/Halide,jiawen/Halide,kenkuang1213/Halide,rodrigob/Halide,smxlong/Halide,smxlong/Halide,rodrigob/Halide,ayanazmat/Halide,fengzhyuan/Halide,myrtleTree33/Halide,damienfir/Halide,myrtleTree33/Halide,lglucin/Halide,kenkuang1213/Halide,damienfir/Halide,rodrigob/Halide,dougkwan/Halide,rodrigob/Halide,adasworks/Halide,tdenniston/Halide,fengzhyuan/Halide,delcypher/Halide,delcypher/Halide,dougkwan/Halide,smxlong/Halide,adasworks/Halide,lglucin/Halide,ronen/Halide,tdenniston/Halide,ronen/Halide,delcypher/Halide,mcanthony/Halide,psuriana/Halide,damienfir/Halide,aam/Halide,dan-tull/Halide,aam/Halide,kenkuang1213/Halide,ronen/Halide,kgnk/Halide,tdenniston/Halide,delcypher/Halide,ronen/Halide,kenkuang1213/Halide,kgnk/Halide,tdenniston/Halide,jiawen/Halide,kenkuang1213/Halide,tdenniston/Halide,psuriana/Halide,jiawen/Halide,myrtleTree33/Halide,mcanthony/Halide,rodrigob/Halide,kgnk/Halide,kenkuang1213/Halide,delcypher/Halide,myrtleTree33/Halide,fengzhyuan/Halide,smxlong/Halide,jiawen/Halide,dougkwan/Halide,myrtleTree33/Halide,damienfir/Halide,rodrigob/Halide,ronen/Halide,jiawen/Halide,mcanthony/Halide,ronen/Halide,aam/Halide,mcanthony/Halide,myrtleTree33/Halide,ayanazmat/Halide,psuriana/Halide,damienfir/Halide,delcypher/Halide,dougkwan/Halide,adasworks/Halide,damienfir/Halide,kgnk/Halide,fengzhyuan/Halide,rodrigob/Halide,ayanazmat/Halide,smxlong/Halide,delcypher/Halide,mcanthony/Halide,ronen/Halide,smxlong/Halide,fengzhyuan/Halide,lglucin/Halide,jiawen/Halide,dan-tull/Halide,smxlong/Halide,myrtleTree33/Halide,kgnk/Halide,adasworks/Halide,dan-tull/Halide,adasworks/Halide,rodrigob/Halide,ayanazmat/Halide,kgnk/Halide,aam/Halide,lglucin/Halide,dan-tull/Halide,tdenniston/Halide,fengzhyuan/Halide,dougkwan/Halide,tdenniston/Halide,kenkuang1213/Halide,ayanazmat/Halide,ayanazmat/Halide,aam/Halide,mcanthony/Halide
81c5a10a8db5530eb028c85887f0cc73d16c04d3
connectivity/source/drivers/odbcbase/ODriver.cxx
connectivity/source/drivers/odbcbase/ODriver.cxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include "odbc/ODriver.hxx" #include "odbc/OConnection.hxx" #include "odbc/OFunctions.hxx" #include "odbc/OTools.hxx" #include "connectivity/dbexception.hxx" #include "resource/common_res.hrc" #include "resource/sharedresources.hxx" using namespace connectivity::odbc; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::sdbc; // -------------------------------------------------------------------------------- ODBCDriver::ODBCDriver(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) :ODriver_BASE(m_aMutex) ,m_xORB(_rxFactory) ,m_pDriverHandle(SQL_NULL_HANDLE) { } // -------------------------------------------------------------------------------- void ODBCDriver::disposing() { ::osl::MutexGuard aGuard(m_aMutex); for (OWeakRefArray::iterator i = m_xConnections.begin(); m_xConnections.end() != i; ++i) { Reference< XComponent > xComp(i->get(), UNO_QUERY); if (xComp.is()) xComp->dispose(); } m_xConnections.clear(); ODriver_BASE::disposing(); } // static ServiceInfo //------------------------------------------------------------------------------ rtl::OUString ODBCDriver::getImplementationName_Static( ) throw(RuntimeException) { return rtl::OUString("com.sun.star.comp.sdbc.ODBCDriver"); // this name is referenced in the configuration and in the odbc.xml // Please take care when changing it. } typedef Sequence< ::rtl::OUString > SS; //------------------------------------------------------------------------------ SS ODBCDriver::getSupportedServiceNames_Static( ) throw (RuntimeException) { SS aSNS( 1 ); aSNS[0] = ::rtl::OUString("com.sun.star.sdbc.Driver"); return aSNS; } //------------------------------------------------------------------ ::rtl::OUString SAL_CALL ODBCDriver::getImplementationName( ) throw(RuntimeException) { return getImplementationName_Static(); } //------------------------------------------------------------------ sal_Bool SAL_CALL ODBCDriver::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException) { SS aSupported(getSupportedServiceNames()); const ::rtl::OUString* pSupported = aSupported.getConstArray(); const ::rtl::OUString* pEnd = pSupported + aSupported.getLength(); for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported) ; return pSupported != pEnd; } //------------------------------------------------------------------ SS SAL_CALL ODBCDriver::getSupportedServiceNames( ) throw(RuntimeException) { return getSupportedServiceNames_Static(); } // -------------------------------------------------------------------------------- Reference< XConnection > SAL_CALL ODBCDriver::connect( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException) { if ( ! acceptsURL(url) ) return NULL; if(!m_pDriverHandle) { ::rtl::OUString aPath; if(!EnvironmentHandle(aPath)) throw SQLException(aPath,*this,::rtl::OUString(),1000,Any()); } OConnection* pCon = new OConnection(m_pDriverHandle,this); Reference< XConnection > xCon = pCon; pCon->Construct(url,info); m_xConnections.push_back(WeakReferenceHelper(*pCon)); return xCon; } // -------------------------------------------------------------------------------- sal_Bool SAL_CALL ODBCDriver::acceptsURL( const ::rtl::OUString& url ) throw(SQLException, RuntimeException) { return (!url.compareTo(::rtl::OUString("sdbc:odbc:"),10)); } // -------------------------------------------------------------------------------- Sequence< DriverPropertyInfo > SAL_CALL ODBCDriver::getPropertyInfo( const ::rtl::OUString& url, const Sequence< PropertyValue >& /*info*/ ) throw(SQLException, RuntimeException) { if ( acceptsURL(url) ) { ::std::vector< DriverPropertyInfo > aDriverInfo; Sequence< ::rtl::OUString > aBooleanValues(2); aBooleanValues[0] = ::rtl::OUString( "false" ); aBooleanValues[1] = ::rtl::OUString( "true" ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("CharSet") ,::rtl::OUString("CharSet of the database.") ,sal_False ,::rtl::OUString() ,Sequence< ::rtl::OUString >()) ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("UseCatalog") ,::rtl::OUString("Use catalog for file-based databases.") ,sal_False ,::rtl::OUString( "false" ) ,aBooleanValues) ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("SystemDriverSettings") ,::rtl::OUString("Driver settings.") ,sal_False ,::rtl::OUString() ,Sequence< ::rtl::OUString >()) ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("ParameterNameSubstitution") ,::rtl::OUString("Change named parameters with '?'.") ,sal_False ,::rtl::OUString( "false" ) ,aBooleanValues) ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("IgnoreDriverPrivileges") ,::rtl::OUString("Ignore the privileges from the database driver.") ,sal_False ,::rtl::OUString( "false" ) ,aBooleanValues) ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("IsAutoRetrievingEnabled") ,::rtl::OUString("Retrieve generated values.") ,sal_False ,::rtl::OUString( "false" ) ,aBooleanValues) ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("AutoRetrievingStatement") ,::rtl::OUString("Auto-increment statement.") ,sal_False ,::rtl::OUString() ,Sequence< ::rtl::OUString >()) ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("GenerateASBeforeCorrelationName") ,::rtl::OUString("Generate AS before table correlation names.") ,sal_False ,::rtl::OUString( "true" ) ,aBooleanValues) ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("EscapeDateTime") ,::rtl::OUString("Escape date time format.") ,sal_False ,::rtl::OUString( "true" ) ,aBooleanValues) ); return Sequence< DriverPropertyInfo >(&aDriverInfo[0],aDriverInfo.size()); } ::connectivity::SharedResources aResources; const ::rtl::OUString sMessage = aResources.getResourceString(STR_URI_SYNTAX_ERROR); ::dbtools::throwGenericSQLException(sMessage ,*this); return Sequence< DriverPropertyInfo >(); } // -------------------------------------------------------------------------------- sal_Int32 SAL_CALL ODBCDriver::getMajorVersion( ) throw(RuntimeException) { return 1; } // -------------------------------------------------------------------------------- sal_Int32 SAL_CALL ODBCDriver::getMinorVersion( ) throw(RuntimeException) { return 0; } // -------------------------------------------------------------------------------- //----------------------------------------------------------------------------- /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include "odbc/ODriver.hxx" #include "odbc/OConnection.hxx" #include "odbc/OFunctions.hxx" #include "odbc/OTools.hxx" #include "connectivity/dbexception.hxx" #include "resource/common_res.hrc" #include "resource/sharedresources.hxx" using namespace connectivity::odbc; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::sdbc; // -------------------------------------------------------------------------------- ODBCDriver::ODBCDriver(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) :ODriver_BASE(m_aMutex) ,m_xORB(_rxFactory) ,m_pDriverHandle(SQL_NULL_HANDLE) { } // -------------------------------------------------------------------------------- void ODBCDriver::disposing() { ::osl::MutexGuard aGuard(m_aMutex); for (OWeakRefArray::iterator i = m_xConnections.begin(); m_xConnections.end() != i; ++i) { Reference< XComponent > xComp(i->get(), UNO_QUERY); if (xComp.is()) xComp->dispose(); } m_xConnections.clear(); ODriver_BASE::disposing(); } // static ServiceInfo //------------------------------------------------------------------------------ rtl::OUString ODBCDriver::getImplementationName_Static( ) throw(RuntimeException) { return rtl::OUString("com.sun.star.comp.sdbc.ODBCDriver"); // this name is referenced in the configuration and in the odbc.xml // Please take care when changing it. } //------------------------------------------------------------------------------ Sequence< ::rtl::OUString > ODBCDriver::getSupportedServiceNames_Static( ) throw (RuntimeException) { Sequence< ::rtl::OUString > aSNS( 1 ); aSNS[0] = ::rtl::OUString("com.sun.star.sdbc.Driver"); return aSNS; } //------------------------------------------------------------------ ::rtl::OUString SAL_CALL ODBCDriver::getImplementationName( ) throw(RuntimeException) { return getImplementationName_Static(); } //------------------------------------------------------------------ sal_Bool SAL_CALL ODBCDriver::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException) { Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames()); const ::rtl::OUString* pSupported = aSupported.getConstArray(); const ::rtl::OUString* pEnd = pSupported + aSupported.getLength(); for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported) ; return pSupported != pEnd; } //------------------------------------------------------------------ Sequence< ::rtl::OUString > SAL_CALL ODBCDriver::getSupportedServiceNames( ) throw(RuntimeException) { return getSupportedServiceNames_Static(); } // -------------------------------------------------------------------------------- Reference< XConnection > SAL_CALL ODBCDriver::connect( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException) { if ( ! acceptsURL(url) ) return NULL; if(!m_pDriverHandle) { ::rtl::OUString aPath; if(!EnvironmentHandle(aPath)) throw SQLException(aPath,*this,::rtl::OUString(),1000,Any()); } OConnection* pCon = new OConnection(m_pDriverHandle,this); Reference< XConnection > xCon = pCon; pCon->Construct(url,info); m_xConnections.push_back(WeakReferenceHelper(*pCon)); return xCon; } // -------------------------------------------------------------------------------- sal_Bool SAL_CALL ODBCDriver::acceptsURL( const ::rtl::OUString& url ) throw(SQLException, RuntimeException) { return (!url.compareTo(::rtl::OUString("sdbc:odbc:"),10)); } // -------------------------------------------------------------------------------- Sequence< DriverPropertyInfo > SAL_CALL ODBCDriver::getPropertyInfo( const ::rtl::OUString& url, const Sequence< PropertyValue >& /*info*/ ) throw(SQLException, RuntimeException) { if ( acceptsURL(url) ) { ::std::vector< DriverPropertyInfo > aDriverInfo; Sequence< ::rtl::OUString > aBooleanValues(2); aBooleanValues[0] = ::rtl::OUString( "false" ); aBooleanValues[1] = ::rtl::OUString( "true" ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("CharSet") ,::rtl::OUString("CharSet of the database.") ,sal_False ,::rtl::OUString() ,Sequence< ::rtl::OUString >()) ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("UseCatalog") ,::rtl::OUString("Use catalog for file-based databases.") ,sal_False ,::rtl::OUString( "false" ) ,aBooleanValues) ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("SystemDriverSettings") ,::rtl::OUString("Driver settings.") ,sal_False ,::rtl::OUString() ,Sequence< ::rtl::OUString >()) ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("ParameterNameSubstitution") ,::rtl::OUString("Change named parameters with '?'.") ,sal_False ,::rtl::OUString( "false" ) ,aBooleanValues) ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("IgnoreDriverPrivileges") ,::rtl::OUString("Ignore the privileges from the database driver.") ,sal_False ,::rtl::OUString( "false" ) ,aBooleanValues) ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("IsAutoRetrievingEnabled") ,::rtl::OUString("Retrieve generated values.") ,sal_False ,::rtl::OUString( "false" ) ,aBooleanValues) ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("AutoRetrievingStatement") ,::rtl::OUString("Auto-increment statement.") ,sal_False ,::rtl::OUString() ,Sequence< ::rtl::OUString >()) ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("GenerateASBeforeCorrelationName") ,::rtl::OUString("Generate AS before table correlation names.") ,sal_False ,::rtl::OUString( "true" ) ,aBooleanValues) ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("EscapeDateTime") ,::rtl::OUString("Escape date time format.") ,sal_False ,::rtl::OUString( "true" ) ,aBooleanValues) ); return Sequence< DriverPropertyInfo >(&aDriverInfo[0],aDriverInfo.size()); } ::connectivity::SharedResources aResources; const ::rtl::OUString sMessage = aResources.getResourceString(STR_URI_SYNTAX_ERROR); ::dbtools::throwGenericSQLException(sMessage ,*this); return Sequence< DriverPropertyInfo >(); } // -------------------------------------------------------------------------------- sal_Int32 SAL_CALL ODBCDriver::getMajorVersion( ) throw(RuntimeException) { return 1; } // -------------------------------------------------------------------------------- sal_Int32 SAL_CALL ODBCDriver::getMinorVersion( ) throw(RuntimeException) { return 0; } // -------------------------------------------------------------------------------- //----------------------------------------------------------------------------- /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
Remove conflicting typedef
Remove conflicting typedef Barely used typedef produced compilation error on Solaris, due to already defined type 'SS'. Change-Id: I2d1d563d8c4818a4afe9656cc4a62ba1bbaaafd2
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
d56de849f8f328d8f3eaa7bc104225debb09c956
rcb_generator.hpp
rcb_generator.hpp
/*----------------------------------------------------------------------------------*\ | | | rcb_generator.hpp | | | | Copyright (c) 2016 Richard Cookman | | | | 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. | | | \*----------------------------------------------------------------------------------*/ #pragma once namespace rcbg { template<typename U> inline bool get_bit(U val, unsigned pos) { return val & ((U)1 << pos); } template<typename U> inline U set_bit(U val, unsigned pos, bool to) { return (val & ~((U)1 << pos)) | ((U)to << pos); } //the random cycle bit generator - random number generator template<typename T, unsigned int bit_pos_left = ((sizeof(T) * 8) / 3) + 1, unsigned int bit_pos_start = bit_pos_left * 2> class rcb_generator { private: T val; T last; T cnt = 1; //only first two flags used (1 << 1) is "left" (1 << 0) is start char flags = 0; inline static T shift_transform(T val, int i, bool& start_bit) { val ^= (T)start_bit << i; start_bit ^= get_bit(val, i); return val; } static T generate(T val, bool left, bool start_bit) { if(left) for(int i = 0; i < (int)(sizeof(T) * 8); ++i) val = shift_transform(val, i, start_bit); else for(int i = (sizeof(T) * 8) - 1; i > -1; --i) val = shift_transform(val, i, start_bit); return val; } T generate(T inval) { //set the flags left and start bit bool left = (get_bit(val, bit_pos_left) ^ get_bit(flags, 1) ^ true); bool start_bit = (get_bit(val, bit_pos_start) ^ get_bit(flags, 0) ^ true); flags = set_bit(flags, 1, left); flags = set_bit(flags, 0, start_bit); T tmpVal = inval; T tfrm = generate(inval, left, start_bit); inval = tfrm; last = tfrm ^ tmpVal ^ ~last; return last; } public: rcb_generator(T rnd) : val(rnd + 10), last(~(rnd - 10)) {} inline T rand() { T tmp_cnt = cnt++; if(cnt == 0) ++cnt; return val = (((val = generate(val)) << 1) * (generate(tmp_cnt) << 1)) ^ generate(val); } }; }
/*----------------------------------------------------------------------------------*\ | | | rcb_generator.hpp | | | | Copyright (c) 2016 Richard Cookman | | | | 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. | | | \*----------------------------------------------------------------------------------*/ #pragma once namespace rcbg { template<typename U> inline bool get_bit(U val, unsigned pos) { return val & ((U)1 << pos); } template<typename U> inline U set_bit(U val, unsigned pos, bool to) { return (val & ~((U)1 << pos)) | ((U)to << pos); } //the random cycle bit generator - random number generator template<typename T, unsigned int bit_pos_left = ((sizeof(T) * 8) / 3) + 1, unsigned int bit_pos_start = bit_pos_left * 2> class rcb_generator { private: T val; T last; T cnt = 1; //only first two flags used (1 << 1) is "left" (1 << 0) is start char flags = 0; inline static T shift_transform(T val, int i, bool& start_bit) { val ^= (T)start_bit << i; start_bit ^= get_bit(val, i); return val; } static T generate(T val, bool left, bool start_bit) { if(left) for(int i = 0; i < (int)(sizeof(T) * 8); ++i) val = shift_transform(val, i, start_bit); else for(int i = (sizeof(T) * 8) - 1; i > -1; --i) val = shift_transform(val, i, start_bit); return val; } T generate(T inval) { //set the flags left and start bit bool left = (get_bit(val, bit_pos_left) ^ get_bit(flags, 1) ^ true); bool start_bit = (get_bit(val, bit_pos_start) ^ get_bit(flags, 0) ^ true); flags = set_bit(flags, 1, left); flags = set_bit(flags, 0, start_bit); T tmpVal = inval; T tfrm = generate(inval, left, start_bit); last = tfrm ^ tmpVal ^ ~last; return last; } public: rcb_generator(T rnd) : val(rnd + 10), last(~(rnd - 10)) {} inline T rand() { T tmp_cnt = cnt++; if(cnt == 0) ++cnt; return val = (((val = generate(val)) << 1) * (generate(tmp_cnt) << 1)) ^ generate(val); } }; }
remove unneeded assignment
remove unneeded assignment
C++
mit
ceorron/cycle-bit-random-number-generator,ceorron/cycle-bit-random-number-generator
03b405007c67943d6b10a912e5209dcff21e4ded
ui/aura/desktop_host_linux.cc
ui/aura/desktop_host_linux.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/aura/desktop_host.h" #include <X11/cursorfont.h> #include <X11/Xlib.h> // Get rid of a macro from Xlib.h that conflicts with Aura's RootWindow class. #undef RootWindow #include <algorithm> #include "base/message_loop.h" #include "base/message_pump_x.h" #include "ui/aura/cursor.h" #include "ui/aura/desktop.h" #include "ui/aura/event.h" #include "ui/base/touch/touch_factory.h" #include "ui/base/x/x11_util.h" using std::max; using std::min; namespace aura { namespace { // Returns X font cursor shape from an Aura cursor. int CursorShapeFromNative(gfx::NativeCursor native_cursor) { switch (native_cursor) { case aura::kCursorNull: return XC_left_ptr; case aura::kCursorPointer: return XC_left_ptr; case aura::kCursorCross: return XC_crosshair; case aura::kCursorHand: return XC_hand2; case aura::kCursorIBeam: return XC_xterm; case aura::kCursorWait: return XC_watch; case aura::kCursorHelp: return XC_question_arrow; case aura::kCursorEastResize: return XC_right_side; case aura::kCursorNorthResize: return XC_top_side; case aura::kCursorNorthEastResize: return XC_top_right_corner; case aura::kCursorNorthWestResize: return XC_top_left_corner; case aura::kCursorSouthResize: return XC_bottom_side; case aura::kCursorSouthEastResize: return XC_bottom_right_corner; case aura::kCursorSouthWestResize: return XC_bottom_left_corner; case aura::kCursorWestResize: return XC_left_side; case aura::kCursorNorthSouthResize: return XC_sb_v_double_arrow; case aura::kCursorEastWestResize: return XC_sb_h_double_arrow; case aura::kCursorNorthEastSouthWestResize: case aura::kCursorNorthWestSouthEastResize: // There isn't really a useful cursor available for these. NOTIMPLEMENTED(); return XC_left_ptr; case aura::kCursorColumnResize: return XC_sb_h_double_arrow; case aura::kCursorRowResize: return XC_sb_v_double_arrow; case aura::kCursorMiddlePanning: return XC_fleur; case aura::kCursorEastPanning: return XC_sb_right_arrow; case aura::kCursorNorthPanning: return XC_sb_up_arrow; case aura::kCursorNorthEastPanning: return XC_top_right_corner; case aura::kCursorNorthWestPanning: return XC_top_left_corner; case aura::kCursorSouthPanning: return XC_sb_down_arrow; case aura::kCursorSouthEastPanning: return XC_bottom_right_corner; case aura::kCursorSouthWestPanning: return XC_bottom_left_corner; case aura::kCursorWestPanning: return XC_sb_left_arrow; case aura::kCursorMove: return XC_fleur; case aura::kCursorVerticalText: case aura::kCursorCell: case aura::kCursorContextMenu: case aura::kCursorAlias: case aura::kCursorProgress: case aura::kCursorNoDrop: case aura::kCursorCopy: case aura::kCursorNone: case aura::kCursorNotAllowed: case aura::kCursorZoomIn: case aura::kCursorZoomOut: case aura::kCursorGrab: case aura::kCursorGrabbing: case aura::kCursorCustom: // TODO(jamescook): Need cursors for these. NOTIMPLEMENTED(); return XC_left_ptr; } NOTREACHED(); return XC_left_ptr; } class DesktopHostLinux : public DesktopHost { public: explicit DesktopHostLinux(const gfx::Rect& bounds); virtual ~DesktopHostLinux(); private: // base::MessageLoop::Dispatcher Override. virtual DispatchStatus Dispatch(XEvent* xev) OVERRIDE; // DesktopHost Overrides. virtual void SetDesktop(Desktop* desktop) OVERRIDE; virtual gfx::AcceleratedWidget GetAcceleratedWidget() OVERRIDE; virtual void Show() OVERRIDE; virtual gfx::Size GetSize() const OVERRIDE; virtual void SetSize(const gfx::Size& size) OVERRIDE; virtual void SetCursor(gfx::NativeCursor cursor_type) OVERRIDE; virtual gfx::Point QueryMouseLocation() OVERRIDE; Desktop* desktop_; // The display and the native X window hosting the desktop. Display* xdisplay_; ::Window xwindow_; // Current Aura cursor. gfx::NativeCursor current_cursor_; // The size of |xwindow_|. gfx::Rect bounds_; DISALLOW_COPY_AND_ASSIGN(DesktopHostLinux); }; DesktopHostLinux::DesktopHostLinux(const gfx::Rect& bounds) : desktop_(NULL), xdisplay_(NULL), xwindow_(0), current_cursor_(aura::kCursorNull), bounds_(bounds) { // This assumes that the message-pump creates and owns the display. xdisplay_ = base::MessagePumpX::GetDefaultXDisplay(); xwindow_ = XCreateSimpleWindow(xdisplay_, DefaultRootWindow(xdisplay_), bounds.x(), bounds.y(), bounds.width(), bounds.height(), 0, 0, 0); long event_mask = ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask | ExposureMask | VisibilityChangeMask | StructureNotifyMask | PropertyChangeMask | PointerMotionMask; XSelectInput(xdisplay_, xwindow_, event_mask); XFlush(xdisplay_); if (base::MessagePumpForUI::HasXInput2()) ui::TouchFactory::GetInstance()->SetupXI2ForXWindow(xwindow_); } DesktopHostLinux::~DesktopHostLinux() { XDestroyWindow(xdisplay_, xwindow_); } base::MessagePumpDispatcher::DispatchStatus DesktopHostLinux::Dispatch( XEvent* xev) { bool handled = false; switch (xev->type) { case Expose: desktop_->Draw(); handled = true; break; case KeyPress: { KeyEvent keydown_event(xev, false); handled = desktop_->OnKeyEvent(keydown_event); KeyEvent char_event(xev, true); handled |= desktop_->OnKeyEvent(char_event); break; } case KeyRelease: { KeyEvent keyup_event(xev, false); handled = desktop_->OnKeyEvent(keyup_event); break; } case ButtonPress: case ButtonRelease: { MouseEvent mouseev(xev); handled = desktop_->OnMouseEvent(mouseev); break; } case MotionNotify: { // Discard all but the most recent motion event that targets the same // window with unchanged state. XEvent last_event; while (XPending(xev->xany.display)) { XEvent next_event; XPeekEvent(xev->xany.display, &next_event); if (next_event.type == MotionNotify && next_event.xmotion.window == xev->xmotion.window && next_event.xmotion.subwindow == xev->xmotion.subwindow && next_event.xmotion.state == xev->xmotion.state) { XNextEvent(xev->xany.display, &last_event); xev = &last_event; } else { break; } } MouseEvent mouseev(xev); handled = desktop_->OnMouseEvent(mouseev); break; } case ConfigureNotify: { DCHECK_EQ(xdisplay_, xev->xconfigure.display); DCHECK_EQ(xwindow_, xev->xconfigure.window); DCHECK_EQ(xwindow_, xev->xconfigure.event); // It's possible that the X window may be resized by some other means than // from within aura (e.g. the X window manager can change the size). Make // sure the desktop size is maintained properly. gfx::Size size(xev->xconfigure.width, xev->xconfigure.height); if (bounds_.size() != size) bounds_.set_size(size); desktop_->OnHostResized(size); handled = true; break; } case GenericEvent: { ui::TouchFactory* factory = ui::TouchFactory::GetInstance(); if (!factory->ShouldProcessXI2Event(xev)) break; ui::EventType type = ui::EventTypeFromNative(xev); switch (type) { case ui::ET_TOUCH_PRESSED: case ui::ET_TOUCH_RELEASED: case ui::ET_TOUCH_MOVED: { TouchEvent touchev(xev); handled = desktop_->OnTouchEvent(touchev); break; } case ui::ET_MOUSE_PRESSED: case ui::ET_MOUSE_RELEASED: case ui::ET_MOUSE_MOVED: case ui::ET_MOUSE_DRAGGED: case ui::ET_MOUSEWHEEL: case ui::ET_MOUSE_ENTERED: case ui::ET_MOUSE_EXITED: { MouseEvent mouseev(xev); handled = desktop_->OnMouseEvent(mouseev); break; } case ui::ET_UNKNOWN: handled = false; break; default: NOTREACHED(); } } } return handled ? EVENT_PROCESSED : EVENT_IGNORED; } void DesktopHostLinux::SetDesktop(Desktop* desktop) { desktop_ = desktop; } gfx::AcceleratedWidget DesktopHostLinux::GetAcceleratedWidget() { return xwindow_; } void DesktopHostLinux::Show() { XMapWindow(xdisplay_, xwindow_); XFlush(xdisplay_); } gfx::Size DesktopHostLinux::GetSize() const { return bounds_.size(); } void DesktopHostLinux::SetSize(const gfx::Size& size) { if (bounds_.size() == size) return; bounds_.set_size(size); XResizeWindow(xdisplay_, xwindow_, size.width(), size.height()); } void DesktopHostLinux::SetCursor(gfx::NativeCursor cursor) { if (current_cursor_ == cursor) return; current_cursor_ = cursor; // Custom web cursors are handled directly. if (cursor == kCursorCustom) return; int cursor_shape = CursorShapeFromNative(cursor); ::Cursor xcursor = ui::GetXCursor(cursor_shape); XDefineCursor(xdisplay_, xwindow_, xcursor); } gfx::Point DesktopHostLinux::QueryMouseLocation() { ::Window root_return, child_return; int root_x_return, root_y_return, win_x_return, win_y_return; unsigned int mask_return; XQueryPointer(xdisplay_, xwindow_, &root_return, &child_return, &root_x_return, &root_y_return, &win_x_return, &win_y_return, &mask_return); return gfx::Point(max(0, min(bounds_.width(), win_x_return)), max(0, min(bounds_.height(), win_y_return))); } } // namespace // static DesktopHost* DesktopHost::Create(const gfx::Rect& bounds) { return new DesktopHostLinux(bounds); } } // namespace aura
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/aura/desktop_host.h" #include <X11/cursorfont.h> #include <X11/Xlib.h> // Get rid of a macro from Xlib.h that conflicts with Aura's RootWindow class. #undef RootWindow #include <algorithm> #include "base/message_loop.h" #include "base/message_pump_x.h" #include "ui/aura/cursor.h" #include "ui/aura/desktop.h" #include "ui/aura/event.h" #include "ui/base/touch/touch_factory.h" #include "ui/base/x/x11_util.h" #include <X11/cursorfont.h> #include <X11/extensions/XInput2.h> #include <X11/Xlib.h> using std::max; using std::min; namespace aura { namespace { // Returns X font cursor shape from an Aura cursor. int CursorShapeFromNative(gfx::NativeCursor native_cursor) { switch (native_cursor) { case aura::kCursorNull: return XC_left_ptr; case aura::kCursorPointer: return XC_left_ptr; case aura::kCursorCross: return XC_crosshair; case aura::kCursorHand: return XC_hand2; case aura::kCursorIBeam: return XC_xterm; case aura::kCursorWait: return XC_watch; case aura::kCursorHelp: return XC_question_arrow; case aura::kCursorEastResize: return XC_right_side; case aura::kCursorNorthResize: return XC_top_side; case aura::kCursorNorthEastResize: return XC_top_right_corner; case aura::kCursorNorthWestResize: return XC_top_left_corner; case aura::kCursorSouthResize: return XC_bottom_side; case aura::kCursorSouthEastResize: return XC_bottom_right_corner; case aura::kCursorSouthWestResize: return XC_bottom_left_corner; case aura::kCursorWestResize: return XC_left_side; case aura::kCursorNorthSouthResize: return XC_sb_v_double_arrow; case aura::kCursorEastWestResize: return XC_sb_h_double_arrow; case aura::kCursorNorthEastSouthWestResize: case aura::kCursorNorthWestSouthEastResize: // There isn't really a useful cursor available for these. NOTIMPLEMENTED(); return XC_left_ptr; case aura::kCursorColumnResize: return XC_sb_h_double_arrow; case aura::kCursorRowResize: return XC_sb_v_double_arrow; case aura::kCursorMiddlePanning: return XC_fleur; case aura::kCursorEastPanning: return XC_sb_right_arrow; case aura::kCursorNorthPanning: return XC_sb_up_arrow; case aura::kCursorNorthEastPanning: return XC_top_right_corner; case aura::kCursorNorthWestPanning: return XC_top_left_corner; case aura::kCursorSouthPanning: return XC_sb_down_arrow; case aura::kCursorSouthEastPanning: return XC_bottom_right_corner; case aura::kCursorSouthWestPanning: return XC_bottom_left_corner; case aura::kCursorWestPanning: return XC_sb_left_arrow; case aura::kCursorMove: return XC_fleur; case aura::kCursorVerticalText: case aura::kCursorCell: case aura::kCursorContextMenu: case aura::kCursorAlias: case aura::kCursorProgress: case aura::kCursorNoDrop: case aura::kCursorCopy: case aura::kCursorNone: case aura::kCursorNotAllowed: case aura::kCursorZoomIn: case aura::kCursorZoomOut: case aura::kCursorGrab: case aura::kCursorGrabbing: case aura::kCursorCustom: // TODO(jamescook): Need cursors for these. NOTIMPLEMENTED(); return XC_left_ptr; } NOTREACHED(); return XC_left_ptr; } // Coalesce all pending motion events that are at the top of the queue, and // return the number eliminated, storing the last one in |last_event|. int CoalescePendingXIMotionEvents(const XEvent* xev, XEvent* last_event) { XIDeviceEvent* xievent = static_cast<XIDeviceEvent*>(xev->xcookie.data); int num_coalesed = 0; Display* display = xev->xany.display; while (XPending(display)) { XEvent next_event; XPeekEvent(display, &next_event); // If we can't get the cookie, abort the check. if (!XGetEventData(next_event.xgeneric.display, &next_event.xcookie)) return num_coalesed; // If this isn't from a valid device, throw the event away, as // that's what the message pump would do. Device events come in pairs // with one from the master and one from the slave so there will // always be at least one pending. if (!ui::TouchFactory::GetInstance()->ShouldProcessXI2Event(&next_event)) { XFreeEventData(display, &next_event.xcookie); XNextEvent(display, &next_event); continue; } if (next_event.type == GenericEvent && next_event.xgeneric.evtype == XI_Motion) { XIDeviceEvent* next_xievent = static_cast<XIDeviceEvent*>(next_event.xcookie.data); // Confirm that the motion event is targeted at the same window // and that no buttons or modifiers have changed. if (xievent->event == next_xievent->event && xievent->child == next_xievent->child && xievent->buttons.mask_len == next_xievent->buttons.mask_len && (memcmp(xievent->buttons.mask, next_xievent->buttons.mask, xievent->buttons.mask_len) == 0) && xievent->mods.base == next_xievent->mods.base && xievent->mods.latched == next_xievent->mods.latched && xievent->mods.locked == next_xievent->mods.locked && xievent->mods.effective == next_xievent->mods.effective) { XFreeEventData(display, &next_event.xcookie); // Free the previous cookie. if (num_coalesed > 0) XFreeEventData(display, &last_event->xcookie); // Get the event and its cookie data. XNextEvent(display, last_event); XGetEventData(display, &last_event->xcookie); ++num_coalesed; continue; } else { // This isn't an event we want so free its cookie data. XFreeEventData(display, &next_event.xcookie); } } break; } return num_coalesed; } class DesktopHostLinux : public DesktopHost { public: explicit DesktopHostLinux(const gfx::Rect& bounds); virtual ~DesktopHostLinux(); private: // base::MessageLoop::Dispatcher Override. virtual DispatchStatus Dispatch(XEvent* xev) OVERRIDE; // DesktopHost Overrides. virtual void SetDesktop(Desktop* desktop) OVERRIDE; virtual gfx::AcceleratedWidget GetAcceleratedWidget() OVERRIDE; virtual void Show() OVERRIDE; virtual gfx::Size GetSize() const OVERRIDE; virtual void SetSize(const gfx::Size& size) OVERRIDE; virtual void SetCursor(gfx::NativeCursor cursor_type) OVERRIDE; virtual gfx::Point QueryMouseLocation() OVERRIDE; Desktop* desktop_; // The display and the native X window hosting the desktop. Display* xdisplay_; ::Window xwindow_; // Current Aura cursor. gfx::NativeCursor current_cursor_; // The size of |xwindow_|. gfx::Rect bounds_; DISALLOW_COPY_AND_ASSIGN(DesktopHostLinux); }; DesktopHostLinux::DesktopHostLinux(const gfx::Rect& bounds) : desktop_(NULL), xdisplay_(NULL), xwindow_(0), current_cursor_(aura::kCursorNull), bounds_(bounds) { // This assumes that the message-pump creates and owns the display. xdisplay_ = base::MessagePumpX::GetDefaultXDisplay(); xwindow_ = XCreateSimpleWindow(xdisplay_, DefaultRootWindow(xdisplay_), bounds.x(), bounds.y(), bounds.width(), bounds.height(), 0, 0, 0); long event_mask = ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask | ExposureMask | VisibilityChangeMask | StructureNotifyMask | PropertyChangeMask | PointerMotionMask; XSelectInput(xdisplay_, xwindow_, event_mask); XFlush(xdisplay_); if (base::MessagePumpForUI::HasXInput2()) ui::TouchFactory::GetInstance()->SetupXI2ForXWindow(xwindow_); } DesktopHostLinux::~DesktopHostLinux() { XDestroyWindow(xdisplay_, xwindow_); } base::MessagePumpDispatcher::DispatchStatus DesktopHostLinux::Dispatch( XEvent* xev) { bool handled = false; switch (xev->type) { case Expose: desktop_->Draw(); handled = true; break; case KeyPress: { KeyEvent keydown_event(xev, false); handled = desktop_->OnKeyEvent(keydown_event); KeyEvent char_event(xev, true); handled |= desktop_->OnKeyEvent(char_event); break; } case KeyRelease: { KeyEvent keyup_event(xev, false); handled = desktop_->OnKeyEvent(keyup_event); break; } case ButtonPress: case ButtonRelease: { MouseEvent mouseev(xev); handled = desktop_->OnMouseEvent(mouseev); break; } case MotionNotify: { // Discard all but the most recent motion event that targets the same // window with unchanged state. XEvent last_event; while (XPending(xev->xany.display)) { XEvent next_event; XPeekEvent(xev->xany.display, &next_event); if (next_event.type == MotionNotify && next_event.xmotion.window == xev->xmotion.window && next_event.xmotion.subwindow == xev->xmotion.subwindow && next_event.xmotion.state == xev->xmotion.state) { XNextEvent(xev->xany.display, &last_event); xev = &last_event; } else { break; } } MouseEvent mouseev(xev); handled = desktop_->OnMouseEvent(mouseev); break; } case ConfigureNotify: { DCHECK_EQ(xdisplay_, xev->xconfigure.display); DCHECK_EQ(xwindow_, xev->xconfigure.window); DCHECK_EQ(xwindow_, xev->xconfigure.event); // It's possible that the X window may be resized by some other means than // from within aura (e.g. the X window manager can change the size). Make // sure the desktop size is maintained properly. gfx::Size size(xev->xconfigure.width, xev->xconfigure.height); if (bounds_.size() != size) bounds_.set_size(size); desktop_->OnHostResized(size); handled = true; break; } case GenericEvent: { ui::TouchFactory* factory = ui::TouchFactory::GetInstance(); if (!factory->ShouldProcessXI2Event(xev)) break; // If this is a motion event we want to coalesce all pending motion // events that are at the top of the queue. XEvent last_event; int num_coalesced = 0; if (xev->xgeneric.evtype == XI_Motion) { num_coalesced = CoalescePendingXIMotionEvents(xev, &last_event); if (num_coalesced > 0) xev = &last_event; } ui::EventType type = ui::EventTypeFromNative(xev); switch (type) { case ui::ET_TOUCH_PRESSED: case ui::ET_TOUCH_RELEASED: case ui::ET_TOUCH_MOVED: { TouchEvent touchev(xev); handled = desktop_->OnTouchEvent(touchev); break; } case ui::ET_MOUSE_PRESSED: case ui::ET_MOUSE_RELEASED: case ui::ET_MOUSE_MOVED: case ui::ET_MOUSE_DRAGGED: case ui::ET_MOUSEWHEEL: case ui::ET_MOUSE_ENTERED: case ui::ET_MOUSE_EXITED: { MouseEvent mouseev(xev); handled = desktop_->OnMouseEvent(mouseev); break; } case ui::ET_UNKNOWN: handled = false; break; default: NOTREACHED(); } // If we coalesced an event we need to free its cookie. if (num_coalesced > 0) XFreeEventData(xev->xgeneric.display, &last_event.xcookie); } } return handled ? EVENT_PROCESSED : EVENT_IGNORED; } void DesktopHostLinux::SetDesktop(Desktop* desktop) { desktop_ = desktop; } gfx::AcceleratedWidget DesktopHostLinux::GetAcceleratedWidget() { return xwindow_; } void DesktopHostLinux::Show() { XMapWindow(xdisplay_, xwindow_); XFlush(xdisplay_); } gfx::Size DesktopHostLinux::GetSize() const { return bounds_.size(); } void DesktopHostLinux::SetSize(const gfx::Size& size) { if (bounds_.size() == size) return; bounds_.set_size(size); XResizeWindow(xdisplay_, xwindow_, size.width(), size.height()); } void DesktopHostLinux::SetCursor(gfx::NativeCursor cursor) { if (current_cursor_ == cursor) return; current_cursor_ = cursor; // Custom web cursors are handled directly. if (cursor == kCursorCustom) return; int cursor_shape = CursorShapeFromNative(cursor); ::Cursor xcursor = ui::GetXCursor(cursor_shape); XDefineCursor(xdisplay_, xwindow_, xcursor); } gfx::Point DesktopHostLinux::QueryMouseLocation() { ::Window root_return, child_return; int root_x_return, root_y_return, win_x_return, win_y_return; unsigned int mask_return; XQueryPointer(xdisplay_, xwindow_, &root_return, &child_return, &root_x_return, &root_y_return, &win_x_return, &win_y_return, &mask_return); return gfx::Point(max(0, min(bounds_.width(), win_x_return)), max(0, min(bounds_.height(), win_y_return))); } } // namespace // static DesktopHost* DesktopHost::Create(const gfx::Rect& bounds) { return new DesktopHostLinux(bounds); } } // namespace aura
Implement motion coalescing for XI2
Implement motion coalescing for XI2 BUG=None TEST=None Review URL: http://codereview.chromium.org/8363001 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@106519 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
yitian134/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,ropik/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,ropik/chromium
04b9780b4e6f3e2618103f4b6abe7120410251ba
src/core/lib/security/credentials/external/external_account_credentials.cc
src/core/lib/security/credentials/external/external_account_credentials.cc
// // Copyright 2020 gRPC authors. // // 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 <grpc/support/port_platform.h> #include "src/core/lib/security/credentials/external/external_account_credentials.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "src/core/lib/http/parser.h" #include "src/core/lib/security/util/json_util.h" #include "src/core/lib/slice/b64.h" #define EXTERNAL_ACCOUNT_CREDENTIALS_GRANT_TYPE \ "urn:ietf:params:oauth:grant-type:token-exchange" #define EXTERNAL_ACCOUNT_CREDENTIALS_REQUESTED_TOKEN_TYPE \ "urn:ietf:params:oauth:token-type:access_token" #define GOOGLE_CLOUD_PLATFORM_DEFAULT_SCOPE \ "https://www.googleapis.com/auth/cloud-platform" namespace grpc_core { ExternalAccountCredentials::ExternalAccountCredentials( ExternalAccountCredentialsOptions options, std::vector<std::string> scopes) : options_(std::move(options)) { if (scopes.empty()) { scopes.push_back(GOOGLE_CLOUD_PLATFORM_DEFAULT_SCOPE); } scopes_ = std::move(scopes); } ExternalAccountCredentials::~ExternalAccountCredentials() {} std::string ExternalAccountCredentials::debug_string() { return absl::StrFormat("ExternalAccountCredentials{Audience:%s,%s}", options_.audience, grpc_oauth2_token_fetcher_credentials::debug_string()); } // The token fetching flow: // 1. Retrieve subject token - Subclass's RetrieveSubjectToken() gets called // and the subject token is received in OnRetrieveSubjectTokenInternal(). // 2. Exchange token - ExchangeToken() gets called with the // subject token from #1. Receive the response in OnExchangeTokenInternal(). // 3. (Optional) Impersonate service account - ImpersenateServiceAccount() gets // called with the access token of the response from #2. Get an impersonated // access token in OnImpersenateServiceAccountInternal(). // 4. Finish token fetch - Return back the response that contains an access // token in FinishTokenFetch(). // TODO(chuanr): Avoid starting the remaining requests if the channel gets shut // down. void ExternalAccountCredentials::fetch_oauth2( grpc_credentials_metadata_request* metadata_req, grpc_httpcli_context* httpcli_context, grpc_polling_entity* pollent, grpc_iomgr_cb_func response_cb, grpc_millis deadline) { GPR_ASSERT(ctx_ == nullptr); ctx_ = new HTTPRequestContext(httpcli_context, pollent, deadline); metadata_req_ = metadata_req; response_cb_ = response_cb; auto cb = [this](std::string token, grpc_error* error) { OnRetrieveSubjectTokenInternal(token, error); }; RetrieveSubjectToken(ctx_, options_, cb); } void ExternalAccountCredentials::OnRetrieveSubjectTokenInternal( absl::string_view subject_token, grpc_error* error) { if (error != GRPC_ERROR_NONE) { FinishTokenFetch(error); } else { ExchangeToken(subject_token); } } void ExternalAccountCredentials::ExchangeToken( absl::string_view subject_token) { grpc_uri* uri = grpc_uri_parse(options_.token_url, false); if (uri == nullptr) { FinishTokenFetch(GRPC_ERROR_CREATE_FROM_COPIED_STRING( absl::StrFormat("Invalid token url: %s.", options_.token_url).c_str())); return; } grpc_httpcli_request request; memset(&request, 0, sizeof(grpc_httpcli_request)); request.host = const_cast<char*>(uri->authority); request.http.path = gpr_strdup(uri->path); grpc_http_header* headers = nullptr; if (!options_.client_id.empty() && !options_.client_secret.empty()) { request.http.hdr_count = 2; headers = static_cast<grpc_http_header*>( gpr_malloc(sizeof(grpc_http_header) * request.http.hdr_count)); headers[0].key = gpr_strdup("Content-Type"); headers[0].value = gpr_strdup("application/x-www-form-urlencoded"); std::string raw_cred = absl::StrFormat("%s:%s", options_.client_id, options_.client_secret); char* encoded_cred = grpc_base64_encode(raw_cred.c_str(), raw_cred.length(), 0, 0); std::string str = absl::StrFormat("Basic %s", std::string(encoded_cred)); headers[1].key = gpr_strdup("Authorization"); headers[1].value = gpr_strdup(str.c_str()); gpr_free(encoded_cred); } else { request.http.hdr_count = 1; headers = static_cast<grpc_http_header*>( gpr_malloc(sizeof(grpc_http_header) * request.http.hdr_count)); headers[0].key = gpr_strdup("Content-Type"); headers[0].value = gpr_strdup("application/x-www-form-urlencoded"); } request.http.hdrs = headers; request.handshaker = (strcmp(uri->scheme, "https") == 0) ? &grpc_httpcli_ssl : &grpc_httpcli_plaintext; std::vector<std::string> body_parts; body_parts.push_back(absl::StrFormat("%s=%s", "audience", options_.audience)); body_parts.push_back(absl::StrFormat( "%s=%s", "grant_type", EXTERNAL_ACCOUNT_CREDENTIALS_GRANT_TYPE)); body_parts.push_back( absl::StrFormat("%s=%s", "requested_token_type", EXTERNAL_ACCOUNT_CREDENTIALS_REQUESTED_TOKEN_TYPE)); body_parts.push_back(absl::StrFormat("%s=%s", "subject_token_type", options_.subject_token_type)); body_parts.push_back( absl::StrFormat("%s=%s", "subject_token", subject_token)); std::string scope = GOOGLE_CLOUD_PLATFORM_DEFAULT_SCOPE; if (options_.service_account_impersonation_url.empty()) { scope = absl::StrJoin(scopes_, " "); } body_parts.push_back(absl::StrFormat("%s=%s", "scope", scope)); std::string body = absl::StrJoin(body_parts, "&"); grpc_resource_quota* resource_quota = grpc_resource_quota_create("external_account_credentials"); grpc_http_response_destroy(&ctx_->response); ctx_->response = {}; GRPC_CLOSURE_INIT(&ctx_->closure, OnExchangeToken, this, nullptr); grpc_httpcli_post(ctx_->httpcli_context, ctx_->pollent, resource_quota, &request, body.c_str(), body.size(), ctx_->deadline, &ctx_->closure, &ctx_->response); grpc_resource_quota_unref_internal(resource_quota); grpc_http_request_destroy(&request.http); grpc_uri_destroy(uri); } void ExternalAccountCredentials::OnExchangeToken(void* arg, grpc_error* error) { ExternalAccountCredentials* self = static_cast<ExternalAccountCredentials*>(arg); self->OnExchangeTokenInternal(GRPC_ERROR_REF(error)); } void ExternalAccountCredentials::OnExchangeTokenInternal(grpc_error* error) { if (error != GRPC_ERROR_NONE) { FinishTokenFetch(error); } else { if (options_.service_account_impersonation_url.empty()) { metadata_req_->response = ctx_->response; metadata_req_->response.body = gpr_strdup(ctx_->response.body); FinishTokenFetch(GRPC_ERROR_NONE); } else { ImpersenateServiceAccount(); } } } void ExternalAccountCredentials::ImpersenateServiceAccount() { grpc_error* error = GRPC_ERROR_NONE; absl::string_view response_body(ctx_->response.body, ctx_->response.body_length); Json json = Json::Parse(response_body, &error); if (error != GRPC_ERROR_NONE || json.type() != Json::Type::OBJECT) { FinishTokenFetch(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "Invalid token exchange response.", &error, 1)); GRPC_ERROR_UNREF(error); return; } auto it = json.object_value().find("access_token"); if (it == json.object_value().end() || it->second.type() != Json::Type::STRING) { FinishTokenFetch(GRPC_ERROR_CREATE_FROM_COPIED_STRING( absl::StrFormat("Missing or invalid access_token in %s.", response_body) .c_str())); return; } std::string access_token = it->second.string_value(); grpc_uri* uri = grpc_uri_parse(options_.service_account_impersonation_url, false); if (uri == nullptr) { FinishTokenFetch(GRPC_ERROR_CREATE_FROM_COPIED_STRING( absl::StrFormat("Invalid service account impersonation url: %s.", options_.service_account_impersonation_url) .c_str())); return; } grpc_httpcli_request request; memset(&request, 0, sizeof(grpc_httpcli_request)); request.host = const_cast<char*>(uri->authority); request.http.path = gpr_strdup(uri->path); request.http.hdr_count = 2; grpc_http_header* headers = static_cast<grpc_http_header*>( gpr_malloc(sizeof(grpc_http_header) * request.http.hdr_count)); headers[0].key = gpr_strdup("Content-Type"); headers[0].value = gpr_strdup("application/x-www-form-urlencoded"); std::string str = absl::StrFormat("Bearer %s", access_token); headers[1].key = gpr_strdup("Authorization"); headers[1].value = gpr_strdup(str.c_str()); request.http.hdrs = headers; request.handshaker = (strcmp(uri->scheme, "https") == 0) ? &grpc_httpcli_ssl : &grpc_httpcli_plaintext; std::string scope = absl::StrJoin(scopes_, " "); std::string body = absl::StrFormat("%s=%s", "scope", scope); grpc_resource_quota* resource_quota = grpc_resource_quota_create("external_account_credentials"); grpc_http_response_destroy(&ctx_->response); ctx_->response = {}; GRPC_CLOSURE_INIT(&ctx_->closure, OnImpersenateServiceAccount, this, nullptr); grpc_httpcli_post(ctx_->httpcli_context, ctx_->pollent, resource_quota, &request, body.c_str(), body.size(), ctx_->deadline, &ctx_->closure, &ctx_->response); grpc_resource_quota_unref_internal(resource_quota); grpc_http_request_destroy(&request.http); grpc_uri_destroy(uri); } void ExternalAccountCredentials::OnImpersenateServiceAccount( void* arg, grpc_error* error) { ExternalAccountCredentials* self = static_cast<ExternalAccountCredentials*>(arg); self->OnImpersenateServiceAccountInternal(GRPC_ERROR_REF(error)); } void ExternalAccountCredentials::OnImpersenateServiceAccountInternal( grpc_error* error) { if (error != GRPC_ERROR_NONE) { FinishTokenFetch(error); return; } absl::string_view response_body(ctx_->response.body, ctx_->response.body_length); Json json = Json::Parse(response_body, &error); if (error != GRPC_ERROR_NONE || json.type() != Json::Type::OBJECT) { FinishTokenFetch(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "Invalid service account impersonation response.", &error, 1)); GRPC_ERROR_UNREF(error); return; } auto it = json.object_value().find("accessToken"); if (it == json.object_value().end() || it->second.type() != Json::Type::STRING) { FinishTokenFetch(GRPC_ERROR_CREATE_FROM_COPIED_STRING( absl::StrFormat("Missing or invalid accessToken in %s.", response_body) .c_str())); return; } std::string access_token = it->second.string_value(); it = json.object_value().find("expireTime"); if (it == json.object_value().end() || it->second.type() != Json::Type::STRING) { FinishTokenFetch(GRPC_ERROR_CREATE_FROM_COPIED_STRING( absl::StrFormat("Missing or invalid expireTime in %s.", response_body) .c_str())); return; } std::string expire_time = it->second.string_value(); absl::Time t; if (!absl::ParseTime(absl::RFC3339_full, expire_time, &t, nullptr)) { FinishTokenFetch(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Invalid expire time of service account impersonation response.")); return; } int expire_in = (t - absl::Now()) / absl::Seconds(1); std::string body = absl::StrFormat( "{\"access_token\":\"%s\",\"expires_in\":%d,\"token_type\":\"Bearer\"}", access_token, expire_in); metadata_req_->response = ctx_->response; metadata_req_->response.body = gpr_strdup(body.c_str()); metadata_req_->response.body_length = body.length(); FinishTokenFetch(GRPC_ERROR_NONE); } void ExternalAccountCredentials::FinishTokenFetch(grpc_error* error) { GRPC_LOG_IF_ERROR("Fetch external account credentials access token", GRPC_ERROR_REF(error)); // Move object state into local variables. auto* cb = response_cb_; response_cb_ = nullptr; auto* metadata_req = metadata_req_; metadata_req_ = nullptr; auto* ctx = ctx_; ctx_ = nullptr; // Invoke the callback. cb(metadata_req, error); // Delete context. delete ctx; GRPC_ERROR_UNREF(error); } } // namespace grpc_core
// // Copyright 2020 gRPC authors. // // 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 <grpc/support/port_platform.h> #include "src/core/lib/security/credentials/external/external_account_credentials.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "src/core/lib/http/parser.h" #include "src/core/lib/security/util/json_util.h" #include "src/core/lib/slice/b64.h" #define EXTERNAL_ACCOUNT_CREDENTIALS_GRANT_TYPE \ "urn:ietf:params:oauth:grant-type:token-exchange" #define EXTERNAL_ACCOUNT_CREDENTIALS_REQUESTED_TOKEN_TYPE \ "urn:ietf:params:oauth:token-type:access_token" #define GOOGLE_CLOUD_PLATFORM_DEFAULT_SCOPE \ "https://www.googleapis.com/auth/cloud-platform" namespace grpc_core { ExternalAccountCredentials::ExternalAccountCredentials( ExternalAccountCredentialsOptions options, std::vector<std::string> scopes) : options_(std::move(options)) { if (scopes.empty()) { scopes.push_back(GOOGLE_CLOUD_PLATFORM_DEFAULT_SCOPE); } scopes_ = std::move(scopes); } ExternalAccountCredentials::~ExternalAccountCredentials() {} std::string ExternalAccountCredentials::debug_string() { return absl::StrFormat("ExternalAccountCredentials{Audience:%s,%s}", options_.audience, grpc_oauth2_token_fetcher_credentials::debug_string()); } // The token fetching flow: // 1. Retrieve subject token - Subclass's RetrieveSubjectToken() gets called // and the subject token is received in OnRetrieveSubjectTokenInternal(). // 2. Exchange token - ExchangeToken() gets called with the // subject token from #1. Receive the response in OnExchangeTokenInternal(). // 3. (Optional) Impersonate service account - ImpersenateServiceAccount() gets // called with the access token of the response from #2. Get an impersonated // access token in OnImpersenateServiceAccountInternal(). // 4. Finish token fetch - Return back the response that contains an access // token in FinishTokenFetch(). // TODO(chuanr): Avoid starting the remaining requests if the channel gets shut // down. void ExternalAccountCredentials::fetch_oauth2( grpc_credentials_metadata_request* metadata_req, grpc_httpcli_context* httpcli_context, grpc_polling_entity* pollent, grpc_iomgr_cb_func response_cb, grpc_millis deadline) { GPR_ASSERT(ctx_ == nullptr); ctx_ = new HTTPRequestContext(httpcli_context, pollent, deadline); metadata_req_ = metadata_req; response_cb_ = response_cb; auto cb = [this](std::string token, grpc_error* error) { OnRetrieveSubjectTokenInternal(token, error); }; RetrieveSubjectToken(ctx_, options_, cb); } void ExternalAccountCredentials::OnRetrieveSubjectTokenInternal( absl::string_view subject_token, grpc_error* error) { if (error != GRPC_ERROR_NONE) { FinishTokenFetch(error); } else { ExchangeToken(subject_token); } } void ExternalAccountCredentials::ExchangeToken( absl::string_view subject_token) { grpc_uri* uri = grpc_uri_parse(options_.token_url, false); if (uri == nullptr) { FinishTokenFetch(GRPC_ERROR_CREATE_FROM_COPIED_STRING( absl::StrFormat("Invalid token url: %s.", options_.token_url).c_str())); return; } grpc_httpcli_request request; memset(&request, 0, sizeof(grpc_httpcli_request)); request.host = const_cast<char*>(uri->authority); request.http.path = gpr_strdup(uri->path); grpc_http_header* headers = nullptr; if (!options_.client_id.empty() && !options_.client_secret.empty()) { request.http.hdr_count = 2; headers = static_cast<grpc_http_header*>( gpr_malloc(sizeof(grpc_http_header) * request.http.hdr_count)); headers[0].key = gpr_strdup("Content-Type"); headers[0].value = gpr_strdup("application/x-www-form-urlencoded"); std::string raw_cred = absl::StrFormat("%s:%s", options_.client_id, options_.client_secret); char* encoded_cred = grpc_base64_encode(raw_cred.c_str(), raw_cred.length(), 0, 0); std::string str = absl::StrFormat("Basic %s", std::string(encoded_cred)); headers[1].key = gpr_strdup("Authorization"); headers[1].value = gpr_strdup(str.c_str()); gpr_free(encoded_cred); } else { request.http.hdr_count = 1; headers = static_cast<grpc_http_header*>( gpr_malloc(sizeof(grpc_http_header) * request.http.hdr_count)); headers[0].key = gpr_strdup("Content-Type"); headers[0].value = gpr_strdup("application/x-www-form-urlencoded"); } request.http.hdrs = headers; request.handshaker = (strcmp(uri->scheme, "https") == 0) ? &grpc_httpcli_ssl : &grpc_httpcli_plaintext; std::vector<std::string> body_parts; body_parts.push_back(absl::StrFormat("%s=%s", "audience", options_.audience)); body_parts.push_back(absl::StrFormat( "%s=%s", "grant_type", EXTERNAL_ACCOUNT_CREDENTIALS_GRANT_TYPE)); body_parts.push_back( absl::StrFormat("%s=%s", "requested_token_type", EXTERNAL_ACCOUNT_CREDENTIALS_REQUESTED_TOKEN_TYPE)); body_parts.push_back(absl::StrFormat("%s=%s", "subject_token_type", options_.subject_token_type)); body_parts.push_back( absl::StrFormat("%s=%s", "subject_token", subject_token)); std::string scope = GOOGLE_CLOUD_PLATFORM_DEFAULT_SCOPE; if (options_.service_account_impersonation_url.empty()) { scope = absl::StrJoin(scopes_, " "); } body_parts.push_back(absl::StrFormat("%s=%s", "scope", scope)); std::string body = absl::StrJoin(body_parts, "&"); grpc_resource_quota* resource_quota = grpc_resource_quota_create("external_account_credentials"); grpc_http_response_destroy(&ctx_->response); ctx_->response = {}; GRPC_CLOSURE_INIT(&ctx_->closure, OnExchangeToken, this, nullptr); grpc_httpcli_post(ctx_->httpcli_context, ctx_->pollent, resource_quota, &request, body.c_str(), body.size(), ctx_->deadline, &ctx_->closure, &ctx_->response); grpc_resource_quota_unref_internal(resource_quota); grpc_http_request_destroy(&request.http); grpc_uri_destroy(uri); } void ExternalAccountCredentials::OnExchangeToken(void* arg, grpc_error* error) { ExternalAccountCredentials* self = static_cast<ExternalAccountCredentials*>(arg); self->OnExchangeTokenInternal(GRPC_ERROR_REF(error)); } void ExternalAccountCredentials::OnExchangeTokenInternal(grpc_error* error) { if (error != GRPC_ERROR_NONE) { FinishTokenFetch(error); } else { if (options_.service_account_impersonation_url.empty()) { metadata_req_->response = ctx_->response; metadata_req_->response.body = gpr_strdup( std::string(ctx_->response.body, ctx_->response.body_length).c_str()); metadata_req_->response.hdrs = static_cast<grpc_http_header*>( gpr_malloc(sizeof(grpc_http_header) * ctx_->response.hdr_count)); for (int i = 0; i < ctx_->response.hdr_count; i++) { metadata_req_->response.hdrs[i].key = gpr_strdup(ctx_->response.hdrs[i].key); metadata_req_->response.hdrs[i].value = gpr_strdup(ctx_->response.hdrs[i].value); } FinishTokenFetch(GRPC_ERROR_NONE); } else { ImpersenateServiceAccount(); } } } void ExternalAccountCredentials::ImpersenateServiceAccount() { grpc_error* error = GRPC_ERROR_NONE; absl::string_view response_body(ctx_->response.body, ctx_->response.body_length); Json json = Json::Parse(response_body, &error); if (error != GRPC_ERROR_NONE || json.type() != Json::Type::OBJECT) { FinishTokenFetch(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "Invalid token exchange response.", &error, 1)); GRPC_ERROR_UNREF(error); return; } auto it = json.object_value().find("access_token"); if (it == json.object_value().end() || it->second.type() != Json::Type::STRING) { FinishTokenFetch(GRPC_ERROR_CREATE_FROM_COPIED_STRING( absl::StrFormat("Missing or invalid access_token in %s.", response_body) .c_str())); return; } std::string access_token = it->second.string_value(); grpc_uri* uri = grpc_uri_parse(options_.service_account_impersonation_url, false); if (uri == nullptr) { FinishTokenFetch(GRPC_ERROR_CREATE_FROM_COPIED_STRING( absl::StrFormat("Invalid service account impersonation url: %s.", options_.service_account_impersonation_url) .c_str())); return; } grpc_httpcli_request request; memset(&request, 0, sizeof(grpc_httpcli_request)); request.host = const_cast<char*>(uri->authority); request.http.path = gpr_strdup(uri->path); request.http.hdr_count = 2; grpc_http_header* headers = static_cast<grpc_http_header*>( gpr_malloc(sizeof(grpc_http_header) * request.http.hdr_count)); headers[0].key = gpr_strdup("Content-Type"); headers[0].value = gpr_strdup("application/x-www-form-urlencoded"); std::string str = absl::StrFormat("Bearer %s", access_token); headers[1].key = gpr_strdup("Authorization"); headers[1].value = gpr_strdup(str.c_str()); request.http.hdrs = headers; request.handshaker = (strcmp(uri->scheme, "https") == 0) ? &grpc_httpcli_ssl : &grpc_httpcli_plaintext; std::string scope = absl::StrJoin(scopes_, " "); std::string body = absl::StrFormat("%s=%s", "scope", scope); grpc_resource_quota* resource_quota = grpc_resource_quota_create("external_account_credentials"); grpc_http_response_destroy(&ctx_->response); ctx_->response = {}; GRPC_CLOSURE_INIT(&ctx_->closure, OnImpersenateServiceAccount, this, nullptr); grpc_httpcli_post(ctx_->httpcli_context, ctx_->pollent, resource_quota, &request, body.c_str(), body.size(), ctx_->deadline, &ctx_->closure, &ctx_->response); grpc_resource_quota_unref_internal(resource_quota); grpc_http_request_destroy(&request.http); grpc_uri_destroy(uri); } void ExternalAccountCredentials::OnImpersenateServiceAccount( void* arg, grpc_error* error) { ExternalAccountCredentials* self = static_cast<ExternalAccountCredentials*>(arg); self->OnImpersenateServiceAccountInternal(GRPC_ERROR_REF(error)); } void ExternalAccountCredentials::OnImpersenateServiceAccountInternal( grpc_error* error) { if (error != GRPC_ERROR_NONE) { FinishTokenFetch(error); return; } absl::string_view response_body(ctx_->response.body, ctx_->response.body_length); Json json = Json::Parse(response_body, &error); if (error != GRPC_ERROR_NONE || json.type() != Json::Type::OBJECT) { FinishTokenFetch(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "Invalid service account impersonation response.", &error, 1)); GRPC_ERROR_UNREF(error); return; } auto it = json.object_value().find("accessToken"); if (it == json.object_value().end() || it->second.type() != Json::Type::STRING) { FinishTokenFetch(GRPC_ERROR_CREATE_FROM_COPIED_STRING( absl::StrFormat("Missing or invalid accessToken in %s.", response_body) .c_str())); return; } std::string access_token = it->second.string_value(); it = json.object_value().find("expireTime"); if (it == json.object_value().end() || it->second.type() != Json::Type::STRING) { FinishTokenFetch(GRPC_ERROR_CREATE_FROM_COPIED_STRING( absl::StrFormat("Missing or invalid expireTime in %s.", response_body) .c_str())); return; } std::string expire_time = it->second.string_value(); absl::Time t; if (!absl::ParseTime(absl::RFC3339_full, expire_time, &t, nullptr)) { FinishTokenFetch(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Invalid expire time of service account impersonation response.")); return; } int expire_in = (t - absl::Now()) / absl::Seconds(1); std::string body = absl::StrFormat( "{\"access_token\":\"%s\",\"expires_in\":%d,\"token_type\":\"Bearer\"}", access_token, expire_in); metadata_req_->response = ctx_->response; metadata_req_->response.body = gpr_strdup(body.c_str()); metadata_req_->response.body_length = body.length(); metadata_req_->response.hdrs = static_cast<grpc_http_header*>( gpr_malloc(sizeof(grpc_http_header) * ctx_->response.hdr_count)); for (int i = 0; i < ctx_->response.hdr_count; i++) { metadata_req_->response.hdrs[i].key = gpr_strdup(ctx_->response.hdrs[i].key); metadata_req_->response.hdrs[i].value = gpr_strdup(ctx_->response.hdrs[i].value); } FinishTokenFetch(GRPC_ERROR_NONE); } void ExternalAccountCredentials::FinishTokenFetch(grpc_error* error) { GRPC_LOG_IF_ERROR("Fetch external account credentials access token", GRPC_ERROR_REF(error)); // Move object state into local variables. auto* cb = response_cb_; response_cb_ = nullptr; auto* metadata_req = metadata_req_; metadata_req_ = nullptr; auto* ctx = ctx_; ctx_ = nullptr; // Invoke the callback. cb(metadata_req, error); // Delete context. delete ctx; GRPC_ERROR_UNREF(error); } } // namespace grpc_core
Update external_account_credentials.cc
Update external_account_credentials.cc
C++
apache-2.0
grpc/grpc,ejona86/grpc,jtattermusch/grpc,donnadionne/grpc,ctiller/grpc,nicolasnoble/grpc,ctiller/grpc,nicolasnoble/grpc,stanley-cheung/grpc,jtattermusch/grpc,donnadionne/grpc,nicolasnoble/grpc,stanley-cheung/grpc,jtattermusch/grpc,grpc/grpc,vjpai/grpc,ctiller/grpc,ctiller/grpc,ctiller/grpc,donnadionne/grpc,ejona86/grpc,ejona86/grpc,stanley-cheung/grpc,stanley-cheung/grpc,jtattermusch/grpc,donnadionne/grpc,vjpai/grpc,donnadionne/grpc,stanley-cheung/grpc,stanley-cheung/grpc,nicolasnoble/grpc,ctiller/grpc,jtattermusch/grpc,ejona86/grpc,vjpai/grpc,jtattermusch/grpc,jtattermusch/grpc,ejona86/grpc,ejona86/grpc,grpc/grpc,grpc/grpc,stanley-cheung/grpc,ctiller/grpc,grpc/grpc,donnadionne/grpc,vjpai/grpc,stanley-cheung/grpc,donnadionne/grpc,stanley-cheung/grpc,vjpai/grpc,ejona86/grpc,stanley-cheung/grpc,ejona86/grpc,ctiller/grpc,grpc/grpc,nicolasnoble/grpc,jtattermusch/grpc,nicolasnoble/grpc,donnadionne/grpc,nicolasnoble/grpc,stanley-cheung/grpc,nicolasnoble/grpc,vjpai/grpc,vjpai/grpc,grpc/grpc,donnadionne/grpc,grpc/grpc,nicolasnoble/grpc,vjpai/grpc,ejona86/grpc,jtattermusch/grpc,grpc/grpc,grpc/grpc,nicolasnoble/grpc,ctiller/grpc,grpc/grpc,vjpai/grpc,vjpai/grpc,vjpai/grpc,jtattermusch/grpc,jtattermusch/grpc,ctiller/grpc,vjpai/grpc,stanley-cheung/grpc,jtattermusch/grpc,ejona86/grpc,ejona86/grpc,ejona86/grpc,nicolasnoble/grpc,nicolasnoble/grpc,donnadionne/grpc,ctiller/grpc,donnadionne/grpc,donnadionne/grpc,grpc/grpc,ctiller/grpc
5deec061115bfe8e9e405f44bb60b0281cd9c252
MQ/src/CommandServer.cpp
MQ/src/CommandServer.cpp
/* * Copyright 2010 MQWeb - Franky Braem * * Licensed under the EUPL, Version 1.1 or – as soon they * will be approved by the European Commission - subsequent * versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the * Licence. * You may obtain a copy of the Licence at: * * http://joinup.ec.europa.eu/software/page/eupl * * Unless required by applicable law or agreed to in * writing, software distributed under the Licence is * distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the Licence for the specific language governing * permissions and limitations under the Licence. */ #include <iostream> #include "MQ/CommandServer.h" #include "MQ/QueueManager.h" #include "MQ/Queue.h" #include "MQ/MQException.h" #include "MQ/Message.h" #include "MQ/PCF.h" // When we get a MQRC_TRUNCATE..., we will try to enlarge the buffer. // It is still possible to get MQRC_CONVERTED_MSG_TOO_BIG, but we really hope // this buffer is large enough for all possible PCF answers. #define REPLY_MESSAGE_LEN 8192 namespace MQ { CommandServer::CommandServer(QueueManager& qmgr, const std::string& modelQueue) : _qmgr(qmgr) , _commandQ(qmgr, qmgr.commandQueue()) , _replyQ(qmgr, modelQueue) { _commandQ.open(MQOO_OUTPUT); _replyQ.open(MQOO_INPUT_SHARED | MQOO_FAIL_IF_QUIESCING); } PCF::Ptr CommandServer::createCommand(MQLONG command) const { return new PCF(command, _qmgr.zos()); } // Throws MQException void CommandServer::sendCommand(PCF::Ptr& command, PCF::Vector& response) { response.clear(); command->setReplyToQueue(_replyQ.name()); _commandQ.put(*command, MQPMO_NO_SYNCPOINT); long wait = 600000; PCF::Ptr msgResponse; bool keepRunning = true; while(keepRunning) { msgResponse = new PCF(_qmgr.zos()); msgResponse->correlationId()->set(command->messageId()); msgResponse->buffer().resize(REPLY_MESSAGE_LEN, false); try { _replyQ.get(*msgResponse.get(), MQGMO_CONVERT | MQGMO_NO_SYNCPOINT, wait); } catch(MQException& mqe) { if ( mqe.reason() == MQRC_TRUNCATED_MSG_FAILED ) { Poco::Logger& logger = Poco::Logger::get("mq"); if ( logger.trace() ) { poco_trace_f2(logger, "Truncated message received. Actual size is %ld (> %d).", msgResponse->dataLength(), REPLY_MESSAGE_LEN); } msgResponse->buffer().resize(msgResponse->dataLength(), false); msgResponse->clear(); msgResponse->correlationId()->set(command->messageId()); _replyQ.get(*msgResponse.get(), MQGMO_CONVERT | MQGMO_NO_SYNCPOINT); } else { // on z/OS we can't rely on isLast, because a response // can have multiple sets of responses which have a // last flag in each set ... if ( _qmgr.zos() && mqe.reason() == MQRC_NO_MSG_AVAILABLE ) { keepRunning = false; continue; } throw; } } wait = 100; msgResponse->buffer().resize(msgResponse->dataLength()); msgResponse->init(); response.push_back(msgResponse); if ( ! _qmgr.zos() && msgResponse->isLast() ) { keepRunning = false; } } } }
/* * Copyright 2010 MQWeb - Franky Braem * * Licensed under the EUPL, Version 1.1 or – as soon they * will be approved by the European Commission - subsequent * versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the * Licence. * You may obtain a copy of the Licence at: * * http://joinup.ec.europa.eu/software/page/eupl * * Unless required by applicable law or agreed to in * writing, software distributed under the Licence is * distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the Licence for the specific language governing * permissions and limitations under the Licence. */ #include <iostream> #include "MQ/CommandServer.h" #include "MQ/QueueManager.h" #include "MQ/Queue.h" #include "MQ/MQException.h" #include "MQ/Message.h" #include "MQ/PCF.h" // When we get a MQRC_TRUNCATE..., we will try to enlarge the buffer. // It is still possible to get MQRC_CONVERTED_MSG_TOO_BIG, but we really hope // this buffer is large enough for all possible PCF answers. #define REPLY_MESSAGE_LEN 8192 namespace MQ { CommandServer::CommandServer(QueueManager& qmgr, const std::string& modelQueue) : _qmgr(qmgr) , _commandQ(qmgr, qmgr.commandQueue()) , _replyQ(qmgr, modelQueue) { _commandQ.open(MQOO_OUTPUT); _replyQ.open(MQOO_INPUT_SHARED | MQOO_FAIL_IF_QUIESCING); } PCF::Ptr CommandServer::createCommand(MQLONG command) const { return new PCF(command, _qmgr.zos()); } // Throws MQException void CommandServer::sendCommand(PCF::Ptr& command, PCF::Vector& response) { response.clear(); command->setReplyToQueue(_replyQ.name()); command->setExpiry(1200000); _commandQ.put(*command, MQPMO_NO_SYNCPOINT); long wait = 600000; PCF::Ptr msgResponse; bool keepRunning = true; while(keepRunning) { msgResponse = new PCF(_qmgr.zos()); msgResponse->correlationId()->set(command->messageId()); msgResponse->buffer().resize(REPLY_MESSAGE_LEN, false); try { _replyQ.get(*msgResponse.get(), MQGMO_CONVERT | MQGMO_NO_SYNCPOINT, wait); } catch(MQException& mqe) { if ( mqe.reason() == MQRC_TRUNCATED_MSG_FAILED ) { Poco::Logger& logger = Poco::Logger::get("mq"); if ( logger.trace() ) { poco_trace_f2(logger, "Truncated message received. Actual size is %ld (> %d).", msgResponse->dataLength(), REPLY_MESSAGE_LEN); } msgResponse->buffer().resize(msgResponse->dataLength(), false); msgResponse->clear(); msgResponse->correlationId()->set(command->messageId()); _replyQ.get(*msgResponse.get(), MQGMO_CONVERT | MQGMO_NO_SYNCPOINT); } else { // on z/OS we can't rely on isLast, because a response // can have multiple sets of responses which have a // last flag in each set ... if ( _qmgr.zos() && mqe.reason() == MQRC_NO_MSG_AVAILABLE ) { keepRunning = false; continue; } throw; } } wait = 100; msgResponse->buffer().resize(msgResponse->dataLength()); msgResponse->init(); response.push_back(msgResponse); if ( ! _qmgr.zos() && msgResponse->isLast() ) { keepRunning = false; } } } }
Set expiry to PCF command message
Set expiry to PCF command message
C++
mit
fbraem/mqweb,fbraem/mqweb,fbraem/mqweb
e0e8e3229e676032abfcf85ea18a1dab3c211d83
MQ/src/PCFParameters.cpp
MQ/src/PCFParameters.cpp
/* * Copyright 2017 - KBC Group NV - Franky Braem - The MIT license * 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 <string.h> // For memcpy #include "Poco/String.h" #include "Poco/DateTimeParser.h" #include "MQ/PCFParameters.h" namespace MQ { PCFParameters::PCFParameters(Buffer& buffer) : _buffer(buffer) { } PCFParameters::PCFParameters(const PCFParameters& copy) : _buffer(copy._buffer), _pointers(copy._pointers) { } PCFParameters::~PCFParameters() { } void PCFParameters::add(MQLONG parameter, const std::string& value) { MQLONG structLength = ((MQCFST_STRUC_LENGTH_FIXED + (MQLONG) value.length()) / 4 + 1) * 4; size_t pos = _buffer.size(); _pointers.insert(std::make_pair(parameter, pos)); _buffer.resize(_buffer.size() + structLength); MQCFST* pcfParam = (MQCFST*) _buffer.data(pos); pcfParam->Type = MQCFT_STRING; pcfParam->StrucLength = structLength; pcfParam->Parameter = parameter; pcfParam->CodedCharSetId = MQCCSI_DEFAULT; pcfParam->StringLength = (MQLONG) value.length(); memcpy(pcfParam->String, value.c_str(), pcfParam->StringLength); } void PCFParameters::add(MQLONG parameter, MQLONG value) { size_t pos = _buffer.size(); _pointers.insert(std::make_pair(parameter, pos)); _buffer.resize(_buffer.size() + MQCFIN_STRUC_LENGTH); MQCFIN* pcfParam = (MQCFIN*) _buffer.data(pos); pcfParam->Type = MQCFT_INTEGER; pcfParam->StrucLength = MQCFIN_STRUC_LENGTH; pcfParam->Parameter = parameter; pcfParam->Value = value; } void PCFParameters::add(MQLONG parameter, Buffer::Ptr value) { size_t pos = _buffer.size(); _pointers.insert(std::make_pair(parameter, pos)); MQLONG structLength = ((MQCFST_STRUC_LENGTH_FIXED + (MQLONG) value->size()) / 4 + 1) * 4; _buffer.resize(_buffer.size() + structLength); MQCFBS* pcfParam = (MQCFBS*) _buffer.data(pos); pcfParam->Type = MQCFT_BYTE_STRING; pcfParam->StrucLength = structLength; pcfParam->Parameter = parameter; pcfParam->StringLength = (MQLONG) value->size(); memcpy(pcfParam->String, value->data(), pcfParam->StringLength); } void PCFParameters::addList(MQLONG parameter, MQLONG *values, unsigned int count) { size_t pos = _buffer.size(); int strucLength = MQCFIL_STRUC_LENGTH_FIXED + count * sizeof(MQLONG); _pointers.insert(std::make_pair(parameter, pos)); _buffer.resize(_buffer.size() + strucLength); MQCFIL *pcfIntegerList = (MQCFIL *) _buffer.data(pos); pcfIntegerList->Count = count; pcfIntegerList->Type = MQCFT_INTEGER_LIST; pcfIntegerList->StrucLength = strucLength; pcfIntegerList->Parameter = parameter; for(int i = 0; i < count; ++i) pcfIntegerList->Values[i] = values[i]; } void PCFParameters::addFilter(MQLONG parameter, MQLONG op, const std::string& value) { size_t pos = _buffer.size(); MQLONG strucLength = ((MQCFSF_STRUC_LENGTH_FIXED + (MQLONG) value.length()) / 4 + 1) * 4; _pointers.insert(std::make_pair(parameter, pos)); _buffer.resize(_buffer.size() + strucLength); MQCFSF* pcfFilter = (MQCFSF*) _buffer.data(pos); pcfFilter->Type = MQCFT_STRING_FILTER; pcfFilter->StrucLength = strucLength; pcfFilter->Parameter = parameter; pcfFilter->Operator = op; pcfFilter->CodedCharSetId = MQCCSI_DEFAULT; pcfFilter->FilterValueLength = (MQLONG) value.length(); memcpy(pcfFilter->FilterValue, value.c_str(), pcfFilter->FilterValueLength); } void PCFParameters::addFilter(MQLONG parameter, MQLONG op, MQLONG value) { size_t pos = _buffer.size(); _pointers.insert(std::make_pair(parameter, pos)); _buffer.resize(_buffer.size() + MQCFIF_STRUC_LENGTH); MQCFIF* pcfFilter = (MQCFIF*) _buffer.data(pos); pcfFilter->Type = MQCFT_INTEGER_FILTER; pcfFilter->StrucLength = MQCFIF_STRUC_LENGTH; pcfFilter->Parameter = parameter; pcfFilter->Operator = op; pcfFilter->FilterValue = value; } PCFParameters PCFParameters::getGroup(MQLONG parameter, size_t pos) const { size_t realPos = 0; std::pair<ParameterPositionMap::const_iterator, ParameterPositionMap::const_iterator> range = _pointers.equal_range(parameter); size_t i = 0; for(ParameterPositionMap::const_iterator it = range.first; it != range.second; ++it, ++i) { if ( i == pos ) { realPos = it->second; break; } } if ( realPos == 0 ) { throw Poco::NotFoundException(parameter); } MQLONG *pcfType = (MQLONG*) _buffer.data(realPos); if ( *pcfType == MQCFT_GROUP ) { MQCFGR* pcfParam = (MQCFGR*) _buffer.data(realPos); PCFParameters group(_buffer); group.parse(pcfParam->ParameterCount, realPos + MQCFGR_STRUC_LENGTH); return group; } throw Poco::BadCastException(parameter); } std::string PCFParameters::getString(MQLONG parameter) const { ParameterPositionMap::const_iterator it = _pointers.find(parameter); if ( it == _pointers.end() ) throw Poco::NotFoundException(parameter); MQLONG *pcfType = (MQLONG*) _buffer.data(it->second); if ( *pcfType == MQCFT_STRING ) { MQCFST* pcfParam = (MQCFST*) _buffer.data(it->second); std::string result(pcfParam->String, pcfParam->StringLength); MQLONG length = pcfParam->StringLength -1; for(; length > 0 && (result[length] == '\0' || result[length] == ' '); \ length--); result.resize(length + 1); return result; } else if ( *pcfType == MQCFT_BYTE_STRING ) { MQCFBS* pcfParam = (MQCFBS*) _buffer.data(it->second); return Buffer((const MQBYTE*) pcfParam->String, pcfParam->StringLength).toHex(); } throw Poco::BadCastException(parameter); } Buffer::Ptr PCFParameters::getByteString(MQLONG parameter) const { ParameterPositionMap::const_iterator it = _pointers.find(parameter); if ( it == _pointers.end() ) throw Poco::NotFoundException(parameter); MQLONG *pcfType = (MQLONG*) _buffer.data(it->second); if ( *pcfType == MQCFT_BYTE_STRING ) { MQCFBS* pcfParam = (MQCFBS*) _buffer.data(it->second); return new Buffer(pcfParam->String, pcfParam->StringLength); } throw Poco::BadCastException(parameter); } std::string PCFParameters::optString(MQLONG parameter, const std::string& def) const { std::string result = def; try { result = getString(parameter); } catch(...) { } return result; } Poco::DateTime PCFParameters::getDate(MQLONG dateParameter, MQLONG timeParameter) const { std::string dateValue = getString(dateParameter); Poco::trimRightInPlace(dateValue); std::string timeValue = getString(timeParameter); Poco::trimRightInPlace(timeValue); dateValue += timeValue; if ( ! dateValue.empty() ) { Poco::DateTime dateTime; int timeZone; Poco::DateTimeParser::parse("%Y%n%e%H%M%S", dateValue, dateTime, timeZone); return dateTime; } return Poco::DateTime(); } MQLONG PCFParameters::getNumber(MQLONG parameter) const { ParameterPositionMap::const_iterator it = _pointers.find(parameter); if ( it == _pointers.end() ) throw Poco::NotFoundException(parameter); MQLONG *pcfType = (MQLONG*) _buffer.data(it->second); if ( *pcfType == MQCFT_INTEGER ) { MQCFIN* pcfParam = (MQCFIN*) _buffer.data(it->second); return pcfParam->Value; } throw Poco::BadCastException(parameter); } std::vector<MQLONG> PCFParameters::getNumberList(MQLONG parameter) const { ParameterPositionMap::const_iterator it = _pointers.find(parameter); if ( it == _pointers.end() ) throw Poco::NotFoundException(parameter); MQLONG *pcfType = (MQLONG*) _buffer.data(it->second); if ( *pcfType == MQCFT_INTEGER_LIST ) { std::vector<MQLONG> list; MQCFIL* pcfParam = (MQCFIL*) _buffer.data(it->second); for(int i = 0; i < pcfParam->Count; ++i) { list.push_back(pcfParam->Values[i]); } return list; } throw Poco::BadCastException(parameter); } std::vector<MQINT64> PCFParameters::getNumber64List(MQLONG parameter) const { ParameterPositionMap::const_iterator it = _pointers.find(parameter); if ( it == _pointers.end() ) throw Poco::NotFoundException(parameter); MQLONG *pcfType = (MQLONG*) _buffer.data(it->second); if ( *pcfType == MQCFT_INTEGER64_LIST ) { std::vector<MQINT64> list; MQCFIL64* pcfParam = (MQCFIL64*) _buffer.data(it->second); for(int i = 0; i < pcfParam->Count; ++i) { list.push_back(pcfParam->Values[i]); } return list; } throw Poco::BadCastException(parameter); } std::vector<std::string> PCFParameters::getStringList(MQLONG parameter) const { ParameterPositionMap::const_iterator it = _pointers.find(parameter); if ( it == _pointers.end() ) throw Poco::NotFoundException(parameter); MQLONG *pcfType = (MQLONG*) _buffer.data(it->second); if ( *pcfType == MQCFT_STRING_LIST ) { std::vector<std::string> list; MQCFSL* pcfParam = (MQCFSL*) _buffer.data(it->second); for(int i = 0; i < pcfParam->Count; ++i) { std::string result(pcfParam->Strings, i * pcfParam->StringLength, pcfParam->StringLength); Poco::trimRightInPlace(result); list.push_back(result); } return list; } throw Poco::BadCastException(parameter); } MQLONG PCFParameters::optNumber(MQLONG parameter, MQLONG def) const { MQLONG result = def; try { result = getNumber(parameter); } catch(...) { } return result; } std::vector<MQLONG> PCFParameters::getIds() const { std::vector<MQLONG> parameters; for(ParameterPositionMap::const_iterator it = _pointers.begin(); it != _pointers.end(); it++) { MQLONG *pcfType = (MQLONG*) _buffer.data(it->second); parameters.push_back(pcfType[2]); } return parameters; } void PCFParameters::parse(MQLONG parameterCount, size_t pos) { for(MQLONG i = 0; i < parameterCount; ++i) { MQLONG *pcfType = (MQLONG*) _buffer.data(pos); _pointers.insert(std::make_pair(pcfType[2], pos)); setNextPos(pcfType, pos); } } void PCFParameters::setNextPos(MQLONG* pcfType, size_t& pos) { if (*pcfType == MQCFT_GROUP) { pos += pcfType[1]; MQCFGR* pcfGroup = (MQCFGR*) pcfType; for(MQLONG i = 0; i < pcfGroup->ParameterCount; ++i) { setNextPos((MQLONG*) _buffer.data(pos), pos); } } else { pos += pcfType[1]; } } } // namespace MQ
/* * Copyright 2017 - KBC Group NV - Franky Braem - The MIT license * 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 <string.h> // For memcpy #include "Poco/String.h" #include "Poco/DateTimeParser.h" #include "MQ/PCFParameters.h" namespace MQ { PCFParameters::PCFParameters(Buffer& buffer) : _buffer(buffer) { } PCFParameters::PCFParameters(const PCFParameters& copy) : _buffer(copy._buffer), _pointers(copy._pointers) { } PCFParameters::~PCFParameters() { } void PCFParameters::add(MQLONG parameter, const std::string& value) { MQLONG structLength = ((MQCFST_STRUC_LENGTH_FIXED + (MQLONG) value.length()) / 4 + 1) * 4; size_t pos = _buffer.size(); _pointers.insert(std::make_pair(parameter, pos)); _buffer.resize(_buffer.size() + structLength); MQCFST* pcfParam = (MQCFST*) _buffer.data(pos); pcfParam->Type = MQCFT_STRING; pcfParam->StrucLength = structLength; pcfParam->Parameter = parameter; pcfParam->CodedCharSetId = MQCCSI_DEFAULT; pcfParam->StringLength = (MQLONG) value.length(); memcpy(pcfParam->String, value.c_str(), pcfParam->StringLength); } void PCFParameters::add(MQLONG parameter, MQLONG value) { size_t pos = _buffer.size(); _pointers.insert(std::make_pair(parameter, pos)); _buffer.resize(_buffer.size() + MQCFIN_STRUC_LENGTH); MQCFIN* pcfParam = (MQCFIN*) _buffer.data(pos); pcfParam->Type = MQCFT_INTEGER; pcfParam->StrucLength = MQCFIN_STRUC_LENGTH; pcfParam->Parameter = parameter; pcfParam->Value = value; } void PCFParameters::add(MQLONG parameter, Buffer::Ptr value) { size_t pos = _buffer.size(); _pointers.insert(std::make_pair(parameter, pos)); MQLONG structLength = ((MQCFST_STRUC_LENGTH_FIXED + (MQLONG) value->size()) / 4 + 1) * 4; _buffer.resize(_buffer.size() + structLength); MQCFBS* pcfParam = (MQCFBS*) _buffer.data(pos); pcfParam->Type = MQCFT_BYTE_STRING; pcfParam->StrucLength = structLength; pcfParam->Parameter = parameter; pcfParam->StringLength = (MQLONG) value->size(); memcpy(pcfParam->String, value->data(), pcfParam->StringLength); } void PCFParameters::addList(MQLONG parameter, MQLONG *values, unsigned int count) { size_t pos = _buffer.size(); int strucLength = MQCFIL_STRUC_LENGTH_FIXED + count * sizeof(MQLONG); _pointers.insert(std::make_pair(parameter, pos)); _buffer.resize(_buffer.size() + strucLength); MQCFIL *pcfIntegerList = (MQCFIL *) _buffer.data(pos); pcfIntegerList->Count = count; pcfIntegerList->Type = MQCFT_INTEGER_LIST; pcfIntegerList->StrucLength = strucLength; pcfIntegerList->Parameter = parameter; for(int i = 0; i < count; ++i) pcfIntegerList->Values[i] = values[i]; } void PCFParameters::addFilter(MQLONG parameter, MQLONG op, const std::string& value) { size_t pos = _buffer.size(); MQLONG strucLength = ((MQCFSF_STRUC_LENGTH_FIXED + (MQLONG) value.length()) / 4 + 1) * 4; _pointers.insert(std::make_pair(parameter, pos)); _buffer.resize(_buffer.size() + strucLength); MQCFSF* pcfFilter = (MQCFSF*) _buffer.data(pos); pcfFilter->Type = MQCFT_STRING_FILTER; pcfFilter->StrucLength = strucLength; pcfFilter->Parameter = parameter; pcfFilter->Operator = op; pcfFilter->CodedCharSetId = MQCCSI_DEFAULT; pcfFilter->FilterValueLength = (MQLONG) value.length(); memcpy(pcfFilter->FilterValue, value.c_str(), pcfFilter->FilterValueLength); } void PCFParameters::addFilter(MQLONG parameter, MQLONG op, MQLONG value) { size_t pos = _buffer.size(); _pointers.insert(std::make_pair(parameter, pos)); _buffer.resize(_buffer.size() + MQCFIF_STRUC_LENGTH); MQCFIF* pcfFilter = (MQCFIF*) _buffer.data(pos); pcfFilter->Type = MQCFT_INTEGER_FILTER; pcfFilter->StrucLength = MQCFIF_STRUC_LENGTH; pcfFilter->Parameter = parameter; pcfFilter->Operator = op; pcfFilter->FilterValue = value; } PCFParameters PCFParameters::getGroup(MQLONG parameter, size_t pos) const { size_t realPos = 0; std::pair<ParameterPositionMap::const_iterator, ParameterPositionMap::const_iterator> range = _pointers.equal_range(parameter); size_t i = 0; for(ParameterPositionMap::const_iterator it = range.first; it != range.second; ++it, ++i) { if ( i == pos ) { realPos = it->second; break; } } if ( realPos == 0 ) { throw Poco::NotFoundException(parameter); } MQLONG *pcfType = (MQLONG*) _buffer.data(realPos); if ( *pcfType == MQCFT_GROUP ) { MQCFGR* pcfParam = (MQCFGR*) _buffer.data(realPos); PCFParameters group(_buffer); group.parse(pcfParam->ParameterCount, realPos + MQCFGR_STRUC_LENGTH); return group; } throw Poco::BadCastException(parameter); } std::string PCFParameters::getString(MQLONG parameter) const { ParameterPositionMap::const_iterator it = _pointers.find(parameter); if ( it == _pointers.end() ) throw Poco::NotFoundException(parameter); MQLONG *pcfType = (MQLONG*) _buffer.data(it->second); if ( *pcfType == MQCFT_STRING ) { MQCFST* pcfParam = (MQCFST*) _buffer.data(it->second); std::string result(pcfParam->String, pcfParam->StringLength); MQLONG length = pcfParam->StringLength -1; while(length >= 0 && (result[length] == '\0' || result[length] == ' ')) length--; result.resize(length + 1); return result; } else if ( *pcfType == MQCFT_BYTE_STRING ) { MQCFBS* pcfParam = (MQCFBS*) _buffer.data(it->second); return Buffer((const MQBYTE*) pcfParam->String, pcfParam->StringLength).toHex(); } throw Poco::BadCastException(parameter); } Buffer::Ptr PCFParameters::getByteString(MQLONG parameter) const { ParameterPositionMap::const_iterator it = _pointers.find(parameter); if ( it == _pointers.end() ) throw Poco::NotFoundException(parameter); MQLONG *pcfType = (MQLONG*) _buffer.data(it->second); if ( *pcfType == MQCFT_BYTE_STRING ) { MQCFBS* pcfParam = (MQCFBS*) _buffer.data(it->second); return new Buffer(pcfParam->String, pcfParam->StringLength); } throw Poco::BadCastException(parameter); } std::string PCFParameters::optString(MQLONG parameter, const std::string& def) const { std::string result = def; try { result = getString(parameter); } catch(...) { } return result; } Poco::DateTime PCFParameters::getDate(MQLONG dateParameter, MQLONG timeParameter) const { std::string dateValue = getString(dateParameter); Poco::trimRightInPlace(dateValue); std::string timeValue = getString(timeParameter); Poco::trimRightInPlace(timeValue); dateValue += timeValue; if ( ! dateValue.empty() ) { Poco::DateTime dateTime; int timeZone; Poco::DateTimeParser::parse("%Y%n%e%H%M%S", dateValue, dateTime, timeZone); return dateTime; } return Poco::DateTime(); } MQLONG PCFParameters::getNumber(MQLONG parameter) const { ParameterPositionMap::const_iterator it = _pointers.find(parameter); if ( it == _pointers.end() ) throw Poco::NotFoundException(parameter); MQLONG *pcfType = (MQLONG*) _buffer.data(it->second); if ( *pcfType == MQCFT_INTEGER ) { MQCFIN* pcfParam = (MQCFIN*) _buffer.data(it->second); return pcfParam->Value; } throw Poco::BadCastException(parameter); } std::vector<MQLONG> PCFParameters::getNumberList(MQLONG parameter) const { ParameterPositionMap::const_iterator it = _pointers.find(parameter); if ( it == _pointers.end() ) throw Poco::NotFoundException(parameter); MQLONG *pcfType = (MQLONG*) _buffer.data(it->second); if ( *pcfType == MQCFT_INTEGER_LIST ) { std::vector<MQLONG> list; MQCFIL* pcfParam = (MQCFIL*) _buffer.data(it->second); for(int i = 0; i < pcfParam->Count; ++i) { list.push_back(pcfParam->Values[i]); } return list; } throw Poco::BadCastException(parameter); } std::vector<MQINT64> PCFParameters::getNumber64List(MQLONG parameter) const { ParameterPositionMap::const_iterator it = _pointers.find(parameter); if ( it == _pointers.end() ) throw Poco::NotFoundException(parameter); MQLONG *pcfType = (MQLONG*) _buffer.data(it->second); if ( *pcfType == MQCFT_INTEGER64_LIST ) { std::vector<MQINT64> list; MQCFIL64* pcfParam = (MQCFIL64*) _buffer.data(it->second); for(int i = 0; i < pcfParam->Count; ++i) { list.push_back(pcfParam->Values[i]); } return list; } throw Poco::BadCastException(parameter); } std::vector<std::string> PCFParameters::getStringList(MQLONG parameter) const { ParameterPositionMap::const_iterator it = _pointers.find(parameter); if ( it == _pointers.end() ) throw Poco::NotFoundException(parameter); MQLONG *pcfType = (MQLONG*) _buffer.data(it->second); if ( *pcfType == MQCFT_STRING_LIST ) { std::vector<std::string> list; MQCFSL* pcfParam = (MQCFSL*) _buffer.data(it->second); for(int i = 0; i < pcfParam->Count; ++i) { std::string result(pcfParam->Strings, i * pcfParam->StringLength, pcfParam->StringLength); Poco::trimRightInPlace(result); list.push_back(result); } return list; } throw Poco::BadCastException(parameter); } MQLONG PCFParameters::optNumber(MQLONG parameter, MQLONG def) const { MQLONG result = def; try { result = getNumber(parameter); } catch(...) { } return result; } std::vector<MQLONG> PCFParameters::getIds() const { std::vector<MQLONG> parameters; for(ParameterPositionMap::const_iterator it = _pointers.begin(); it != _pointers.end(); it++) { MQLONG *pcfType = (MQLONG*) _buffer.data(it->second); parameters.push_back(pcfType[2]); } return parameters; } void PCFParameters::parse(MQLONG parameterCount, size_t pos) { for(MQLONG i = 0; i < parameterCount; ++i) { MQLONG *pcfType = (MQLONG*) _buffer.data(pos); _pointers.insert(std::make_pair(pcfType[2], pos)); setNextPos(pcfType, pos); } } void PCFParameters::setNextPos(MQLONG* pcfType, size_t& pos) { if (*pcfType == MQCFT_GROUP) { pos += pcfType[1]; MQCFGR* pcfGroup = (MQCFGR*) pcfType; for(MQLONG i = 0; i < pcfGroup->ParameterCount; ++i) { setNextPos((MQLONG*) _buffer.data(pos), pos); } } else { pos += pcfType[1]; } } } // namespace MQ
Use while-loop and keep looping while length >= 0
Use while-loop and keep looping while length >= 0
C++
mit
fbraem/mqweb,fbraem/mqweb,fbraem/mqweb
82661736c199eaa9faa2c8a234efaa8916100823
opencog/atoms/core/RandomChoice.cc
opencog/atoms/core/RandomChoice.cc
/* * RandomChoice.cc * * Copyright (C) 2015 Linas Vepstas * * Author: Linas Vepstas <[email protected]> January 2009 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the * exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public * License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/atomspace/AtomSpace.h> #include <opencog/util/mt19937ar.h> #include "../NumberNode.h" #include "FunctionLink.h" #include "RandomChoice.h" using namespace opencog; static MT19937RandGen randy(43); RandomChoiceLink::RandomChoiceLink(const HandleSeq& oset, TruthValuePtr tv, AttentionValuePtr av) : FunctionLink(RANDOM_CHOICE_LINK, oset, tv, av) { } RandomChoiceLink::RandomChoiceLink(Link &l) : FunctionLink(l) { // Type must be as expected Type tscope = l.getType(); if (not classserver().isA(tscope, RANDOM_CHOICE_LINK)) { const std::string& tname = classserver().getTypeName(tscope); throw InvalidParamException(TRACE_INFO, "Expecting an RandomChoiceLink, got %s", tname.c_str()); } } // --------------------------------------------------------------- // When executed, this will randomly select and return an atom // in it's outgoing set. The selection can use either a uniform or // a weighted distribution. Two different formats are used to specify // weights; if neither of these are used, a uniform distribution is // used. // // One way to specify weights is to use a weight-vector: // // RandomChoiceLink // ListLink // NumberNode // ... // NumberNode // ListLink // AtomA // ... // AtomZ // // With the above format, the atoms A..Z will be selected with // distribution weights taken from the NumberNodes. The probability of // selection is in *proportion* to the weights; viz the probability is // given by dividing a given weight by the sum of the weights. // The Number of AtomsA..Z MUST match the number of NumberNodes! // // A second way to specify weights is much more GetLink friendly: // // RandomChoiceLink // SetLink // ListLink // NumberNode1 // AtomA // ListLink // NumberNode2 // AtomB // ... // ListLink // NumberNodeN // AtomZ // // Here, the weights and atoms are paired. The pairs appear in a // SetLink, which is an unordered link, and is the link type returned // by the GetLink query function. // // If neither of the above two formats appear to hold, then it is // assumed that the RandomChoiceLink simply holds a list of atoms; // these are selected with uniform weighting. Viz: // // RandomChoiceLink // AtomA // AtomB // ... // AtomZ // // or the GetLink-friendly format: // // RandomChoiceLink // SetLink // AtomA // AtomB // ... // AtomZ // Handle RandomChoiceLink::execute(AtomSpace * as) const { size_t ary = _outgoing.size(); if (0 == ary) return Handle(); // Special-case handling for SetLinks, so it works with // dynamically-evaluated PutLinks ... Type ot = _outgoing[0]->getType(); if (1 == ary and (SET_LINK == ot or LIST_LINK == ot)) { #if 0 // Already executed by the time we get here... !? // XXX FIXME: this is a situation where doing "eager" execution // is a bad idea. FunctionLinkPtr flp(FunctionLinkCast(_outgoing[0])); if (nullptr == flp) return _outgoing[0]; Handle h(flp->execute(as)); LinkPtr lll(LinkCast(h)); if (nullptr == lll) return h; #endif LinkPtr lll(LinkCast(_outgoing[0])); ary = lll->getArity(); return lll->getOutgoingAtom(randy.randint(ary)); } // Weighted choices cannot be sets, since sets are unordered. if (2 == ary and LIST_LINK == ot) { LinkPtr lweights(LinkCast(_outgoing[0])); LinkPtr lchoices(LinkCast(_outgoing[1])); if (lweights->getArity() != lchoices->getArity()) throw SyntaxException(TRACE_INFO, "Weights and choices must be the same size"); // Weights need to be numbers, or must evaluate to numbers. std::vector<double> weights; for (Handle h : lweights->getOutgoingSet()) { FunctionLinkPtr flp(FunctionLinkCast(h)); if (nullptr != flp) h = flp->execute(as); NumberNodePtr nn(NumberNodeCast(h)); if (nullptr == nn) throw SyntaxException(TRACE_INFO, "Expecting a NumberNode"); weights.push_back(nn->get_value()); } return lchoices->getOutgoingAtom(randy.randDiscrete(weights)); } return _outgoing.at(randy.randint(ary)); } /* ===================== END OF FILE ===================== */
/* * RandomChoice.cc * * Copyright (C) 2015 Linas Vepstas * * Author: Linas Vepstas <[email protected]> January 2009 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the * exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public * License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/atomspace/AtomSpace.h> #include <opencog/util/mt19937ar.h> #include "../NumberNode.h" #include "FunctionLink.h" #include "RandomChoice.h" using namespace opencog; static MT19937RandGen randy(43); RandomChoiceLink::RandomChoiceLink(const HandleSeq& oset, TruthValuePtr tv, AttentionValuePtr av) : FunctionLink(RANDOM_CHOICE_LINK, oset, tv, av) { } RandomChoiceLink::RandomChoiceLink(Link &l) : FunctionLink(l) { // Type must be as expected Type tscope = l.getType(); if (not classserver().isA(tscope, RANDOM_CHOICE_LINK)) { const std::string& tname = classserver().getTypeName(tscope); throw InvalidParamException(TRACE_INFO, "Expecting an RandomChoiceLink, got %s", tname.c_str()); } } // --------------------------------------------------------------- // When executed, this will randomly select and return an atom // in it's outgoing set. The selection can use either a uniform or // a weighted distribution. Two different formats are used to specify // weights; if neither of these are used, a uniform distribution is // used. // // One way to specify weights is to use a weight-vector: // // RandomChoiceLink // ListLink // NumberNode // ... // NumberNode // ListLink // AtomA // ... // AtomZ // // With the above format, the atoms A..Z will be selected with // distribution weights taken from the NumberNodes. The probability of // selection is in *proportion* to the weights; viz the probability is // given by dividing a given weight by the sum of the weights. // The Number of AtomsA..Z MUST match the number of NumberNodes! // // A second way to specify weights is much more GetLink friendly: // // RandomChoiceLink // SetLink // ListLink // NumberNode1 // AtomA // ListLink // NumberNode2 // AtomB // ... // ListLink // NumberNodeN // AtomZ // // Here, the weights and atoms are paired. The pairs appear in a // SetLink, which is an unordered link, and is the link type returned // by the GetLink query function. // // If neither of the above two formats appear to hold, then it is // assumed that the RandomChoiceLink simply holds a list of atoms; // these are selected with uniform weighting. Viz: // // RandomChoiceLink // AtomA // AtomB // ... // AtomZ // // or the GetLink-friendly format: // // RandomChoiceLink // SetLink // AtomA // AtomB // ... // AtomZ // Handle RandomChoiceLink::execute(AtomSpace * as) const { size_t ary = _outgoing.size(); if (0 == ary) return Handle(); // Special-case handling for SetLinks, so it works with // dynamically-evaluated PutLinks ... Type ot = _outgoing[0]->getType(); if (1 == ary and (SET_LINK == ot or LIST_LINK == ot)) { #if 0 // Already executed by the time we get here... !? // XXX FIXME: this is a situation where doing "eager" execution // is a bad idea. FunctionLinkPtr flp(FunctionLinkCast(_outgoing[0])); if (nullptr == flp) return _outgoing[0]; Handle h(flp->execute(as)); LinkPtr lll(LinkCast(h)); if (nullptr == lll) return h; #endif LinkPtr lll(LinkCast(_outgoing[0])); // Search for ListLink pairs, w/car of pair a number. HandleSeq choices; std::vector<double> weights; for (const Handle& h : lll->getOutgoingSet()) { if (LIST_LINK != h->getType()) goto uniform; LinkPtr lpair(LinkCast(h)); const HandleSeq& oset = lpair->getOutgoingSet(); if (2 != oset.size()) goto uniform; Handle hw = oset[0]; FunctionLinkPtr flp(FunctionLinkCast(hw)); if (nullptr != flp) hw = flp->execute(as); NumberNodePtr nn(NumberNodeCast(hw)); if (nullptr == nn) // goto uniform; throw SyntaxException(TRACE_INFO, "Expecting a NumberNode"); weights.push_back(nn->get_value()); choices.push_back(oset[1]); } return choices[randy.randDiscrete(weights)]; uniform: ary = lll->getArity(); return lll->getOutgoingAtom(randy.randint(ary)); } // Weighted choices cannot be sets, since sets are unordered. if (2 == ary and LIST_LINK == ot) { LinkPtr lweights(LinkCast(_outgoing[0])); LinkPtr lchoices(LinkCast(_outgoing[1])); if (lweights->getArity() != lchoices->getArity()) throw SyntaxException(TRACE_INFO, "Weights and choices must be the same size"); // Weights need to be numbers, or must evaluate to numbers. std::vector<double> weights; for (Handle h : lweights->getOutgoingSet()) { FunctionLinkPtr flp(FunctionLinkCast(h)); if (nullptr != flp) h = flp->execute(as); NumberNodePtr nn(NumberNodeCast(h)); if (nullptr == nn) throw SyntaxException(TRACE_INFO, "Expecting a NumberNode"); weights.push_back(nn->get_value()); } return lchoices->getOutgoingAtom(randy.randDiscrete(weights)); } return _outgoing.at(randy.randint(ary)); } /* ===================== END OF FILE ===================== */
Add weighted-pair code.
Add weighted-pair code.
C++
agpl-3.0
yantrabuddhi/atomspace,AmeBel/atomspace,ceefour/atomspace,ArvinPan/atomspace,inflector/atomspace,AmeBel/atomspace,inflector/atomspace,misgeatgit/atomspace,AmeBel/atomspace,inflector/atomspace,misgeatgit/atomspace,ArvinPan/atomspace,yantrabuddhi/atomspace,inflector/atomspace,yantrabuddhi/atomspace,rodsol/atomspace,rTreutlein/atomspace,inflector/atomspace,rodsol/atomspace,rTreutlein/atomspace,yantrabuddhi/atomspace,misgeatgit/atomspace,AmeBel/atomspace,ceefour/atomspace,rodsol/atomspace,ArvinPan/atomspace,ceefour/atomspace,rTreutlein/atomspace,rodsol/atomspace,yantrabuddhi/atomspace,misgeatgit/atomspace,rTreutlein/atomspace,misgeatgit/atomspace,ceefour/atomspace,rTreutlein/atomspace,AmeBel/atomspace,ArvinPan/atomspace
77d7b48d78c3442fec7861b7dd5e547d09cd1981
Sorting/strangesort.cpp
Sorting/strangesort.cpp
// quicksort #include "util.h" using namespace std; int len; namespace NP_STRANGESORT { void printArray(A ** array, int size) { for (int index = 0; index < size; index++) { array[index]->print(); // cout << array[index] << ' '; } cout << "\n"; } void indexSwap(A ** array, int index1, int index2) { A * tmp = array[index1]; // int tmp = array[index1]; array[index1] = array[index2]; array[index2] = tmp; } void SortFirstMiddleLast(A ** array, int loIndex, int midIndex, int hiIndex ) { A * low = array[loIndex]; // int low = array[loIndex]; A * mid = array[midIndex]; //int mid = array[midIndex]; A * hi = array[hiIndex]; //int hi = array[hiIndex]; // while ((low > mid) || (mid > hi)) { while ((*low > *mid) || (*mid > *hi)) { //if (low > mid) if (*low > *mid) indexSwap(array, loIndex, midIndex); //else if (mid > hi) else if (*mid > *hi) indexSwap(array, midIndex, hiIndex); //else if (low > hi) else if (*low > *hi) indexSwap(array, loIndex, hiIndex); //*low = *array[loIndex]; low = array[loIndex]; //*mid = *array[midIndex]; mid = array[midIndex]; //*hi = *array[hiIndex]; hi = array[hiIndex]; } } int partition(A ** array, int fromIndex, int toIndex) { int smallIndex = fromIndex - 1; //int pivot = array[toIndex]; A* pivot = array[toIndex]; for (int k = fromIndex; k < toIndex; k++) { // if (array[k] <= pivot) { if (*array[k] <= *pivot) { smallIndex++; indexSwap(array, k, smallIndex); } } indexSwap(array, toIndex, smallIndex + 1); cout << "Pivot = " << array[smallIndex + 1]->method() << "\n"; // cout << "Pivot = " << array[smallIndex + 1] << "\n"; printArray(array, len); return smallIndex + 1; } void insertionSort(A ** array, int fromIndex, int toIndex) { for (int cursor = fromIndex; cursor < toIndex; cursor++) { int secondCursor = cursor - 1; A * temp = array[cursor]; // int temp = array[cursor]; while (secondCursor >= 0 && *temp < *array[secondCursor]) { *array[secondCursor + 1] = *array[secondCursor]; secondCursor--; } /*while (secondCursor >= 0 && temp < array[secondCursor]) { array[secondCursor + 1] = array[secondCursor]; secondCursor--; }*/ *array[secondCursor + 1] = *temp; //array[secondCursor + 1] = temp; } } void strangeSort(A ** arr, int fromIndex, int toIndex) { if (fromIndex + 4 < toIndex) { SortFirstMiddleLast(arr, fromIndex, (fromIndex + toIndex) / 2, toIndex); int position = partition(arr, fromIndex, toIndex); strangeSort(arr, fromIndex, position - 1); strangeSort(arr, position + 1, toIndex); } else if (fromIndex < toIndex) { insertionSort(arr, fromIndex, toIndex); } } } using namespace NP_STRANGESORT; int main() { len = 10; A ** arr = new A*[len] { &B(9), &B(1), &B(2), &B(7), &B(5), &B(4), &B(8), &B(3), &B(6), &B(0) }; // cout << bool(B(4) < B(5)) << '\n'; // int * arr = new int[len] { 9, 1, 2, 7, 5, 4, 8, 3, 6, 0 }; cout << "Initial Array : "; printArray(arr, len); strangeSort(arr, 0, len - 1); cout << "Sorted Array : "; printArray(arr, len); cin.get(); return 0; }
// quicksort #include "util.h" using namespace std; int len; namespace NP_STRANGESORT { void printArray(A ** array, int size) { for (int index = 0; index < size; index++) { array[index]->print(); } cout << "\n"; } void indexSwap(A ** array, int index1, int index2) { A * tmp = array[index1]; array[index1] = array[index2]; array[index2] = tmp; } void SortFirstMiddleLast(A ** array, int loIndex, int midIndex, int hiIndex ) { A * low = array[loIndex]; A * mid = array[midIndex]; A * hi = array[hiIndex]; while ((*low > *mid) || (*mid > *hi)) { if (*low > *mid) indexSwap(array, loIndex, midIndex); else if (*mid > *hi) indexSwap(array, midIndex, hiIndex); else if (*low > *hi) indexSwap(array, loIndex, hiIndex); low = array[loIndex]; mid = array[midIndex]; hi = array[hiIndex]; } } int partition(A ** array, int fromIndex, int toIndex) { int smallIndex = fromIndex - 1; A* pivot = array[toIndex]; for (int k = fromIndex; k < toIndex; k++) { if (*array[k] <= *pivot) { smallIndex++; indexSwap(array, k, smallIndex); } } indexSwap(array, toIndex, smallIndex + 1); cout << "Pivot = " << array[smallIndex + 1]->method() << "\n"; printArray(array, len); return smallIndex + 1; } void insertionSort(A ** array, int fromIndex, int toIndex) { for (int cursor = fromIndex; cursor < toIndex; cursor++) { int secondCursor = cursor - 1; A * temp = array[cursor]; while (secondCursor >= 0 && *temp < *array[secondCursor]) { *array[secondCursor + 1] = *array[secondCursor]; secondCursor--; } *array[secondCursor + 1] = *temp; } } void strangeSort(A ** arr, int fromIndex, int toIndex) { if (fromIndex + 4 < toIndex) { SortFirstMiddleLast(arr, fromIndex, (fromIndex + toIndex) / 2, toIndex); int position = partition(arr, fromIndex, toIndex); strangeSort(arr, fromIndex, position - 1); strangeSort(arr, position + 1, toIndex); } else if (fromIndex < toIndex) { insertionSort(arr, fromIndex, toIndex); } } } using namespace NP_STRANGESORT; int main() { len = 10; A ** arr = new A*[len] { &B(9), &B(1), &B(2), &B(7), &B(5), &B(4), &B(8), &B(3), &B(6), &B(0) }; cout << "Initial Array : "; printArray(arr, len); strangeSort(arr, 0, len - 1); cout << "Sorted Array : "; printArray(arr, len); cin.get(); return 0; }
remove int comparison
remove int comparison
C++
mit
qwergram/CS133Assignment,qwergram/CS133Assignment
554d6990c201916cf2e1fcb47ce1ba6459ba08cc
runtime/cpp/Literals.hpp
runtime/cpp/Literals.hpp
#ifndef K3_RUNTIME_LITERALS_H #define K3_RUNTIME_LITERALS_H #include <list> #include <map> #include <memory> #include <string> #include <tuple> #include <vector> #include "boost/asio.hpp" #include "boost/fusion/include/std_pair.hpp" #include "boost/spirit/include/qi.hpp" namespace K3 { namespace qi = boost::spirit::qi; using boost::asio::ip::address; using std::begin; using std::end; using std::function; using std::list; using std::make_shared; using std::map; using std::pair; using std::shared_ptr; using std::string; using std::tuple; using std::vector; template <class iterator> class shallow: public qi::grammar<iterator, qi::space_type, string()> { public: shallow(): shallow::base_type(start) { start = qi::raw[indirection | option | angles | braces | parens | quotes | other]; indirection = qi::lit("ind") >> start; option = qi::lit("none") | qi::lit("some") >> start; angles = '<' >> *(qi::char_ - '>') >> '>'; braces = '{' >> *(qi::char_ - '}') >> '}'; brackets = '[' >> *(qi::char_ - ']') >> ']'; parens = '(' >> *(qi::char_ - ')') >> ')'; quotes = '"' >> *(escape - '"') >> '"'; other = *(qi::char_ - ','); escape = '\\' >> qi::char_ | qi::char_; } private: qi::rule<iterator, qi::space_type, string()> start; qi::rule<iterator, qi::space_type> indirection; qi::rule<iterator, qi::space_type> option; qi::rule<iterator, qi::space_type> angles; qi::rule<iterator, qi::space_type> braces; qi::rule<iterator, qi::space_type> brackets; qi::rule<iterator, qi::space_type> parens; qi::rule<iterator, qi::space_type> quotes; qi::rule<iterator, qi::space_type> other; qi::rule<iterator, qi::space_type> escape; }; template <class iterator> class literal: public qi::grammar<iterator, map<string, string>(), qi::space_type> { public: literal(): literal::base_type(start) { start = binding % ','; binding = key >> ':' >> value; key = qi::char_("a-zA-Z_") >> *qi::char_("a-zA-Z0-9_"); } private: qi::rule<iterator, map<string, string>(), qi::space_type> start; qi::rule<iterator, pair<string, string>(), qi::space_type> binding; qi::rule<iterator, string(), qi::space_type> key; shallow<iterator> value; }; // Built-in literal patchers. template <class T> struct patcher; template <class T, size_t i, size_t n> struct tuple_patcher; template <class T> struct patcher { static void patch(string, T&); }; template <> struct patcher<bool> { static void patch(string s, bool& b) { qi::parse(begin(s), end(s), qi::bool_[([&b] (bool q) { b = q; })]); } }; template <> struct patcher<int> { static void patch(string s, int& i) { qi::parse(begin(s), end(s), qi::int_[([&i] (int j) { i = j; })]); } }; template <> struct patcher<double> { static void patch(string s, double& d) { qi::parse(begin(s), end(s), qi::double_[([&d] (double f) { d = f; })]); } }; template <> struct patcher<string> { static void patch(string s, string& t) { string r; if (qi::parse(begin(s), end(s), ('"' >> *(('\\' >> qi::char_) | (qi::char_ - '"')) >> '"'), r)) { t = r; } } }; template <> struct patcher<unsigned short> { static void patch(string s, unsigned short& u) { qi::parse(std::begin(s), std::end(s), qi::ushort_, u); } }; template <> struct patcher<address> { static void patch(string s, address& a) { a = address::from_string(s); } }; template <class T> struct patcher<shared_ptr<T>> { static void patch(string s, shared_ptr<T> p) { shallow<string::iterator> _shallow; shared_ptr<T> tp = make_shared<T>(T()); qi::rule<string::iterator, qi::space_type> ind_rule = qi::lit("ind") >> _shallow[([&tp] (string t) { patcher<T>::patch(t, *tp); })]; qi::rule<string::iterator, qi::space_type> opt_rule = qi::lit("none")[([&p, &tp] () { tp = p = nullptr; })] | qi::lit("some") >> _shallow[([&tp] (string t) { patcher<T>::patch(t, *tp); })]; qi::phrase_parse(begin(s), end(s), ind_rule | opt_rule, qi::space); if (tp) { p = tp; } } }; template <class T> struct patcher<shared_ptr<list<T>>> { static void patch(string s, shared_ptr<list<T>>& p) { shallow<string::iterator> _shallow; list<T> lp; qi::rule<string::iterator, qi::space_type> item_rule = _shallow[([&lp] (string t) { lp.push_back(T()); patcher<T>::patch(t, lp.back()); })]; qi::rule<string::iterator, qi::space_type> list_rule = '[' >> (item_rule % ',') >> ']'; if (qi::phrase_parse(begin(s), end(s), list_rule, qi::space)) { p = make_shared<list<T>>(lp); } } }; template <class ... Ts> struct patcher<tuple<Ts...>> { static void patch(string s, tuple<Ts...>& t) { list<string> v; shallow<string::iterator> _shallow; qi::rule<string::iterator, qi::space_type, list<string>()> tuple_rule = '(' >> (_shallow % ',') >> ')'; qi::rule<string::iterator, qi::space_type, string()> ip_rule = qi::raw[(qi::int_ % '.')]; qi::rule<string::iterator, qi::space_type, string()> port_rule = qi::raw[qi::int_]; qi::rule<string::iterator, qi::space_type, list<string>()> address_rule = '<' >> ip_rule >> ':' >> port_rule >> '>'; qi::phrase_parse(begin(s), end(s), tuple_rule | address_rule, qi::space, v); tuple_patcher<tuple<Ts...>, 0, sizeof...(Ts)>::patch(v, t); } }; template <class T, size_t i> struct tuple_patcher<T, i, i> { static void patch(list<string>&, T&) {} }; template <class T, size_t i, size_t n> struct tuple_patcher { static void patch(list<string>& v, T& t) { if (v.empty()) { return; } patcher<typename std::tuple_element<i, T>::type>::patch(v.front(), std::get<i>(t)); v.pop_front(); tuple_patcher<T, i + 1, n>::patch(v, t); } }; template <template <class> class C, class E> struct collection_patcher { static void patch(string s, C<E>& c) { shared_ptr<list<E>> tmp_dsp = nullptr; patcher<shared_ptr<list<E>>>::patch(s, tmp_dsp); if (tmp_dsp) { C<E> new_c; for (E e: *tmp_dsp) { new_c.insert(e); } c = new_c; } } }; map<string, string> parse_bindings(string s) { map<string, string> bindings; literal<string::iterator> parser; qi::phrase_parse(begin(s), end(s), parser, qi::space, bindings); return bindings; } template <class T> void do_patch(string s, T& t) { patcher<T>::patch(s, t); } void match_patchers(map<string, string>& m, map<string, function<void(string)>>& f) { for (pair<string, string> p: m) { if (f.find(p.first) != end(f)) { f[p.first](p.second); } } } string preprocess_argv(int argc, char** argv) { if (argc < 2) return ""; return argv[1]; } } #endif
#ifndef K3_RUNTIME_LITERALS_H #define K3_RUNTIME_LITERALS_H #include <list> #include <map> #include <memory> #include <string> #include <tuple> #include <vector> #include "boost/asio.hpp" #include "boost/fusion/include/std_pair.hpp" #include "boost/spirit/include/qi.hpp" namespace K3 { namespace qi = boost::spirit::qi; using boost::asio::ip::address; using std::begin; using std::end; using std::function; using std::list; using std::make_shared; using std::map; using std::pair; using std::shared_ptr; using std::string; using std::tuple; using std::vector; template <class iterator> class shallow: public qi::grammar<iterator, qi::space_type, string()> { public: shallow(): shallow::base_type(start) { start = qi::raw[indirection | option | angles | braces | brackets | parens | quotes | other]; indirection = qi::lit("ind") >> start; option = qi::lit("none") | qi::lit("some") >> start; angles = '<' >> *(qi::char_ - '>') >> '>'; braces = '{' >> *(qi::char_ - '}') >> '}'; brackets = '[' >> *(qi::char_ - ']') >> ']'; parens = '(' >> *(qi::char_ - ')') >> ')'; quotes = '"' >> *(escape - '"') >> '"'; other = *(qi::char_ - ','); escape = '\\' >> qi::char_ | qi::char_; } private: qi::rule<iterator, qi::space_type, string()> start; qi::rule<iterator, qi::space_type> indirection; qi::rule<iterator, qi::space_type> option; qi::rule<iterator, qi::space_type> angles; qi::rule<iterator, qi::space_type> braces; qi::rule<iterator, qi::space_type> brackets; qi::rule<iterator, qi::space_type> parens; qi::rule<iterator, qi::space_type> quotes; qi::rule<iterator, qi::space_type> other; qi::rule<iterator, qi::space_type> escape; }; template <class iterator> class literal: public qi::grammar<iterator, map<string, string>(), qi::space_type> { public: literal(): literal::base_type(start) { start = binding % ','; binding = key >> ':' >> value; key = qi::char_("a-zA-Z_") >> *qi::char_("a-zA-Z0-9_"); } private: qi::rule<iterator, map<string, string>(), qi::space_type> start; qi::rule<iterator, pair<string, string>(), qi::space_type> binding; qi::rule<iterator, string(), qi::space_type> key; shallow<iterator> value; }; // Built-in literal patchers. template <class T> struct patcher; template <class T, size_t i, size_t n> struct tuple_patcher; template <class T> struct patcher { static void patch(string, T&); }; template <> struct patcher<bool> { static void patch(string s, bool& b) { qi::parse(begin(s), end(s), qi::bool_[([&b] (bool q) { b = q; })]); } }; template <> struct patcher<int> { static void patch(string s, int& i) { qi::parse(begin(s), end(s), qi::int_[([&i] (int j) { i = j; })]); } }; template <> struct patcher<double> { static void patch(string s, double& d) { qi::parse(begin(s), end(s), qi::double_[([&d] (double f) { d = f; })]); } }; template <> struct patcher<string> { static void patch(string s, string& t) { string r; if (qi::parse(begin(s), end(s), ('"' >> *(('\\' >> qi::char_) | (qi::char_ - '"')) >> '"'), r)) { t = r; } } }; template <> struct patcher<unsigned short> { static void patch(string s, unsigned short& u) { qi::parse(std::begin(s), std::end(s), qi::ushort_, u); } }; template <> struct patcher<address> { static void patch(string s, address& a) { a = address::from_string(s); } }; template <class T> struct patcher<shared_ptr<T>> { static void patch(string s, shared_ptr<T> p) { shallow<string::iterator> _shallow; shared_ptr<T> tp = make_shared<T>(T()); qi::rule<string::iterator, qi::space_type> ind_rule = qi::lit("ind") >> _shallow[([&tp] (string t) { patcher<T>::patch(t, *tp); })]; qi::rule<string::iterator, qi::space_type> opt_rule = qi::lit("none")[([&p, &tp] () { tp = p = nullptr; })] | qi::lit("some") >> _shallow[([&tp] (string t) { patcher<T>::patch(t, *tp); })]; qi::phrase_parse(begin(s), end(s), ind_rule | opt_rule, qi::space); if (tp) { p = tp; } } }; template <class T> struct patcher<shared_ptr<list<T>>> { static void patch(string s, shared_ptr<list<T>>& p) { shallow<string::iterator> _shallow; list<T> lp; qi::rule<string::iterator, qi::space_type> item_rule = _shallow[([&lp] (string t) { lp.push_back(T()); patcher<T>::patch(t, lp.back()); })]; qi::rule<string::iterator, qi::space_type> list_rule = '[' >> (item_rule % ',') >> ']'; if (qi::phrase_parse(begin(s), end(s), list_rule, qi::space)) { p = make_shared<list<T>>(lp); } } }; template <class ... Ts> struct patcher<tuple<Ts...>> { static void patch(string s, tuple<Ts...>& t) { list<string> v; shallow<string::iterator> _shallow; qi::rule<string::iterator, qi::space_type, list<string>()> tuple_rule = '(' >> (_shallow % ',') >> ')'; qi::rule<string::iterator, qi::space_type, string()> ip_rule = qi::raw[(qi::int_ % '.')]; qi::rule<string::iterator, qi::space_type, string()> port_rule = qi::raw[qi::int_]; qi::rule<string::iterator, qi::space_type, list<string>()> address_rule = '<' >> ip_rule >> ':' >> port_rule >> '>'; qi::phrase_parse(begin(s), end(s), tuple_rule | address_rule, qi::space, v); tuple_patcher<tuple<Ts...>, 0, sizeof...(Ts)>::patch(v, t); } }; template <class T, size_t i> struct tuple_patcher<T, i, i> { static void patch(list<string>&, T&) {} }; template <class T, size_t i, size_t n> struct tuple_patcher { static void patch(list<string>& v, T& t) { if (v.empty()) { return; } patcher<typename std::tuple_element<i, T>::type>::patch(v.front(), std::get<i>(t)); v.pop_front(); tuple_patcher<T, i + 1, n>::patch(v, t); } }; template <template <class> class C, class E> struct collection_patcher { static void patch(string s, C<E>& c) { shared_ptr<list<E>> tmp_dsp = nullptr; patcher<shared_ptr<list<E>>>::patch(s, tmp_dsp); if (tmp_dsp) { C<E> new_c; for (E e: *tmp_dsp) { new_c.insert(e); } c = new_c; } } }; map<string, string> parse_bindings(string s) { map<string, string> bindings; literal<string::iterator> parser; qi::phrase_parse(begin(s), end(s), parser, qi::space, bindings); return bindings; } template <class T> void do_patch(string s, T& t) { patcher<T>::patch(s, t); } void match_patchers(map<string, string>& m, map<string, function<void(string)>>& f) { for (pair<string, string> p: m) { if (f.find(p.first) != end(f)) { f[p.first](p.second); } } } string preprocess_argv(int argc, char** argv) { if (argc < 2) return ""; return argv[1]; } } #endif
Fix absence of square brackets in literal syntax.
Fix absence of square brackets in literal syntax.
C++
apache-2.0
DaMSL/K3,DaMSL/K3,yliu120/K3
cda07dafe57633439c67473f7c20b5f83316ba03
folly/futures/ThreadWheelTimekeeper.cpp
folly/futures/ThreadWheelTimekeeper.cpp
/* * Copyright 2017 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ThreadWheelTimekeeper.h" #include <folly/Singleton.h> #include <folly/futures/Future.h> #include <future> namespace folly { namespace { Singleton<ThreadWheelTimekeeper> timekeeperSingleton_; // Our Callback object for HHWheelTimer struct WTCallback : public std::enable_shared_from_this<WTCallback>, public folly::HHWheelTimer::Callback { public: // Only allow creation by this factory, to ensure heap allocation. static std::shared_ptr<WTCallback> create(EventBase* base) { // optimization opportunity: memory pool auto cob = std::shared_ptr<WTCallback>(new WTCallback(base)); // Capture shared_ptr of cob in lambda so that Core inside Promise will // hold a ref count to it. The ref count will be released when Core goes // away which happens when both Promise and Future go away cob->promise_->setInterruptHandler([cob](const folly::exception_wrapper&) { cob->interruptHandler(); }); return cob; } Future<Unit> getFuture() { return promise_->getFuture(); } void releasePromise() { // Don't need promise anymore. Break the circular reference as promise_ // is holding a ref count to us via Core. Core won't go away until both // Promise and Future go away. promise_.reset(); } protected: EventBase* base_; std::shared_ptr<Promise<Unit>> promise_; explicit WTCallback(EventBase* base) : base_(base) { promise_ = std::make_shared<Promise<Unit>>(); } void timeoutExpired() noexcept override { promise_->setValue(); // Don't need Promise anymore, break the circular reference releasePromise(); } void interruptHandler() { // Capture shared_ptr of self in lambda, if we don't do this, object // may go away before the lambda is executed from event base thread. // This is not racing with timeoutExpired anymore because this is called // through Future, which means Core is still alive and keeping a ref count // on us, so what timeouExpired is doing won't make the object go away auto me = shared_from_this(); base_->runInEventBaseThread([me] { me->cancelTimeout(); // Don't need Promise anymore, break the circular reference me->releasePromise(); }); } }; } // namespace ThreadWheelTimekeeper::ThreadWheelTimekeeper() : thread_([this] { eventBase_.loopForever(); }), wheelTimer_( HHWheelTimer::newTimer(&eventBase_, std::chrono::milliseconds(1))) { eventBase_.waitUntilRunning(); eventBase_.runInEventBaseThread([this]{ // 15 characters max eventBase_.setName("FutureTimekeepr"); }); } ThreadWheelTimekeeper::~ThreadWheelTimekeeper() { eventBase_.runInEventBaseThreadAndWait([this]{ wheelTimer_->cancelAll(); eventBase_.terminateLoopSoon(); }); thread_.join(); } Future<Unit> ThreadWheelTimekeeper::after(Duration dur) { auto cob = WTCallback::create(&eventBase_); auto f = cob->getFuture(); // // Even shared_ptr of cob is captured in lambda this is still somewhat *racy* // because it will be released once timeout is scheduled. So technically there // is no gurantee that EventBase thread can safely call timeout callback. // However due to fact that we are having circular reference here: // WTCallback->Promise->Core->WTCallbak, so three of them won't go away until // we break the circular reference. The break happens either in // WTCallback::timeoutExpired or WTCallback::interruptHandler. Former means // timeout callback is being safely executed. Latter captures shared_ptr of // WTCallback again in another lambda for canceling timeout. The moment // canceling timeout is executed in EventBase thread, the actual timeout // callback has either been executed, or will never be executed. So we are // fine here. // if (!eventBase_.runInEventBaseThread([this, cob, dur]{ wheelTimer_->scheduleTimeout(cob.get(), dur); })) { // Release promise to break the circular reference. Because if // scheduleTimeout fails, there is nothing to *promise*. Internally // Core would automatically set an exception result when Promise is // destructed before fulfilling. // This is either called from EventBase thread, or here. // They are somewhat racy but given the rare chance this could fail, // I don't see it is introducing any problem yet. cob->releasePromise(); } return f; } namespace detail { std::shared_ptr<Timekeeper> getTimekeeperSingleton() { return timekeeperSingleton_.try_get(); } } // namespace detail } // namespace folly
/* * Copyright 2017 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ThreadWheelTimekeeper.h" #include <folly/Singleton.h> #include <folly/futures/Future.h> #include <future> namespace folly { namespace { Singleton<ThreadWheelTimekeeper> timekeeperSingleton_; // Our Callback object for HHWheelTimer struct WTCallback : public std::enable_shared_from_this<WTCallback>, public folly::HHWheelTimer::Callback { struct PrivateConstructorTag {}; public: WTCallback(PrivateConstructorTag, EventBase* base) : base_(base) {} // Only allow creation by this factory, to ensure heap allocation. static std::shared_ptr<WTCallback> create(EventBase* base) { // optimization opportunity: memory pool auto cob = std::make_shared<WTCallback>(PrivateConstructorTag{}, base); // Capture shared_ptr of cob in lambda so that Core inside Promise will // hold a ref count to it. The ref count will be released when Core goes // away which happens when both Promise and Future go away cob->promise_.setInterruptHandler( [cob](const folly::exception_wrapper&) { cob->interruptHandler(); }); return cob; } Future<Unit> getFuture() { return promise_.getFuture(); } void releasePromise() { // Don't need promise anymore. Break the circular reference as promise_ // is holding a ref count to us via Core. Core won't go away until both // Promise and Future go away. promise_ = Promise<Unit>::makeEmpty(); } protected: EventBase* base_; Promise<Unit> promise_; void timeoutExpired() noexcept override { promise_.setValue(); // Don't need Promise anymore, break the circular reference releasePromise(); } void interruptHandler() { // Capture shared_ptr of self in lambda, if we don't do this, object // may go away before the lambda is executed from event base thread. // This is not racing with timeoutExpired anymore because this is called // through Future, which means Core is still alive and keeping a ref count // on us, so what timeouExpired is doing won't make the object go away base_->runInEventBaseThread([me = shared_from_this()] { me->cancelTimeout(); // Don't need Promise anymore, break the circular reference me->releasePromise(); }); } }; } // namespace ThreadWheelTimekeeper::ThreadWheelTimekeeper() : thread_([this] { eventBase_.loopForever(); }), wheelTimer_( HHWheelTimer::newTimer(&eventBase_, std::chrono::milliseconds(1))) { eventBase_.waitUntilRunning(); eventBase_.runInEventBaseThread([this]{ // 15 characters max eventBase_.setName("FutureTimekeepr"); }); } ThreadWheelTimekeeper::~ThreadWheelTimekeeper() { eventBase_.runInEventBaseThreadAndWait([this]{ wheelTimer_->cancelAll(); eventBase_.terminateLoopSoon(); }); thread_.join(); } Future<Unit> ThreadWheelTimekeeper::after(Duration dur) { auto cob = WTCallback::create(&eventBase_); auto f = cob->getFuture(); // // Even shared_ptr of cob is captured in lambda this is still somewhat *racy* // because it will be released once timeout is scheduled. So technically there // is no gurantee that EventBase thread can safely call timeout callback. // However due to fact that we are having circular reference here: // WTCallback->Promise->Core->WTCallbak, so three of them won't go away until // we break the circular reference. The break happens either in // WTCallback::timeoutExpired or WTCallback::interruptHandler. Former means // timeout callback is being safely executed. Latter captures shared_ptr of // WTCallback again in another lambda for canceling timeout. The moment // canceling timeout is executed in EventBase thread, the actual timeout // callback has either been executed, or will never be executed. So we are // fine here. // if (!eventBase_.runInEventBaseThread([this, cob, dur]{ wheelTimer_->scheduleTimeout(cob.get(), dur); })) { // Release promise to break the circular reference. Because if // scheduleTimeout fails, there is nothing to *promise*. Internally // Core would automatically set an exception result when Promise is // destructed before fulfilling. // This is either called from EventBase thread, or here. // They are somewhat racy but given the rare chance this could fail, // I don't see it is introducing any problem yet. cob->releasePromise(); } return f; } namespace detail { std::shared_ptr<Timekeeper> getTimekeeperSingleton() { return timekeeperSingleton_.try_get(); } } // namespace detail } // namespace folly
Remove a few memory allocations in ThreadWheelTimekeeper.after()
Remove a few memory allocations in ThreadWheelTimekeeper.after() Summary: This diff reduces number of memory allocation in folly::ThreadWheelTimekeeper.after() method for a bit. * std::shared_ptr(new T) is replaced with std::make_shared<T>() * folly::Promise is stored by value Reviewed By: yfeldblum Differential Revision: D6172017 fbshipit-source-id: 41bf123f10570c76d64eaac1800b7e65fe381110
C++
apache-2.0
Orvid/folly,rklabs/folly,rklabs/folly,facebook/folly,Orvid/folly,rklabs/folly,rklabs/folly,Orvid/folly,facebook/folly,Orvid/folly,Orvid/folly,facebook/folly,rklabs/folly,facebook/folly,facebook/folly
161a263acf187f613e54d6f82e997b39856df96e
src/lib/convenience/RegisterProviderRequest.cpp
src/lib/convenience/RegisterProviderRequest.cpp
/* * * Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Orion Context Broker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero * General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * iot_support at tid dot es * * Author: Ken Zangelin */ #include <stdio.h> #include <string> #include <vector> #include "logMsg/logMsg.h" #include "logMsg/traceLevels.h" #include "common/globals.h" #include "common/Format.h" #include "common/tag.h" #include "convenience/RegisterProviderRequest.h" #include "ngsi/StatusCode.h" #include "ngsi/MetadataVector.h" #include "ngsi/Duration.h" #include "ngsi/ProvidingApplication.h" #include "ngsi/RegistrationId.h" #include "ngsi9/DiscoverContextAvailabilityResponse.h" /* **************************************************************************** * * Constructor - */ RegisterProviderRequest::RegisterProviderRequest() { } /* **************************************************************************** * * RegisterProviderRequest::render - */ std::string RegisterProviderRequest::render(Format format, std::string indent) { std::string out = ""; std::string xmlTag = "registerProviderRequest"; bool durationRendered = duration.get() != ""; bool providingApplicationRendered = providingApplication.get() != ""; bool registrationIdRendered = registrationId.get() != ""; bool commaAfterRegistrationId = false; // Last element bool commaAfterProvidingApplication = registrationIdRendered; bool commaAfterDuration = commaAfterProvidingApplication || providingApplicationRendered; bool commaAfterMetadataVector = commaAfterDuration || durationRendered; out += startTag(indent, xmlTag, "", format, false, false); out += metadataVector.render(format, indent + " ", commaAfterMetadataVector); out += duration.render(format, indent + " ", commaAfterDuration); out += providingApplication.render(format, indent + " ", commaAfterProvidingApplication); out += registrationId.render(RegisterContext, format, indent + " ", commaAfterRegistrationId); out += endTag(indent, xmlTag, format, false); return out; } /* **************************************************************************** * * RegisterProviderRequest::check - */ std::string RegisterProviderRequest::check ( RequestType requestType, Format format, std::string indent, std::string predetectedError, int counter ) { DiscoverContextAvailabilityResponse response; std::string res; if (predetectedError != "") { response.errorCode.fill(SccBadRequest, predetectedError); } else if (((res = metadataVector.check(requestType, format, indent, "", counter)) != "OK") || ((res = duration.check(requestType, format, indent, "", 0)) != "OK") || ((res = providingApplication.check(requestType, format, indent, "", 0)) != "OK") || ((res = registrationId.check(requestType, format, indent, "", 0)) != "OK")) { response.errorCode.fill(SccBadRequest, res); } else { return "OK"; } LM_W(("Bad Input (RegisterProviderRequest Error: %s)", res.c_str())); return response.render(DiscoverContextAvailability, format, indent); } /* **************************************************************************** * * RegisterProviderRequest::present - */ void RegisterProviderRequest::present(std::string indent) { PRINTF("%sRegisterProviderRequest:\n", indent.c_str()); metadataVector.present("Registration", indent + " "); duration.present(indent + " "); providingApplication.present(indent + " "); registrationId.present(indent + " "); PRINTF("\n"); } /* **************************************************************************** * * RegisterProviderRequest::release - */ void RegisterProviderRequest::release(void) { metadataVector.release(); }
/* * * Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Orion Context Broker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero * General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * iot_support at tid dot es * * Author: Ken Zangelin */ #include <stdio.h> #include <string> #include <vector> #include "logMsg/logMsg.h" #include "logMsg/traceLevels.h" #include "common/globals.h" #include "common/Format.h" #include "common/tag.h" #include "convenience/RegisterProviderRequest.h" #include "ngsi/StatusCode.h" #include "ngsi/MetadataVector.h" #include "ngsi/Duration.h" #include "ngsi/ProvidingApplication.h" #include "ngsi/RegistrationId.h" #include "ngsi9/DiscoverContextAvailabilityResponse.h" /* **************************************************************************** * * Constructor - */ RegisterProviderRequest::RegisterProviderRequest() { } /* **************************************************************************** * * RegisterProviderRequest::render - */ std::string RegisterProviderRequest::render(Format format, std::string indent) { std::string out = ""; std::string xmlTag = "registerProviderRequest"; bool durationRendered = duration.get() != ""; bool providingApplicationRendered = providingApplication.get() != ""; bool registrationIdRendered = registrationId.get() != ""; bool commaAfterRegistrationId = false; // Last element bool commaAfterProvidingApplication = registrationIdRendered; bool commaAfterDuration = commaAfterProvidingApplication || providingApplicationRendered; bool commaAfterMetadataVector = commaAfterDuration || durationRendered; out += startTag(indent, xmlTag, "", format, false, false); out += metadataVector.render(format, indent + " ", commaAfterMetadataVector); out += duration.render(format, indent + " ", commaAfterDuration); out += providingApplication.render(format, indent + " ", commaAfterProvidingApplication); out += registrationId.render(RegisterContext, format, indent + " ", commaAfterRegistrationId); out += endTag(indent, xmlTag, format, false); return out; } /* **************************************************************************** * * RegisterProviderRequest::check - */ std::string RegisterProviderRequest::check ( RequestType requestType, Format format, std::string indent, std::string predetectedError, int counter ) { DiscoverContextAvailabilityResponse response; std::string res; if (predetectedError != "") { response.errorCode.fill(SccBadRequest, predetectedError); } else if (((res = metadataVector.check(requestType, format, indent, "", counter)) != "OK") || ((res = duration.check(requestType, format, indent, "", 0)) != "OK") || ((res = providingApplication.check(requestType, format, indent, "", 0)) != "OK") || ((res = registrationId.check(requestType, format, indent, "", 0)) != "OK")) { response.errorCode.fill(SccBadRequest, res); } else { return "OK"; } LM_W(("Bad Input (RegisterProviderRequest Error: %s)", res.c_str())); return response.render(DiscoverContextAvailability, format, indent); } /* **************************************************************************** * * RegisterProviderRequest::present - */ void RegisterProviderRequest::present(std::string indent) { LM_F(("%sRegisterProviderRequest:\n", indent.c_str())); metadataVector.present("Registration", indent + " "); duration.present(indent + " "); providingApplication.present(indent + " "); registrationId.present(indent + " "); LM_F(("\n")); } /* **************************************************************************** * * RegisterProviderRequest::release - */ void RegisterProviderRequest::release(void) { metadataVector.release(); }
Remove PRINTF macro
Remove PRINTF macro
C++
agpl-3.0
telefonicaid/fiware-orion,Fiware/context.Orion,Fiware/data.Orion,jmcanterafonseca/fiware-orion,Fiware/context.Orion,Fiware/context.Orion,jmcanterafonseca/fiware-orion,guerrerocarlos/fiware-orion,telefonicaid/fiware-orion,telefonicaid/fiware-orion,telefonicaid/fiware-orion,gavioto/fiware-orion,Fiware/context.Orion,jmcanterafonseca/fiware-orion,gavioto/fiware-orion,Fiware/context.Orion,McMutton/fiware-orion,fiwareulpgcmirror/fiware-orion,pacificIT/fiware-orion,McMutton/fiware-orion,McMutton/fiware-orion,jmcanterafonseca/fiware-orion,jmcanterafonseca/fiware-orion,guerrerocarlos/fiware-orion,pacificIT/fiware-orion,Fiware/data.Orion,jmcanterafonseca/fiware-orion,j1fig/fiware-orion,yalp/fiware-orion,j1fig/fiware-orion,yalp/fiware-orion,gavioto/fiware-orion,guerrerocarlos/fiware-orion,pacificIT/fiware-orion,fiwareulpgcmirror/fiware-orion,telefonicaid/fiware-orion,j1fig/fiware-orion,j1fig/fiware-orion,Fiware/data.Orion,pacificIT/fiware-orion,fiwareulpgcmirror/fiware-orion,guerrerocarlos/fiware-orion,Fiware/data.Orion,fortizc/fiware-orion,gavioto/fiware-orion,j1fig/fiware-orion,yalp/fiware-orion,McMutton/fiware-orion,yalp/fiware-orion,McMutton/fiware-orion,Fiware/data.Orion,fiwareulpgcmirror/fiware-orion,fortizc/fiware-orion,fortizc/fiware-orion,fiwareulpgcmirror/fiware-orion,telefonicaid/fiware-orion,fortizc/fiware-orion,fortizc/fiware-orion,yalp/fiware-orion,McMutton/fiware-orion,guerrerocarlos/fiware-orion,Fiware/context.Orion,Fiware/data.Orion,McMutton/fiware-orion,pacificIT/fiware-orion,gavioto/fiware-orion,fiwareulpgcmirror/fiware-orion,fortizc/fiware-orion
0e947458cca146b4245cf3aeb1b79c2e3f4ca228
sceneGraph/glc_world.cpp
sceneGraph/glc_world.cpp
/**************************************************************************** This file is part of the GLC-lib library. Copyright (C) 2005-2008 Laurent Ribon ([email protected]) Version 1.2.0, packaged on September 2009. http://glc-lib.sourceforge.net GLC-lib 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. GLC-lib 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 GLC-lib; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ //! \file glc_world.cpp implementation of the GLC_World class. #include "glc_world.h" #include "glc_structinstance.h" #include "glc_structreference.h" // Default constructor GLC_World::GLC_World() : m_pWorldHandle(new GLC_WorldHandle()) , m_pRoot(new GLC_StructOccurence(m_pWorldHandle, (new GLC_StructReference())->createStructInstance())) { //qDebug() << "GLC_World::GLC_World() : " << (*m_pNumberOfWorld) << " " << this; } // Copy constructor GLC_World::GLC_World(const GLC_World& world) : m_pWorldHandle(world.m_pWorldHandle) , m_pRoot(world.m_pRoot) { //qDebug() << "GLC_World::GLC_World() : " << (*m_pNumberOfWorld) << " " << this; // Increment the number of world m_pWorldHandle->increment(); } GLC_World::~GLC_World() { // Decrement the number of world m_pWorldHandle->decrement(); //qDebug() << "GLC_World::GLC_World() : " << (*m_pNumberOfWorld) << " " << this; if (m_pWorldHandle->isOrphan()) { // this is the last World, delete the root product and collection //m_pWorldHandle->collection()->clear(); // Clear collection first (performance) delete m_pRoot; delete m_pWorldHandle; } } // Merge this world with another world void GLC_World::mergeWithAnotherWorld(GLC_World& anotherWorld) { qDebug() << "GLC_World::mergeWithAnotherWorld"; GLC_StructOccurence* pAnotherRoot= anotherWorld.rootOccurence(); if (pAnotherRoot->childCount() > 0) { QList<GLC_StructOccurence*> childs= pAnotherRoot->children(); const int size= childs.size(); for (int i= 0; i < size; ++i) { m_pRoot->addChild(childs.at(i)->clone(m_pWorldHandle, true)); } m_pRoot->updateChildrenAbsoluteMatrix(); } else { m_pRoot->addChild(anotherWorld.rootOccurence()->clone(m_pWorldHandle, true)); } } // Assignment operator GLC_World& GLC_World::operator=(const GLC_World& world) { // Decrement the number of world m_pWorldHandle->decrement(); if (m_pWorldHandle->isOrphan()) { // this is the last World, delete the root product and collection //m_pWorldHandle->collection()->clear(); // Clear collection first (performance) delete m_pRoot; delete m_pWorldHandle; } m_pRoot= world.m_pRoot; m_pWorldHandle= world.m_pWorldHandle; m_pWorldHandle->increment(); return *this; }
/**************************************************************************** This file is part of the GLC-lib library. Copyright (C) 2005-2008 Laurent Ribon ([email protected]) Version 1.2.0, packaged on September 2009. http://glc-lib.sourceforge.net GLC-lib 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. GLC-lib 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 GLC-lib; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ //! \file glc_world.cpp implementation of the GLC_World class. #include "glc_world.h" #include "glc_structinstance.h" #include "glc_structreference.h" // Default constructor GLC_World::GLC_World() : m_pWorldHandle(new GLC_WorldHandle()) , m_pRoot(new GLC_StructOccurence()) { m_pRoot->setWorldHandle(m_pWorldHandle); //qDebug() << "GLC_World::GLC_World() : " << (*m_pNumberOfWorld) << " " << this; } // Copy constructor GLC_World::GLC_World(const GLC_World& world) : m_pWorldHandle(world.m_pWorldHandle) , m_pRoot(world.m_pRoot) { //qDebug() << "GLC_World::GLC_World() : " << (*m_pNumberOfWorld) << " " << this; // Increment the number of world m_pWorldHandle->increment(); } GLC_World::~GLC_World() { // Decrement the number of world m_pWorldHandle->decrement(); //qDebug() << "GLC_World::GLC_World() : " << (*m_pNumberOfWorld) << " " << this; if (m_pWorldHandle->isOrphan()) { // this is the last World, delete the root product and collection //m_pWorldHandle->collection()->clear(); // Clear collection first (performance) delete m_pRoot; delete m_pWorldHandle; } } // Merge this world with another world void GLC_World::mergeWithAnotherWorld(GLC_World& anotherWorld) { qDebug() << "GLC_World::mergeWithAnotherWorld"; GLC_StructOccurence* pAnotherRoot= anotherWorld.rootOccurence(); if (pAnotherRoot->childCount() > 0) { QList<GLC_StructOccurence*> childs= pAnotherRoot->children(); const int size= childs.size(); for (int i= 0; i < size; ++i) { m_pRoot->addChild(childs.at(i)->clone(m_pWorldHandle, true)); } m_pRoot->updateChildrenAbsoluteMatrix(); } else { m_pRoot->addChild(anotherWorld.rootOccurence()->clone(m_pWorldHandle, true)); } } // Assignment operator GLC_World& GLC_World::operator=(const GLC_World& world) { if (this != &world) { // Decrement the number of world m_pWorldHandle->decrement(); if (m_pWorldHandle->isOrphan()) { // this is the last World, delete the root product and collection //m_pWorldHandle->collection()->clear(); // Clear collection first (performance) delete m_pRoot; delete m_pWorldHandle; } m_pRoot= world.m_pRoot; m_pWorldHandle= world.m_pWorldHandle; m_pWorldHandle->increment(); } return *this; }
Use the new interface of GLC_Struct.. classes.
Use the new interface of GLC_Struct.. classes.
C++
lgpl-2.1
3drepo/GLC_lib
74b02b781d20e6e009927ee9e6844f29673aac9c
src/userspace/console_user_server/console_user_server/include/receiver.hpp
src/userspace/console_user_server/console_user_server/include/receiver.hpp
#pragma once #include "constants.hpp" #include "local_datagram_server.hpp" class receiver final { public: void start(void) { try { const char* path = constants::get_console_user_socket_file_path(); unlink(path); server_ = std::make_unique<local_datagram_server>(path); chmod(path, 0600); thread_ = std::thread([this] { this->worker(); }); } catch (...) { std::cout << "default exception"; } } void stop(void) { if (!thread_.joinable()) { return; } if (!server_) { return; } server_->get_socket().cancel(); thread_.join(); server_.reset(nullptr); } void worker(void) { for (;;) { if (!server_) { break; } boost::system::error_code ec; std::size_t n = server_->receive(boost::asio::buffer(buffer_), boost::posix_time::seconds(1), ec); if (ec) { std::cout << "Receive error: " << ec.message() << "\n"; } else { std::cout << n << std::endl; } } } private: enum { buffer_length = 8 * 1024, }; std::array<uint8_t, buffer_length> buffer_; std::unique_ptr<local_datagram_server> server_; std::thread thread_; };
#pragma once #include "constants.hpp" #include "local_datagram_server.hpp" class receiver final { public: receiver(void) : exit_loop_(false) {} void start(void) { if (server_) { return; } const char* path = constants::get_console_user_socket_file_path(); unlink(path); server_ = std::make_unique<local_datagram_server>(path); chmod(path, 0600); thread_ = std::thread([this] { this->worker(); }); } void stop(void) { if (!thread_.joinable()) { return; } if (!server_) { return; } exit_loop_ = true; thread_.join(); server_.reset(nullptr); } void worker(void) { if (!server_) { return; } while (!exit_loop_) { boost::system::error_code ec; std::size_t n = server_->receive(boost::asio::buffer(buffer_), boost::posix_time::seconds(1), ec); if (ec) { std::cout << "Receive error: " << ec.message() << "\n"; } else { std::cout << n << std::endl; } } } private: enum { buffer_length = 8 * 1024, }; std::array<uint8_t, buffer_length> buffer_; std::unique_ptr<local_datagram_server> server_; std::thread thread_; volatile bool exit_loop_; };
add exit_loop_
add exit_loop_
C++
unlicense
jgosmann/Karabiner-Elements-Neo,epegzz/Karabiner-Elements,tekezo/Karabiner-Elements,jgosmann/Karabiner-Elements-Neo,tekezo/Karabiner-Elements,tekezo/Karabiner-Elements,epegzz/Karabiner-Elements,epegzz/Karabiner-Elements,jrolfs/Karabiner-Elements,jgosmann/Karabiner-Elements-Neo,jrolfs/Karabiner-Elements,jrolfs/Karabiner-Elements,jrolfs/Karabiner-Elements,epegzz/Karabiner-Elements,jgosmann/Karabiner-Elements-Neo,tekezo/Karabiner-Elements
745cdce3de0a1010ed888485bfa32debc0842d9d
velib/include/vdb/vhdfsdb.hpp
velib/include/vdb/vhdfsdb.hpp
#ifndef __V_HDFS_DB_HPP__ #define __V_HDFS_DB_HPP__ #include "utility.hpp" #include "debug.hpp" #include "videotype.hpp" using namespace UtilityLib; class HdfsRecSession; class VHdfsDBData; class HdfsRecWrapper; class VE_LIBRARY_API VHdfsDB { public: typedef std::map<s32, HdfsRecSession*> _MapSession; public: VHdfsDB(astring &pNameNode, astring &pPort, astring &pUser); ~VHdfsDB(); public: void Lock(); void UnLock(); public: BOOL Config(astring &pNameNode, astring &pPort, astring &pUser); public: /* Start and Stop Record */ HdfsRecSession * StartRecord(s32 deviceId, astring strName); BOOL FinishRecord(HdfsRecSession *pSess); public: HdfsRecWrapper & GetHdfsRecWrapper(); BOOL ReleaseHdfsRecWrapper(); private: fast_mutex m_Lock; _MapSession m_MapSess; VHdfsDBData * m_data; astring m_pNameNode; astring m_pPort; astring m_pUser; }; #endif /* __V_HDFS_DB_HPP__ */
#ifndef __V_HDFS_DB_HPP__ #define __V_HDFS_DB_HPP__ #include "utility.hpp" #include "debug.hpp" #include "videotype.hpp" using namespace UtilityLib; class HdfsRecSession; class VHdfsDBData; class HdfsRecWrapper; class VE_LIBRARY_API VHdfsDB { public: typedef std::map<s32, HdfsRecSession*> _MapSession; public: VHdfsDB(astring &pNameNode, astring &pPort, astring &pUser); ~VHdfsDB(); public: void Lock(); void UnLock(); public: BOOL Config(astring &pNameNode, astring &pPort, astring &pUser); public: /* Start and Stop Record */ HdfsRecSession * StartRecord(s32 deviceId, astring strName); BOOL FinishRecord(HdfsRecSession *pSess); public: HdfsRecWrapper & GetHdfsRecWrapper(); BOOL ReleaseHdfsRecWrapper(); s32 GetInerval() { return m_inerval; } private: fast_mutex m_Lock; _MapSession m_MapSess; VHdfsDBData * m_data; astring m_pNameNode; astring m_pPort; astring m_pUser; s32 m_inerval;/*time in sec */ }; #endif /* __V_HDFS_DB_HPP__ */
update hdfs db
update hdfs db
C++
mit
xsmart/opencvr,telecamera/opencvr,herocodemaster/opencvr,herocodemaster/opencvr,veyesys/opencvr,xsmart/opencvr,herocodemaster/opencvr,veyesys/opencvr,xsmart/opencvr,xiaojuntong/opencvr,veyesys/opencvr,xiaojuntong/opencvr,herocodemaster/opencvr,xsmart/opencvr,xsmart/opencvr,telecamera/opencvr,telecamera/opencvr,xiaojuntong/opencvr,telecamera/opencvr,veyesys/opencvr,xiaojuntong/opencvr,veyesys/opencvr
789188aa6d54859c11ed657e9b1c444fbb29cdcd
RawSpeed/TiffEntryBE.cpp
RawSpeed/TiffEntryBE.cpp
#include "StdAfx.h" #include "TiffEntryBE.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009 Klaus Post This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ namespace RawSpeed { TiffEntryBE::TiffEntryBE(FileMap* f, uint32 offset) : mDataSwapped(false) { type = TIFF_UNDEFINED; // We set type to undefined to avoid debug assertion errors. data = f->getDataWrt(offset); tag = (TiffTag)getShort(); data += 2; TiffDataType _type = (TiffDataType)getShort(); data += 2; count = getInt(); type = _type; //Now we can set it to the proper type if (type > 13) ThrowTPE("Error reading TIFF structure. Unknown Type 0x%x encountered.", type); uint32 bytesize = count << datashifts[type]; if (bytesize <= 4) { data = f->getDataWrt(offset + 8); } else { // offset data = f->getDataWrt(offset + 8); uint32 data_offset = (unsigned int)data[0] << 24 | (unsigned int)data[1] << 16 | (unsigned int)data[2] << 8 | (unsigned int)data[3]; CHECKSIZE(data_offset + bytesize); data = f->getDataWrt(data_offset); } #ifdef _DEBUG debug_intVal = 0xC0CAC01A; debug_floatVal = sqrtf(-1); if (type == TIFF_LONG || type == TIFF_SHORT) debug_intVal = getInt(); if (type == TIFF_FLOAT || type == TIFF_DOUBLE) debug_floatVal = getFloat(); #endif } TiffEntryBE::~TiffEntryBE(void) { } unsigned int TiffEntryBE::getInt() { if (!(type == TIFF_LONG || type == TIFF_SHORT || type == TIFF_UNDEFINED)) ThrowTPE("TIFF, getInt: Wrong type 0x%x encountered. Expected Int", type); if (type == TIFF_SHORT) return getShort(); return (unsigned int)data[0] << 24 | (unsigned int)data[1] << 16 | (unsigned int)data[2] << 8 | (unsigned int)data[3]; } unsigned short TiffEntryBE::getShort() { if (!(type == TIFF_SHORT || type == TIFF_UNDEFINED)) ThrowTPE("TIFF, getShort: Wrong type 0x%x encountered. Expected Short", type); return (unsigned short)data[0] << 8 | (unsigned short)data[1]; } const unsigned int* TiffEntryBE::getIntArray() { //TODO: Make critical section to avoid clashes. if (!(type == TIFF_LONG || type == TIFF_UNDEFINED || type == TIFF_RATIONAL || type == TIFF_SRATIONAL)) ThrowTPE("TIFF, getIntArray: Wrong type 0x%x encountered. Expected Int", type); if (mDataSwapped) return (unsigned int*)&data[0]; unsigned int* d = (unsigned int*) & data[0]; for (uint32 i = 0; i < count; i++) { d[i] = (unsigned int)data[i*4+0] << 24 | (unsigned int)data[i*4+1] << 16 | (unsigned int)data[i*4+2] << 8 | (unsigned int)data[i*4+3]; } mDataSwapped = true; return d; } const unsigned short* TiffEntryBE::getShortArray() { //TODO: Make critical section to avoid clashes. if (!(type == TIFF_SHORT || type == TIFF_UNDEFINED)) ThrowTPE("TIFF, getShortArray: Wrong type 0x%x encountered. Expected Short", type); if (mDataSwapped) return (unsigned short*)&data[0]; unsigned short* d = (unsigned short*) & data[0]; for (uint32 i = 0; i < count; i++) { d[i] = (unsigned short)data[i*2+0] << 8 | (unsigned short)data[i*2+1]; } mDataSwapped = true; return d; } } // namespace RawSpeed
#include "StdAfx.h" #include "TiffEntryBE.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009 Klaus Post This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ namespace RawSpeed { TiffEntryBE::TiffEntryBE(FileMap* f, uint32 offset) : mDataSwapped(false) { type = TIFF_UNDEFINED; // We set type to undefined to avoid debug assertion errors. data = f->getDataWrt(offset); tag = (TiffTag)getShort(); data += 2; TiffDataType _type = (TiffDataType)getShort(); data += 2; count = getInt(); type = _type; //Now we can set it to the proper type if (type > 13) ThrowTPE("Error reading TIFF structure. Unknown Type 0x%x encountered.", type); uint32 bytesize = count << datashifts[type]; if (bytesize <= 4) { data = f->getDataWrt(offset + 8); } else { // offset data = f->getDataWrt(offset + 8); data_offset = (unsigned int)data[0] << 24 | (unsigned int)data[1] << 16 | (unsigned int)data[2] << 8 | (unsigned int)data[3]; CHECKSIZE(data_offset + bytesize); data = f->getDataWrt(data_offset); } #ifdef _DEBUG debug_intVal = 0xC0CAC01A; debug_floatVal = sqrtf(-1); if (type == TIFF_LONG || type == TIFF_SHORT) debug_intVal = getInt(); if (type == TIFF_FLOAT || type == TIFF_DOUBLE) debug_floatVal = getFloat(); #endif } TiffEntryBE::~TiffEntryBE(void) { } unsigned int TiffEntryBE::getInt() { if (!(type == TIFF_LONG || type == TIFF_SHORT || type == TIFF_UNDEFINED)) ThrowTPE("TIFF, getInt: Wrong type 0x%x encountered. Expected Int", type); if (type == TIFF_SHORT) return getShort(); return (unsigned int)data[0] << 24 | (unsigned int)data[1] << 16 | (unsigned int)data[2] << 8 | (unsigned int)data[3]; } unsigned short TiffEntryBE::getShort() { if (!(type == TIFF_SHORT || type == TIFF_UNDEFINED)) ThrowTPE("TIFF, getShort: Wrong type 0x%x encountered. Expected Short", type); return (unsigned short)data[0] << 8 | (unsigned short)data[1]; } const unsigned int* TiffEntryBE::getIntArray() { //TODO: Make critical section to avoid clashes. if (!(type == TIFF_LONG || type == TIFF_UNDEFINED || type == TIFF_RATIONAL || type == TIFF_SRATIONAL)) ThrowTPE("TIFF, getIntArray: Wrong type 0x%x encountered. Expected Int", type); if (mDataSwapped) return (unsigned int*)&data[0]; unsigned int* d = (unsigned int*) & data[0]; for (uint32 i = 0; i < count; i++) { d[i] = (unsigned int)data[i*4+0] << 24 | (unsigned int)data[i*4+1] << 16 | (unsigned int)data[i*4+2] << 8 | (unsigned int)data[i*4+3]; } mDataSwapped = true; return d; } const unsigned short* TiffEntryBE::getShortArray() { //TODO: Make critical section to avoid clashes. if (!(type == TIFF_SHORT || type == TIFF_UNDEFINED)) ThrowTPE("TIFF, getShortArray: Wrong type 0x%x encountered. Expected Short", type); if (mDataSwapped) return (unsigned short*)&data[0]; unsigned short* d = (unsigned short*) & data[0]; for (uint32 i = 0; i < count; i++) { d[i] = (unsigned short)data[i*2+0] << 8 | (unsigned short)data[i*2+1]; } mDataSwapped = true; return d; } } // namespace RawSpeed
Fix broken Nikons
Fix broken Nikons git-svn-id: 04e88ac4940b0408b73cd6f458a224a262abaaff@250 ec705bc8-faf6-4f9b-9aff-b4916e9bedc3
C++
lgpl-2.1
jbuchbinder/rawspeed,jbuchbinder/rawspeed
e74b0c8495693ea052d3c7436fd7eb86cd29c94b
tests/auto/qserviceinterfacedescriptor/tst_qserviceinterfacedescriptor.cpp
tests/auto/qserviceinterfacedescriptor/tst_qserviceinterfacedescriptor.cpp
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include <QtCore> #ifndef QT_NO_DEBUG_STREAM #include <QDebug> #endif #include <qserviceinterfacedescriptor.h> #include <qserviceinterfacedescriptor_p.h> class tst_QServiceInterfaceDescriptor: public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); void comparison(); #ifndef QT_NO_DATASTREAM void testStreamOperators(); #endif #ifndef QT_NO_DEBUG_STREAM void testDebugStream(); #endif }; void tst_QServiceInterfaceDescriptor::initTestCase() { } void tst_QServiceInterfaceDescriptor::comparison() { QServiceInterfaceDescriptor desc; QVERIFY(desc.majorVersion() == -1); QVERIFY(desc.minorVersion() == -1); QVERIFY(desc.serviceName().isEmpty()); QVERIFY(desc.interfaceName().isEmpty()); QVERIFY(!desc.property(QServiceInterfaceDescriptor::Capabilities).isValid()); QVERIFY(!desc.property(QServiceInterfaceDescriptor::Location).isValid()); QVERIFY(!desc.property(QServiceInterfaceDescriptor::InterfaceDescription).isValid()); QVERIFY(!desc.property(QServiceInterfaceDescriptor::ServiceDescription).isValid()); QVERIFY(!desc.isValid()); QServiceInterfaceDescriptor copy(desc); QVERIFY(copy.majorVersion() == -1); QVERIFY(copy.minorVersion() == -1); QVERIFY(copy.serviceName().isEmpty()); QVERIFY(copy.interfaceName().isEmpty()); QVERIFY(!copy.property(QServiceInterfaceDescriptor::Capabilities).isValid()); QVERIFY(!copy.property(QServiceInterfaceDescriptor::Location).isValid()); QVERIFY(!copy.property(QServiceInterfaceDescriptor::InterfaceDescription).isValid()); QVERIFY(!copy.property(QServiceInterfaceDescriptor::ServiceDescription).isValid()); QVERIFY(!copy.isValid()); QVERIFY(desc == copy); QServiceInterfaceDescriptor valid; QServiceInterfaceDescriptorPrivate *d = new QServiceInterfaceDescriptorPrivate(); QServiceInterfaceDescriptorPrivate::setPrivate(&valid, d); d->serviceName = "name"; d->interfaceName = "interface"; d->major = 3; d->minor = 1; QCOMPARE(valid.interfaceName(), QString("interface")); QCOMPARE(valid.serviceName(), QString("name")); QCOMPARE(valid.majorVersion(), 3); QCOMPARE(valid.minorVersion(), 1); QVERIFY(valid.isValid()); QVERIFY(valid != desc); QVERIFY(desc != valid); //test copy constructor QServiceInterfaceDescriptor validCopy(valid); QVERIFY(valid==validCopy); QVERIFY(validCopy==valid); QServiceInterfaceDescriptorPrivate::getPrivate(&validCopy)->properties.insert(QServiceInterfaceDescriptor::Location, QString("myValue")); QVERIFY(valid!=validCopy); QVERIFY(validCopy!=valid); QCOMPARE(validCopy.interfaceName(), QString("interface")); QCOMPARE(validCopy.serviceName(), QString("name")); QCOMPARE(validCopy.majorVersion(), 3); QCOMPARE(validCopy.minorVersion(), 1); QCOMPARE(validCopy.property(QServiceInterfaceDescriptor::Location).toString(), QString("myValue")); QVERIFY(validCopy.isValid()); //test assignment operator QServiceInterfaceDescriptor validCopy2 = valid; QVERIFY(valid==validCopy2); QVERIFY(validCopy2==valid); QServiceInterfaceDescriptorPrivate::getPrivate(&validCopy2)->properties.insert(QServiceInterfaceDescriptor::Location, QString("myValue")); QVERIFY(valid!=validCopy2); QVERIFY(validCopy2!=valid); QCOMPARE(validCopy2.interfaceName(), QString("interface")); QCOMPARE(validCopy2.serviceName(), QString("name")); QCOMPARE(validCopy2.majorVersion(), 3); QCOMPARE(validCopy2.minorVersion(), 1); QCOMPARE(validCopy2.property(QServiceInterfaceDescriptor::Location).toString(), QString("myValue")); QVERIFY(validCopy2.isValid()); } #ifndef QT_NO_DATASTREAM void tst_QServiceInterfaceDescriptor::testStreamOperators() { QByteArray byteArray; QBuffer buffer(&byteArray); buffer.open(QIODevice::ReadWrite); QDataStream stream(&buffer); QServiceInterfaceDescriptor empty; QVERIFY(!empty.isValid()); //stream invalid into invalid QServiceInterfaceDescriptor invalid; QVERIFY(!invalid.isValid()); QVERIFY(invalid == empty); buffer.seek(0); stream << empty; buffer.seek(0); stream >> invalid; QVERIFY(invalid == empty); //stream invalid into valid QServiceInterfaceDescriptor valid; QServiceInterfaceDescriptorPrivate *d = new QServiceInterfaceDescriptorPrivate(); QServiceInterfaceDescriptorPrivate::setPrivate(&valid, d); d->serviceName = "name"; d->interfaceName = "interface"; d->major = 3; d->minor = 1; d->properties.insert(QServiceInterfaceDescriptor::Location, QString("myValue")); d->properties.insert(QServiceInterfaceDescriptor::Capabilities, QStringList() << "val1" << "val2"); d->properties.insert(QServiceInterfaceDescriptor::ServiceDescription, QString("This is the service description")); d->properties.insert(QServiceInterfaceDescriptor::InterfaceDescription, QString("This is the interface description")); QVERIFY(valid.isValid()); QServiceInterfaceDescriptor validref = valid; QVERIFY(validref == valid); QVERIFY(!(validref!=valid)); QVERIFY(empty!=validref); buffer.seek(0); stream << empty; buffer.seek(0); stream >> validref; QVERIFY(empty == validref); QVERIFY(!(empty!=validref)); QVERIFY(validref != valid); //stream valid into invalid QServiceInterfaceDescriptor invalid2; QVERIFY(!invalid2.isValid()); validref = valid; QVERIFY(validref == valid); QVERIFY(validref != invalid2); buffer.seek(0); stream << validref; buffer.seek(0); stream >> invalid2; QVERIFY(invalid2 == validref); QVERIFY(!(invalid2 != validref)); QVERIFY(invalid2.isValid()); QVERIFY(invalid2.interfaceName() == QString("interface")); QVERIFY(invalid2.serviceName() == QString("name")); QVERIFY(invalid2.majorVersion() == 3); QVERIFY(invalid2.minorVersion() == 1); QVERIFY(invalid2.property(QServiceInterfaceDescriptor::Location).toString() == QString("myValue")); QVERIFY(invalid2.property(QServiceInterfaceDescriptor::Capabilities).toStringList() == (QStringList() << "val1" << "val2")); QVERIFY(invalid2.property(QServiceInterfaceDescriptor::ServiceDescription).toString() == QString("This is the service description")); QVERIFY(invalid2.property(QServiceInterfaceDescriptor::InterfaceDescription).toString() == QString("This is the interface description")); //stream valid into valid QServiceInterfaceDescriptor valid2; QServiceInterfaceDescriptorPrivate *d2 = new QServiceInterfaceDescriptorPrivate(); QServiceInterfaceDescriptorPrivate::setPrivate(&valid2, d2); d2->serviceName = "name2"; d2->interfaceName = "interface2"; d2->major = 5; d2->minor = 6; d2->properties.insert(QServiceInterfaceDescriptor::Location, QString("myValue1")); d2->properties.insert(QServiceInterfaceDescriptor::Capabilities, QStringList() << "val3" << "val4"); d2->properties.insert(QServiceInterfaceDescriptor::ServiceDescription, QString("This is the second service description")); d2->properties.insert(QServiceInterfaceDescriptor::InterfaceDescription, QString("This is the second interface description")); QVERIFY(valid2.isValid()); QVERIFY(valid2 != valid); QVERIFY(!(valid2 == valid)); buffer.seek(0); stream << valid; buffer.seek(0); stream >> valid2; QVERIFY(valid2 == valid); QVERIFY(!(valid2 != valid)); QVERIFY(valid2.isValid()); QVERIFY(valid2.interfaceName() == QString("interface")); QVERIFY(valid2.serviceName() == QString("name")); QVERIFY(valid2.majorVersion() == 3); QVERIFY(valid2.minorVersion() == 1); QVERIFY(valid2.property(QServiceInterfaceDescriptor::Location).toString() == QString("myValue")); QVERIFY(valid2.property(QServiceInterfaceDescriptor::Capabilities).toStringList() == (QStringList() << "val1" << "val2")); QVERIFY(valid2.property(QServiceInterfaceDescriptor::ServiceDescription).toString() == QString("This is the service description")); QVERIFY(valid2.property(QServiceInterfaceDescriptor::InterfaceDescription).toString() == QString("This is the interface description")); } #endif //QT_NO_DATASTREAM #ifndef QT_NO_DEBUG_STREAM static QByteArray msg; static QtMsgType type; static void customMsgHandler(QtMsgType t, const char* m) { msg = m; type = t; } void tst_QServiceInterfaceDescriptor::testDebugStream() { QServiceInterfaceDescriptor valid2; QServiceInterfaceDescriptorPrivate *d2 = new QServiceInterfaceDescriptorPrivate(); QServiceInterfaceDescriptorPrivate::setPrivate(&valid2, d2); d2->serviceName = "name2"; d2->interfaceName = "interface2"; d2->major = 5; d2->minor = 6; d2->properties.insert(QServiceInterfaceDescriptor::Location, QString("myValue1")); d2->properties.insert(QServiceInterfaceDescriptor::Capabilities, QStringList() << "val3" << "val4"); d2->properties.insert(QServiceInterfaceDescriptor::ServiceDescription, QString("This is the second service description")); d2->properties.insert(QServiceInterfaceDescriptor::InterfaceDescription, QString("This is the second interface description")); QVERIFY(valid2.isValid()); QServiceInterfaceDescriptor invalid; qInstallMsgHandler(customMsgHandler); qDebug() << valid2 << invalid; QCOMPARE(type, QtDebugMsg); QCOMPARE(QString::fromLatin1(msg.data()),QString::fromLatin1("QServiceInterfaceDescriptor(service=\"name2\", interface=\"interface2 5.6\") QServiceInterfaceDescriptor(invalid) ")); qInstallMsgHandler(0); } #endif void tst_QServiceInterfaceDescriptor::cleanupTestCase() { } QTEST_MAIN(tst_QServiceInterfaceDescriptor) #include "tst_qserviceinterfacedescriptor.moc"
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include <QtCore> #ifndef QT_NO_DEBUG_STREAM #include <QDebug> #endif #include <qserviceinterfacedescriptor.h> #include <qserviceinterfacedescriptor_p.h> class tst_QServiceInterfaceDescriptor: public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); void comparison(); #ifndef QT_NO_DATASTREAM void testStreamOperators(); #endif #ifndef QT_NO_DEBUG_STREAM void testDebugStream(); #endif void destructor(); }; void tst_QServiceInterfaceDescriptor::initTestCase() { } void tst_QServiceInterfaceDescriptor::comparison() { QServiceInterfaceDescriptor desc; QVERIFY(desc.majorVersion() == -1); QVERIFY(desc.minorVersion() == -1); QVERIFY(desc.serviceName().isEmpty()); QVERIFY(desc.interfaceName().isEmpty()); QVERIFY(!desc.property(QServiceInterfaceDescriptor::Capabilities).isValid()); QVERIFY(!desc.property(QServiceInterfaceDescriptor::Location).isValid()); QVERIFY(!desc.property(QServiceInterfaceDescriptor::InterfaceDescription).isValid()); QVERIFY(!desc.property(QServiceInterfaceDescriptor::ServiceDescription).isValid()); QVERIFY(!desc.isValid()); QServiceInterfaceDescriptor copy(desc); QVERIFY(copy.majorVersion() == -1); QVERIFY(copy.minorVersion() == -1); QVERIFY(copy.serviceName().isEmpty()); QVERIFY(copy.interfaceName().isEmpty()); QVERIFY(!copy.property(QServiceInterfaceDescriptor::Capabilities).isValid()); QVERIFY(!copy.property(QServiceInterfaceDescriptor::Location).isValid()); QVERIFY(!copy.property(QServiceInterfaceDescriptor::InterfaceDescription).isValid()); QVERIFY(!copy.property(QServiceInterfaceDescriptor::ServiceDescription).isValid()); QVERIFY(!copy.isValid()); QVERIFY(desc == copy); QServiceInterfaceDescriptor valid; QServiceInterfaceDescriptorPrivate *d = new QServiceInterfaceDescriptorPrivate(); QServiceInterfaceDescriptorPrivate::setPrivate(&valid, d); d->serviceName = "name"; d->interfaceName = "interface"; d->major = 3; d->minor = 1; QCOMPARE(valid.interfaceName(), QString("interface")); QCOMPARE(valid.serviceName(), QString("name")); QCOMPARE(valid.majorVersion(), 3); QCOMPARE(valid.minorVersion(), 1); QVERIFY(valid.isValid()); QVERIFY(valid != desc); QVERIFY(desc != valid); //test copy constructor QServiceInterfaceDescriptor validCopy(valid); QVERIFY(valid==validCopy); QVERIFY(validCopy==valid); QServiceInterfaceDescriptorPrivate::getPrivate(&validCopy)->properties.insert(QServiceInterfaceDescriptor::Location, QString("myValue")); QVERIFY(valid!=validCopy); QVERIFY(validCopy!=valid); QCOMPARE(validCopy.interfaceName(), QString("interface")); QCOMPARE(validCopy.serviceName(), QString("name")); QCOMPARE(validCopy.majorVersion(), 3); QCOMPARE(validCopy.minorVersion(), 1); QCOMPARE(validCopy.property(QServiceInterfaceDescriptor::Location).toString(), QString("myValue")); QVERIFY(validCopy.isValid()); //test assignment operator QServiceInterfaceDescriptor validCopy2 = valid; QVERIFY(valid==validCopy2); QVERIFY(validCopy2==valid); QServiceInterfaceDescriptorPrivate::getPrivate(&validCopy2)->properties.insert(QServiceInterfaceDescriptor::Location, QString("myValue")); QVERIFY(valid!=validCopy2); QVERIFY(validCopy2!=valid); QCOMPARE(validCopy2.interfaceName(), QString("interface")); QCOMPARE(validCopy2.serviceName(), QString("name")); QCOMPARE(validCopy2.majorVersion(), 3); QCOMPARE(validCopy2.minorVersion(), 1); QCOMPARE(validCopy2.property(QServiceInterfaceDescriptor::Location).toString(), QString("myValue")); QVERIFY(validCopy2.isValid()); } #ifndef QT_NO_DATASTREAM void tst_QServiceInterfaceDescriptor::testStreamOperators() { QByteArray byteArray; QBuffer buffer(&byteArray); buffer.open(QIODevice::ReadWrite); QDataStream stream(&buffer); QServiceInterfaceDescriptor empty; QVERIFY(!empty.isValid()); //stream invalid into invalid QServiceInterfaceDescriptor invalid; QVERIFY(!invalid.isValid()); QVERIFY(invalid == empty); buffer.seek(0); stream << empty; buffer.seek(0); stream >> invalid; QVERIFY(invalid == empty); //stream invalid into valid QServiceInterfaceDescriptor valid; QServiceInterfaceDescriptorPrivate *d = new QServiceInterfaceDescriptorPrivate(); QServiceInterfaceDescriptorPrivate::setPrivate(&valid, d); d->serviceName = "name"; d->interfaceName = "interface"; d->major = 3; d->minor = 1; d->properties.insert(QServiceInterfaceDescriptor::Location, QString("myValue")); d->properties.insert(QServiceInterfaceDescriptor::Capabilities, QStringList() << "val1" << "val2"); d->properties.insert(QServiceInterfaceDescriptor::ServiceDescription, QString("This is the service description")); d->properties.insert(QServiceInterfaceDescriptor::InterfaceDescription, QString("This is the interface description")); QVERIFY(valid.isValid()); QServiceInterfaceDescriptor validref = valid; QVERIFY(validref == valid); QVERIFY(!(validref!=valid)); QVERIFY(empty!=validref); buffer.seek(0); stream << empty; buffer.seek(0); stream >> validref; QVERIFY(empty == validref); QVERIFY(!(empty!=validref)); QVERIFY(validref != valid); //stream valid into invalid QServiceInterfaceDescriptor invalid2; QVERIFY(!invalid2.isValid()); validref = valid; QVERIFY(validref == valid); QVERIFY(validref != invalid2); buffer.seek(0); stream << validref; buffer.seek(0); stream >> invalid2; QVERIFY(invalid2 == validref); QVERIFY(!(invalid2 != validref)); QVERIFY(invalid2.isValid()); QVERIFY(invalid2.interfaceName() == QString("interface")); QVERIFY(invalid2.serviceName() == QString("name")); QVERIFY(invalid2.majorVersion() == 3); QVERIFY(invalid2.minorVersion() == 1); QVERIFY(invalid2.property(QServiceInterfaceDescriptor::Location).toString() == QString("myValue")); QVERIFY(invalid2.property(QServiceInterfaceDescriptor::Capabilities).toStringList() == (QStringList() << "val1" << "val2")); QVERIFY(invalid2.property(QServiceInterfaceDescriptor::ServiceDescription).toString() == QString("This is the service description")); QVERIFY(invalid2.property(QServiceInterfaceDescriptor::InterfaceDescription).toString() == QString("This is the interface description")); //stream valid into valid QServiceInterfaceDescriptor valid2; QServiceInterfaceDescriptorPrivate *d2 = new QServiceInterfaceDescriptorPrivate(); QServiceInterfaceDescriptorPrivate::setPrivate(&valid2, d2); d2->serviceName = "name2"; d2->interfaceName = "interface2"; d2->major = 5; d2->minor = 6; d2->properties.insert(QServiceInterfaceDescriptor::Location, QString("myValue1")); d2->properties.insert(QServiceInterfaceDescriptor::Capabilities, QStringList() << "val3" << "val4"); d2->properties.insert(QServiceInterfaceDescriptor::ServiceDescription, QString("This is the second service description")); d2->properties.insert(QServiceInterfaceDescriptor::InterfaceDescription, QString("This is the second interface description")); QVERIFY(valid2.isValid()); QVERIFY(valid2 != valid); QVERIFY(!(valid2 == valid)); buffer.seek(0); stream << valid; buffer.seek(0); stream >> valid2; QVERIFY(valid2 == valid); QVERIFY(!(valid2 != valid)); QVERIFY(valid2.isValid()); QVERIFY(valid2.interfaceName() == QString("interface")); QVERIFY(valid2.serviceName() == QString("name")); QVERIFY(valid2.majorVersion() == 3); QVERIFY(valid2.minorVersion() == 1); QVERIFY(valid2.property(QServiceInterfaceDescriptor::Location).toString() == QString("myValue")); QVERIFY(valid2.property(QServiceInterfaceDescriptor::Capabilities).toStringList() == (QStringList() << "val1" << "val2")); QVERIFY(valid2.property(QServiceInterfaceDescriptor::ServiceDescription).toString() == QString("This is the service description")); QVERIFY(valid2.property(QServiceInterfaceDescriptor::InterfaceDescription).toString() == QString("This is the interface description")); } #endif //QT_NO_DATASTREAM #ifndef QT_NO_DEBUG_STREAM static QByteArray msg; static QtMsgType type; static void customMsgHandler(QtMsgType t, const char* m) { msg = m; type = t; } void tst_QServiceInterfaceDescriptor::testDebugStream() { QServiceInterfaceDescriptor valid2; QServiceInterfaceDescriptorPrivate *d2 = new QServiceInterfaceDescriptorPrivate(); QServiceInterfaceDescriptorPrivate::setPrivate(&valid2, d2); d2->serviceName = "name2"; d2->interfaceName = "interface2"; d2->major = 5; d2->minor = 6; d2->properties.insert(QServiceInterfaceDescriptor::Location, QString("myValue1")); d2->properties.insert(QServiceInterfaceDescriptor::Capabilities, QStringList() << "val3" << "val4"); d2->properties.insert(QServiceInterfaceDescriptor::ServiceDescription, QString("This is the second service description")); d2->properties.insert(QServiceInterfaceDescriptor::InterfaceDescription, QString("This is the second interface description")); QVERIFY(valid2.isValid()); QServiceInterfaceDescriptor invalid; qInstallMsgHandler(customMsgHandler); qDebug() << valid2 << invalid; QCOMPARE(type, QtDebugMsg); QCOMPARE(QString::fromLatin1(msg.data()),QString::fromLatin1("QServiceInterfaceDescriptor(service=\"name2\", interface=\"interface2 5.6\") QServiceInterfaceDescriptor(invalid) ")); qInstallMsgHandler(0); } #endif void tst_QServiceInterfaceDescriptor::destructor() { //test destructor if descriptor is invalid QServiceInterfaceDescriptor* invalid = new QServiceInterfaceDescriptor(); delete invalid; //test destructor if descriptor is valid QServiceInterfaceDescriptor* valid = new QServiceInterfaceDescriptor(); QServiceInterfaceDescriptorPrivate *d = new QServiceInterfaceDescriptorPrivate(); QServiceInterfaceDescriptorPrivate::setPrivate(valid, d); d->serviceName = "name"; d->interfaceName = "interface"; d->major = 3; d->minor = 1; d->properties.insert(QServiceInterfaceDescriptor::Location, QString("myValue")); d->properties.insert(QServiceInterfaceDescriptor::Capabilities, QStringList() << "val1" << "val2"); d->properties.insert(QServiceInterfaceDescriptor::ServiceDescription, QString("This is the service description")); d->properties.insert(QServiceInterfaceDescriptor::InterfaceDescription, QString("This is the interface description")); QVERIFY(valid->isValid()); delete valid; } void tst_QServiceInterfaceDescriptor::cleanupTestCase() { } QTEST_MAIN(tst_QServiceInterfaceDescriptor) #include "tst_qserviceinterfacedescriptor.moc"
test ~QSerivceINterfaceDescriptor
test ~QSerivceINterfaceDescriptor
C++
lgpl-2.1
enthought/qt-mobility,tmcguire/qt-mobility,enthought/qt-mobility,KDE/android-qt-mobility,tmcguire/qt-mobility,tmcguire/qt-mobility,qtproject/qt-mobility,enthought/qt-mobility,KDE/android-qt-mobility,qtproject/qt-mobility,kaltsi/qt-mobility,enthought/qt-mobility,KDE/android-qt-mobility,KDE/android-qt-mobility,qtproject/qt-mobility,kaltsi/qt-mobility,kaltsi/qt-mobility,qtproject/qt-mobility,kaltsi/qt-mobility,kaltsi/qt-mobility,tmcguire/qt-mobility,qtproject/qt-mobility,kaltsi/qt-mobility,enthought/qt-mobility,enthought/qt-mobility,qtproject/qt-mobility,tmcguire/qt-mobility
293050a91973bd6a6974eb852a43438d447a3801
core/io/compression.cpp
core/io/compression.cpp
/*************************************************************************/ /* compression.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "compression.h" #include "core/config/project_settings.h" #include "core/io/zip_io.h" #include "thirdparty/misc/fastlz.h" #include <zlib.h> #include <zstd.h> int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size, Mode p_mode) { switch (p_mode) { case MODE_FASTLZ: { if (p_src_size < 16) { uint8_t src[16]; memset(&src[p_src_size], 0, 16 - p_src_size); memcpy(src, p_src, p_src_size); return fastlz_compress(src, 16, p_dst); } else { return fastlz_compress(p_src, p_src_size, p_dst); } } break; case MODE_DEFLATE: case MODE_GZIP: { int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16; z_stream strm; strm.zalloc = zipio_alloc; strm.zfree = zipio_free; strm.opaque = Z_NULL; int level = p_mode == MODE_DEFLATE ? zlib_level : gzip_level; int err = deflateInit2(&strm, level, Z_DEFLATED, window_bits, 8, Z_DEFAULT_STRATEGY); if (err != Z_OK) { return -1; } strm.avail_in = p_src_size; int aout = deflateBound(&strm, p_src_size); strm.avail_out = aout; strm.next_in = (Bytef *)p_src; strm.next_out = p_dst; deflate(&strm, Z_FINISH); aout = aout - strm.avail_out; deflateEnd(&strm); return aout; } break; case MODE_ZSTD: { ZSTD_CCtx *cctx = ZSTD_createCCtx(); ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, zstd_level); if (zstd_long_distance_matching) { ZSTD_CCtx_setParameter(cctx, ZSTD_c_enableLongDistanceMatching, 1); ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, zstd_window_log_size); } int max_dst_size = get_max_compressed_buffer_size(p_src_size, MODE_ZSTD); int ret = ZSTD_compressCCtx(cctx, p_dst, max_dst_size, p_src, p_src_size, zstd_level); ZSTD_freeCCtx(cctx); return ret; } break; } ERR_FAIL_V(-1); } int Compression::get_max_compressed_buffer_size(int p_src_size, Mode p_mode) { switch (p_mode) { case MODE_FASTLZ: { int ss = p_src_size + p_src_size * 6 / 100; if (ss < 66) { ss = 66; } return ss; } break; case MODE_DEFLATE: case MODE_GZIP: { int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16; z_stream strm; strm.zalloc = zipio_alloc; strm.zfree = zipio_free; strm.opaque = Z_NULL; int err = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, window_bits, 8, Z_DEFAULT_STRATEGY); if (err != Z_OK) { return -1; } int aout = deflateBound(&strm, p_src_size); deflateEnd(&strm); return aout; } break; case MODE_ZSTD: { return ZSTD_compressBound(p_src_size); } break; } ERR_FAIL_V(-1); } int Compression::decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size, Mode p_mode) { switch (p_mode) { case MODE_FASTLZ: { int ret_size = 0; if (p_dst_max_size < 16) { uint8_t dst[16]; ret_size = fastlz_decompress(p_src, p_src_size, dst, 16); memcpy(p_dst, dst, p_dst_max_size); } else { ret_size = fastlz_decompress(p_src, p_src_size, p_dst, p_dst_max_size); } return ret_size; } break; case MODE_DEFLATE: case MODE_GZIP: { int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16; z_stream strm; strm.zalloc = zipio_alloc; strm.zfree = zipio_free; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; int err = inflateInit2(&strm, window_bits); ERR_FAIL_COND_V(err != Z_OK, -1); strm.avail_in = p_src_size; strm.avail_out = p_dst_max_size; strm.next_in = (Bytef *)p_src; strm.next_out = p_dst; err = inflate(&strm, Z_FINISH); int total = strm.total_out; inflateEnd(&strm); ERR_FAIL_COND_V(err != Z_STREAM_END, -1); return total; } break; case MODE_ZSTD: { ZSTD_DCtx *dctx = ZSTD_createDCtx(); if (zstd_long_distance_matching) { ZSTD_DCtx_setParameter(dctx, ZSTD_d_windowLogMax, zstd_window_log_size); } int ret = ZSTD_decompressDCtx(dctx, p_dst, p_dst_max_size, p_src, p_src_size); ZSTD_freeDCtx(dctx); return ret; } break; } ERR_FAIL_V(-1); } /** This will handle both Gzip and Deflate streams. It will automatically allocate the output buffer into the provided p_dst_vect Vector. This is required for compressed data whose final uncompressed size is unknown, as is the case for HTTP response bodies. This is much slower however than using Compression::decompress because it may result in multiple full copies of the output buffer. */ int Compression::decompress_dynamic(Vector<uint8_t> *p_dst_vect, int p_max_dst_size, const uint8_t *p_src, int p_src_size, Mode p_mode) { int ret; uint8_t *dst = nullptr; int out_mark = 0; z_stream strm; ERR_FAIL_COND_V(p_src_size <= 0, Z_DATA_ERROR); // This function only supports GZip and Deflate int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16; ERR_FAIL_COND_V(p_mode != MODE_DEFLATE && p_mode != MODE_GZIP, Z_ERRNO); // Initialize the stream strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; int err = inflateInit2(&strm, window_bits); ERR_FAIL_COND_V(err != Z_OK, -1); // Setup the stream inputs strm.next_in = (Bytef *)p_src; strm.avail_in = p_src_size; // Ensure the destination buffer is empty p_dst_vect->resize(0); // decompress until deflate stream ends or end of file do { // Add another chunk size to the output buffer // This forces a copy of the whole buffer p_dst_vect->resize(p_dst_vect->size() + gzip_chunk); // Get pointer to the actual output buffer dst = p_dst_vect->ptrw(); // Set the stream to the new output stream // Since it was copied, we need to reset the stream to the new buffer strm.next_out = &(dst[out_mark]); strm.avail_out = gzip_chunk; // run inflate() on input until output buffer is full and needs to be resized // or input runs out do { ret = inflate(&strm, Z_SYNC_FLUSH); switch (ret) { case Z_NEED_DICT: ret = Z_DATA_ERROR; [[fallthrough]]; case Z_DATA_ERROR: case Z_MEM_ERROR: case Z_STREAM_ERROR: WARN_PRINT(strm.msg); (void)inflateEnd(&strm); p_dst_vect->resize(0); return ret; } } while (strm.avail_out > 0 && strm.avail_in > 0); out_mark += gzip_chunk; // Enforce max output size if (p_max_dst_size > -1 && strm.total_out > (uint64_t)p_max_dst_size) { (void)inflateEnd(&strm); p_dst_vect->resize(0); return Z_BUF_ERROR; } } while (ret != Z_STREAM_END); // If all done successfully, resize the output if it's larger than the actual output if ((unsigned long)p_dst_vect->size() > strm.total_out) { p_dst_vect->resize(strm.total_out); } // clean up and return (void)inflateEnd(&strm); return Z_OK; } int Compression::zlib_level = Z_DEFAULT_COMPRESSION; int Compression::gzip_level = Z_DEFAULT_COMPRESSION; int Compression::zstd_level = 3; bool Compression::zstd_long_distance_matching = false; int Compression::zstd_window_log_size = 27; // ZSTD_WINDOWLOG_LIMIT_DEFAULT int Compression::gzip_chunk = 16384;
/*************************************************************************/ /* compression.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "compression.h" #include "core/config/project_settings.h" #include "core/io/zip_io.h" #include "thirdparty/misc/fastlz.h" #include <zlib.h> #include <zstd.h> int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size, Mode p_mode) { switch (p_mode) { case MODE_FASTLZ: { if (p_src_size < 16) { uint8_t src[16]; memset(&src[p_src_size], 0, 16 - p_src_size); memcpy(src, p_src, p_src_size); return fastlz_compress(src, 16, p_dst); } else { return fastlz_compress(p_src, p_src_size, p_dst); } } break; case MODE_DEFLATE: case MODE_GZIP: { int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16; z_stream strm; strm.zalloc = zipio_alloc; strm.zfree = zipio_free; strm.opaque = Z_NULL; int level = p_mode == MODE_DEFLATE ? zlib_level : gzip_level; int err = deflateInit2(&strm, level, Z_DEFLATED, window_bits, 8, Z_DEFAULT_STRATEGY); if (err != Z_OK) { return -1; } strm.avail_in = p_src_size; int aout = deflateBound(&strm, p_src_size); strm.avail_out = aout; strm.next_in = (Bytef *)p_src; strm.next_out = p_dst; deflate(&strm, Z_FINISH); aout = aout - strm.avail_out; deflateEnd(&strm); return aout; } break; case MODE_ZSTD: { ZSTD_CCtx *cctx = ZSTD_createCCtx(); ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, zstd_level); if (zstd_long_distance_matching) { ZSTD_CCtx_setParameter(cctx, ZSTD_c_enableLongDistanceMatching, 1); ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, zstd_window_log_size); } int max_dst_size = get_max_compressed_buffer_size(p_src_size, MODE_ZSTD); int ret = ZSTD_compressCCtx(cctx, p_dst, max_dst_size, p_src, p_src_size, zstd_level); ZSTD_freeCCtx(cctx); return ret; } break; } ERR_FAIL_V(-1); } int Compression::get_max_compressed_buffer_size(int p_src_size, Mode p_mode) { switch (p_mode) { case MODE_FASTLZ: { int ss = p_src_size + p_src_size * 6 / 100; if (ss < 66) { ss = 66; } return ss; } break; case MODE_DEFLATE: case MODE_GZIP: { int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16; z_stream strm; strm.zalloc = zipio_alloc; strm.zfree = zipio_free; strm.opaque = Z_NULL; int err = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, window_bits, 8, Z_DEFAULT_STRATEGY); if (err != Z_OK) { return -1; } int aout = deflateBound(&strm, p_src_size); deflateEnd(&strm); return aout; } break; case MODE_ZSTD: { return ZSTD_compressBound(p_src_size); } break; } ERR_FAIL_V(-1); } int Compression::decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size, Mode p_mode) { switch (p_mode) { case MODE_FASTLZ: { int ret_size = 0; if (p_dst_max_size < 16) { uint8_t dst[16]; ret_size = fastlz_decompress(p_src, p_src_size, dst, 16); memcpy(p_dst, dst, p_dst_max_size); } else { ret_size = fastlz_decompress(p_src, p_src_size, p_dst, p_dst_max_size); } return ret_size; } break; case MODE_DEFLATE: case MODE_GZIP: { int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16; z_stream strm; strm.zalloc = zipio_alloc; strm.zfree = zipio_free; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; int err = inflateInit2(&strm, window_bits); ERR_FAIL_COND_V(err != Z_OK, -1); strm.avail_in = p_src_size; strm.avail_out = p_dst_max_size; strm.next_in = (Bytef *)p_src; strm.next_out = p_dst; err = inflate(&strm, Z_FINISH); int total = strm.total_out; inflateEnd(&strm); ERR_FAIL_COND_V(err != Z_STREAM_END, -1); return total; } break; case MODE_ZSTD: { ZSTD_DCtx *dctx = ZSTD_createDCtx(); if (zstd_long_distance_matching) { ZSTD_DCtx_setParameter(dctx, ZSTD_d_windowLogMax, zstd_window_log_size); } int ret = ZSTD_decompressDCtx(dctx, p_dst, p_dst_max_size, p_src, p_src_size); ZSTD_freeDCtx(dctx); return ret; } break; } ERR_FAIL_V(-1); } /** This will handle both Gzip and Deflate streams. It will automatically allocate the output buffer into the provided p_dst_vect Vector. This is required for compressed data whose final uncompressed size is unknown, as is the case for HTTP response bodies. This is much slower however than using Compression::decompress because it may result in multiple full copies of the output buffer. */ int Compression::decompress_dynamic(Vector<uint8_t> *p_dst_vect, int p_max_dst_size, const uint8_t *p_src, int p_src_size, Mode p_mode) { int ret; uint8_t *dst = nullptr; int out_mark = 0; z_stream strm; ERR_FAIL_COND_V(p_src_size <= 0, Z_DATA_ERROR); // This function only supports GZip and Deflate int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16; ERR_FAIL_COND_V(p_mode != MODE_DEFLATE && p_mode != MODE_GZIP, Z_ERRNO); // Initialize the stream strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; int err = inflateInit2(&strm, window_bits); ERR_FAIL_COND_V(err != Z_OK, -1); // Setup the stream inputs strm.next_in = (Bytef *)p_src; strm.avail_in = p_src_size; // Ensure the destination buffer is empty p_dst_vect->resize(0); // decompress until deflate stream ends or end of file do { // Add another chunk size to the output buffer // This forces a copy of the whole buffer p_dst_vect->resize(p_dst_vect->size() + gzip_chunk); // Get pointer to the actual output buffer dst = p_dst_vect->ptrw(); // Set the stream to the new output stream // Since it was copied, we need to reset the stream to the new buffer strm.next_out = &(dst[out_mark]); strm.avail_out = gzip_chunk; // run inflate() on input until output buffer is full and needs to be resized // or input runs out do { ret = inflate(&strm, Z_SYNC_FLUSH); switch (ret) { case Z_NEED_DICT: ret = Z_DATA_ERROR; [[fallthrough]]; case Z_DATA_ERROR: case Z_MEM_ERROR: case Z_STREAM_ERROR: case Z_BUF_ERROR: if (strm.msg) { WARN_PRINT(strm.msg); } (void)inflateEnd(&strm); p_dst_vect->resize(0); return ret; } } while (strm.avail_out > 0 && strm.avail_in > 0); out_mark += gzip_chunk; // Enforce max output size if (p_max_dst_size > -1 && strm.total_out > (uint64_t)p_max_dst_size) { (void)inflateEnd(&strm); p_dst_vect->resize(0); return Z_BUF_ERROR; } } while (ret != Z_STREAM_END); // If all done successfully, resize the output if it's larger than the actual output if ((unsigned long)p_dst_vect->size() > strm.total_out) { p_dst_vect->resize(strm.total_out); } // clean up and return (void)inflateEnd(&strm); return Z_OK; } int Compression::zlib_level = Z_DEFAULT_COMPRESSION; int Compression::gzip_level = Z_DEFAULT_COMPRESSION; int Compression::zstd_level = 3; bool Compression::zstd_long_distance_matching = false; int Compression::zstd_window_log_size = 27; // ZSTD_WINDOWLOG_LIMIT_DEFAULT int Compression::gzip_chunk = 16384;
Handle Z_BUF_ERROR in decompress_dynamic
Handle Z_BUF_ERROR in decompress_dynamic
C++
mit
godotengine/godot,Zylann/godot,guilhermefelipecgs/godot,guilhermefelipecgs/godot,firefly2442/godot,Faless/godot,Valentactive/godot,josempans/godot,guilhermefelipecgs/godot,Valentactive/godot,Valentactive/godot,godotengine/godot,sanikoyes/godot,guilhermefelipecgs/godot,vkbsb/godot,pkowal1982/godot,godotengine/godot,vkbsb/godot,Valentactive/godot,Valentactive/godot,pkowal1982/godot,honix/godot,akien-mga/godot,Shockblast/godot,Shockblast/godot,BastiaanOlij/godot,ZuBsPaCe/godot,ZuBsPaCe/godot,DmitriySalnikov/godot,pkowal1982/godot,godotengine/godot,vkbsb/godot,firefly2442/godot,vnen/godot,josempans/godot,BastiaanOlij/godot,DmitriySalnikov/godot,Shockblast/godot,BastiaanOlij/godot,BastiaanOlij/godot,BastiaanOlij/godot,akien-mga/godot,guilhermefelipecgs/godot,vkbsb/godot,Valentactive/godot,Shockblast/godot,firefly2442/godot,akien-mga/godot,josempans/godot,ZuBsPaCe/godot,Zylann/godot,akien-mga/godot,Valentactive/godot,godotengine/godot,DmitriySalnikov/godot,ZuBsPaCe/godot,Faless/godot,akien-mga/godot,vnen/godot,Faless/godot,pkowal1982/godot,BastiaanOlij/godot,firefly2442/godot,sanikoyes/godot,firefly2442/godot,akien-mga/godot,Zylann/godot,firefly2442/godot,BastiaanOlij/godot,firefly2442/godot,pkowal1982/godot,ZuBsPaCe/godot,Shockblast/godot,Faless/godot,Zylann/godot,vkbsb/godot,josempans/godot,BastiaanOlij/godot,Zylann/godot,DmitriySalnikov/godot,vnen/godot,DmitriySalnikov/godot,honix/godot,honix/godot,Faless/godot,guilhermefelipecgs/godot,vkbsb/godot,ZuBsPaCe/godot,vkbsb/godot,Shockblast/godot,pkowal1982/godot,vnen/godot,josempans/godot,guilhermefelipecgs/godot,godotengine/godot,honix/godot,ZuBsPaCe/godot,akien-mga/godot,honix/godot,Shockblast/godot,sanikoyes/godot,Zylann/godot,vkbsb/godot,Zylann/godot,DmitriySalnikov/godot,guilhermefelipecgs/godot,ZuBsPaCe/godot,honix/godot,vnen/godot,Shockblast/godot,josempans/godot,josempans/godot,sanikoyes/godot,DmitriySalnikov/godot,sanikoyes/godot,Valentactive/godot,godotengine/godot,vnen/godot,Faless/godot,Faless/godot,firefly2442/godot,josempans/godot,sanikoyes/godot,vnen/godot,godotengine/godot,sanikoyes/godot,vnen/godot,sanikoyes/godot,pkowal1982/godot,pkowal1982/godot,akien-mga/godot,Faless/godot,Zylann/godot
3f3508e699ce4de4529750051b32b1cb5004165c
volo.cpp
volo.cpp
// Copyright (c) 2014 Josh Rickmar. // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. #include <volo.h> using namespace volo; WebContext WebContext::get_default() { return WebContext{}; } void WebContext::set_process_model(WebKitProcessModel model) { webkit_web_context_set_process_model(wc, model); } static void WebView_load_changed_callback(WebKitWebView *wv, WebKitLoadEvent ev, gpointer signal) { static_cast<sigc::signal<void, WebKitLoadEvent> *>(signal)->emit(ev); } static void BackForwardList_changed_callback(WebKitBackForwardList *list, WebKitBackForwardListItem *item, gpointer removed, gpointer signal) { static_cast<sigc::signal<void, WebKitBackForwardList *> *>(signal)->emit(list); } static void WebView_notify_title_callback(GObject *, GParamSpec *, gpointer signal) { static_cast<sigc::signal<void> *>(signal)->emit(); } static void WebView_notify_uri_callback(GObject *, GParamSpec *, gpointer signal) { static_cast<sigc::signal<void> *>(signal)->emit(); } WebView::WebView(WebKitWebView *wv) : Gtk::Widget{GTK_WIDGET(wv)} { g_signal_connect(wv, "load-changed", G_CALLBACK(WebView_load_changed_callback), &signal_load_changed); auto bfl = webkit_web_view_get_back_forward_list(wv); g_signal_connect(bfl, "changed", G_CALLBACK(BackForwardList_changed_callback), &signal_back_forward_list_changed); g_signal_connect(wv, "notify::title", G_CALLBACK(WebView_notify_title_callback), &signal_notify_title); g_signal_connect(wv, "notify::uri", G_CALLBACK(WebView_notify_uri_callback), &signal_notify_uri); } WebView::WebView(const Glib::ustring& uri) : WebView{} { load_uri(uri); } void WebView::load_uri(const Glib::ustring& uri) { webkit_web_view_load_uri(gobj(), uri.c_str()); } Glib::ustring WebView::get_uri() { auto uri = webkit_web_view_get_uri(gobj()); return uri ? uri : ""; } void WebView::reload() { webkit_web_view_reload(gobj()); } void WebView::go_back() { webkit_web_view_go_back(gobj()); } void WebView::go_forward() { webkit_web_view_go_forward(gobj()); } sigc::connection WebView::connect_load_changed( std::function<void(WebKitLoadEvent)> handler) { return signal_load_changed.connect(handler); } sigc::connection WebView::connect_back_forward_list_changed( std::function<void(WebKitBackForwardList *)> handler) { return signal_back_forward_list_changed.connect(handler); } sigc::connection WebView::connect_notify_title(std::function<void()> handler) { return signal_notify_title.connect(handler); } sigc::connection WebView::connect_notify_uri(std::function<void()> handler) { return signal_notify_uri.connect(handler); } URIEntry::URIEntry() { set_size_request(600, -1); // TODO: make this dynamic with the window size set_margin_left(6); set_margin_right(6); entry.set_hexpand(true); entry.set_input_purpose(Gtk::INPUT_PURPOSE_URL); entry.set_icon_from_icon_name("view-refresh", Gtk::ENTRY_ICON_SECONDARY); entry.signal_button_release_event().connect(sigc::mem_fun(*this, &URIEntry::on_button_release_event), false); entry.property_is_focus().signal_changed().connect([this](...) { if (!entry.is_focus()) { entry.select_region(0, 0); editing = false; } }); entry.signal_icon_press().connect([this](Gtk::EntryIconPosition pos, ...) { refresh_pressed = true; }); entry.signal_icon_release().connect([this](Gtk::EntryIconPosition pos, ...) { if (refresh_pressed) { signal_refresh.emit(); } refresh_pressed = false; }); add(entry); show_all_children(); } Glib::SignalProxy0<void> URIEntry::signal_uri_entered() { return entry.signal_activate(); } Glib::ustring URIEntry::get_uri() { return entry.get_text(); } void URIEntry::set_uri(const Glib::ustring& uri) { entry.set_text(uri); } // This can't be a lambda since we can't create sigc::slots from lambdas // with return values. bool URIEntry::on_button_release_event(GdkEventButton *) { if (!editing && !refresh_pressed) { int start, end; if (!entry.get_selection_bounds(start, end)) { entry.grab_focus(); } } editing = true; return false; } sigc::connection URIEntry::connect_refresh(std::function<void()> handler) { return signal_refresh.connect(handler); } Browser::Browser(const std::vector<Glib::ustring>& uris) { auto wc = WebContext::get_default(); wc.set_process_model(WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES); // Set navigation button images. No gtkmm constructor wraps // gtk_button_new_from_icon_name (due to a conflict with // gtk_button_new_with_label) so this must be done in the Browser // constructor. back.set_image_from_icon_name("go-previous"); fwd.set_image_from_icon_name("go-next"); new_tab.set_image_from_icon_name("add"); auto histnav_style = histnav.get_style_context(); histnav_style->add_class("raised"); histnav_style->add_class("linked"); histnav.add(back); histnav.add(fwd); navbar.pack_start(histnav); navbar.set_custom_title(nav_entry); new_tab.set_can_focus(false); new_tab.set_relief(Gtk::RELIEF_NONE); new_tab.show(); navbar.pack_end(new_tab); navbar.set_show_close_button(true); auto num_uris = uris.size(); nb.set_show_tabs(num_uris > 1); set_title("volo"); set_default_size(1024, 768); set_titlebar(navbar); nb.set_scrollable(); add(nb); tabs.reserve(num_uris); for (const auto& uri : uris) { open_new_tab(uri); } nav_entry.signal_uri_entered().connect([this] { auto text = nav_entry.get_uri(); // TODO: this could not be a valid uri. visable_tab.webview->load_uri(text); visable_tab.webview->grab_focus(); }); nb.signal_switch_page().connect([this] (auto, guint page_num) { switch_page(page_num); }); nb.signal_page_added().connect([this] (...) { nb.set_show_tabs(true); }); nb.signal_page_removed().connect([this] (...) { nb.set_show_tabs(nb.get_n_pages() > 1); }); new_tab.signal_clicked().connect([this] { auto n = open_new_tab(""); nb.set_current_page(n); }); show_webview(0, tabs.front()->wv); show_all_children(); } Browser::Tab::Tab(const Glib::ustring& uri) : wv{uri}, tab_title{"New tab"} { tab_title.set_can_focus(false); tab_title.set_hexpand(true); tab_title.set_ellipsize(Pango::ELLIPSIZE_END); tab_title.set_size_request(50, -1); tab_close.set_image_from_icon_name("window-close"); } int Browser::open_new_tab(const Glib::ustring& uri) { tabs.emplace_back(std::make_unique<Tab>(uri)); const auto& tab = tabs.back(); auto& wv = tab->wv; auto tab_content = make_managed<Gtk::Box>(); tab_content->set_can_focus(false); tab_content->add(tab->tab_title); tab_content->add(tab->tab_close); wv.show_all(); tab_content->show_all(); const auto n = nb.append_page(wv, *tab_content); nb.set_tab_reorderable(wv, true); tab->tab_close.signal_clicked().connect([this, &tab = *tab] { // NOTE: This is very fast because it does not need to // dereference every pointer in the tabs vector, but it // relies on the Tab struct never being moved. Currently // this holds true because moving for this type is disabled // (no move constructors or assignment operators exists). for (auto it = tabs.begin(); it != tabs.end(); ++it) { // Compare using pointer equality. We intentionally // captured a reference to the Tab, and not the // vector's unique_ptr<Tab>, so that we could take the // address of the actual WebView object without the // vector's unique_ptr having been zeroed after a move. if (it->get() != &tab) { continue; } tabs.erase(it); break; } if (tabs.size() == 0) { close(); } }); wv.connect_notify_title([this, &tab = *tab] { // Update tab title and the window title (if this tab is // currently visable) with the new page title. auto& wv = tab.wv; auto c_title = webkit_web_view_get_title(wv.gobj()); Glib::ustring title{c_title ? c_title : "(Untitled)"}; tab.tab_title.set_text(title); if (visable_tab.webview == &wv) { set_title(title); } }); return n; } void Browser::show_webview(unsigned int page_num, WebView& wv) { visable_tab = VisableTab{page_num, wv}; // Update navbar/titlebar with the current state of the webview being // shown. auto c_title = webkit_web_view_get_title(wv.gobj()); set_title(c_title ? c_title : "volo"); update_histnav(wv); nav_entry.set_uri(wv.get_uri()); page_signals = { { back.signal_clicked().connect([&wv] { wv.go_back(); }), fwd.signal_clicked().connect([&wv] { wv.go_forward(); }), wv.connect_back_forward_list_changed([this](WebKitBackForwardList *bfl) { if (visable_tab.bfl == bfl) { update_histnav(*visable_tab.webview); } }), wv.connect_notify_uri([this, &wv] { nav_entry.set_uri(wv.get_uri()); }), nav_entry.connect_refresh([&wv] { wv.reload(); }), } }; } void Browser::update_histnav(WebView& wv) { const auto p = wv.gobj(); back.set_sensitive(webkit_web_view_can_go_back(p)); fwd.set_sensitive(webkit_web_view_can_go_forward(p)); } void Browser::switch_page(unsigned int page_num) noexcept { // Disconnect previous WebView's signals before showing and connecting // the new WebView. for (auto& sig : page_signals) { sig.disconnect(); } show_webview(page_num, tabs.at(page_num)->wv); } int main(int argc, char **argv) { const auto app = Gtk::Application::create(argc, argv, "org.jrick.volo"); Browser b; return app->run(b); }
// Copyright (c) 2014 Josh Rickmar. // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. #include <volo.h> using namespace volo; WebContext WebContext::get_default() { return WebContext{}; } void WebContext::set_process_model(WebKitProcessModel model) { webkit_web_context_set_process_model(wc, model); } static void WebView_load_changed_callback(WebKitWebView *wv, WebKitLoadEvent ev, gpointer signal) { static_cast<sigc::signal<void, WebKitLoadEvent> *>(signal)->emit(ev); } static void BackForwardList_changed_callback(WebKitBackForwardList *list, WebKitBackForwardListItem *item, gpointer removed, gpointer signal) { static_cast<sigc::signal<void, WebKitBackForwardList *> *>(signal)->emit(list); } static void WebView_notify_title_callback(GObject *, GParamSpec *, gpointer signal) { static_cast<sigc::signal<void> *>(signal)->emit(); } static void WebView_notify_uri_callback(GObject *, GParamSpec *, gpointer signal) { static_cast<sigc::signal<void> *>(signal)->emit(); } WebView::WebView(WebKitWebView *wv) : Gtk::Widget{GTK_WIDGET(wv)} { g_signal_connect(wv, "load-changed", G_CALLBACK(WebView_load_changed_callback), &signal_load_changed); auto bfl = webkit_web_view_get_back_forward_list(wv); g_signal_connect(bfl, "changed", G_CALLBACK(BackForwardList_changed_callback), &signal_back_forward_list_changed); g_signal_connect(wv, "notify::title", G_CALLBACK(WebView_notify_title_callback), &signal_notify_title); g_signal_connect(wv, "notify::uri", G_CALLBACK(WebView_notify_uri_callback), &signal_notify_uri); } WebView::WebView(const Glib::ustring& uri) : WebView{} { load_uri(uri); } void WebView::load_uri(const Glib::ustring& uri) { webkit_web_view_load_uri(gobj(), uri.c_str()); } Glib::ustring WebView::get_uri() { auto uri = webkit_web_view_get_uri(gobj()); return uri ? uri : ""; } void WebView::reload() { webkit_web_view_reload(gobj()); } void WebView::go_back() { webkit_web_view_go_back(gobj()); } void WebView::go_forward() { webkit_web_view_go_forward(gobj()); } sigc::connection WebView::connect_load_changed( std::function<void(WebKitLoadEvent)> handler) { return signal_load_changed.connect(handler); } sigc::connection WebView::connect_back_forward_list_changed( std::function<void(WebKitBackForwardList *)> handler) { return signal_back_forward_list_changed.connect(handler); } sigc::connection WebView::connect_notify_title(std::function<void()> handler) { return signal_notify_title.connect(handler); } sigc::connection WebView::connect_notify_uri(std::function<void()> handler) { return signal_notify_uri.connect(handler); } URIEntry::URIEntry() { set_size_request(600, -1); // TODO: make this dynamic with the window size set_margin_left(6); set_margin_right(6); entry.set_hexpand(true); entry.set_input_purpose(Gtk::INPUT_PURPOSE_URL); entry.set_icon_from_icon_name("view-refresh", Gtk::ENTRY_ICON_SECONDARY); entry.signal_button_release_event().connect(sigc::mem_fun(*this, &URIEntry::on_button_release_event), false); entry.property_is_focus().signal_changed().connect([this](...) { if (!entry.is_focus()) { entry.select_region(0, 0); editing = false; } }); entry.signal_icon_press().connect([this](Gtk::EntryIconPosition pos, ...) { refresh_pressed = true; }); entry.signal_icon_release().connect([this](Gtk::EntryIconPosition pos, ...) { if (refresh_pressed) { signal_refresh.emit(); } refresh_pressed = false; }); add(entry); show_all_children(); } Glib::SignalProxy0<void> URIEntry::signal_uri_entered() { return entry.signal_activate(); } Glib::ustring URIEntry::get_uri() { return entry.get_text(); } void URIEntry::set_uri(const Glib::ustring& uri) { entry.set_text(uri); } // This can't be a lambda since we can't create sigc::slots from lambdas // with return values. bool URIEntry::on_button_release_event(GdkEventButton *) { if (!editing && !refresh_pressed) { int start, end; if (!entry.get_selection_bounds(start, end)) { entry.grab_focus(); } } editing = true; return false; } sigc::connection URIEntry::connect_refresh(std::function<void()> handler) { return signal_refresh.connect(handler); } Browser::Browser(const std::vector<Glib::ustring>& uris) { auto wc = WebContext::get_default(); wc.set_process_model(WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES); // Set navigation button images. No gtkmm constructor wraps // gtk_button_new_from_icon_name (due to a conflict with // gtk_button_new_with_label) so this must be done in the Browser // constructor. back.set_image_from_icon_name("go-previous"); fwd.set_image_from_icon_name("go-next"); new_tab.set_image_from_icon_name("add"); auto histnav_style = histnav.get_style_context(); histnav_style->add_class("raised"); histnav_style->add_class("linked"); histnav.add(back); histnav.add(fwd); navbar.pack_start(histnav); navbar.set_custom_title(nav_entry); new_tab.set_can_focus(false); new_tab.set_relief(Gtk::RELIEF_NONE); new_tab.show(); navbar.pack_end(new_tab); navbar.set_show_close_button(true); auto num_uris = uris.size(); nb.set_show_tabs(num_uris > 1); set_title("volo"); set_default_size(1024, 768); set_titlebar(navbar); nb.set_scrollable(); add(nb); tabs.reserve(num_uris); for (const auto& uri : uris) { open_new_tab(uri); } nav_entry.signal_uri_entered().connect([this] { auto text = nav_entry.get_uri(); // TODO: this could not be a valid uri. visable_tab.webview->load_uri(text); visable_tab.webview->grab_focus(); }); nb.signal_switch_page().connect([this] (auto, guint page_num) { switch_page(page_num); }); nb.signal_page_added().connect([this] (...) { nb.set_show_tabs(true); }); nb.signal_page_removed().connect([this] (...) { nb.set_show_tabs(nb.get_n_pages() > 1); }); new_tab.signal_clicked().connect([this] { auto n = open_new_tab(""); nb.set_current_page(n); }); show_webview(0, tabs.front()->wv); show_all_children(); } Browser::Tab::Tab(const Glib::ustring& uri) : wv{uri}, tab_title{"New tab"} { tab_title.set_can_focus(false); tab_title.set_hexpand(true); tab_title.set_ellipsize(Pango::ELLIPSIZE_END); tab_title.set_size_request(50, -1); tab_close.set_image_from_icon_name("window-close"); } int Browser::open_new_tab(const Glib::ustring& uri) { tabs.emplace_back(std::make_unique<Tab>(uri)); const auto& tab = tabs.back(); auto& wv = tab->wv; auto tab_content = make_managed<Gtk::Box>(); tab_content->set_can_focus(false); tab_content->add(tab->tab_title); tab_content->add(tab->tab_close); wv.show_all(); tab_content->show_all(); const auto n = nb.append_page(wv, *tab_content); nb.set_tab_reorderable(wv, true); tab->tab_close.signal_clicked().connect([this, &tab = *tab] { // NOTE: This is very fast because it does not need to // dereference every pointer in the tabs vector, but it // relies on the Tab struct never being moved. Currently // this holds true because moving for this type is disabled // (no move constructors or assignment operators exists). for (auto it = tabs.begin(); it != tabs.end(); ++it) { // Compare using pointer equality. We intentionally // captured a reference to the Tab, and not the // vector's unique_ptr<Tab>, so that we could take the // address of the actual Tab object without the // vector's unique_ptr having been zeroed after a move. if (it->get() != &tab) { continue; } tabs.erase(it); break; } if (tabs.size() == 0) { close(); } }); wv.connect_notify_title([this, &tab = *tab] { // Update tab title and the window title (if this tab is // currently visable) with the new page title. auto& wv = tab.wv; auto c_title = webkit_web_view_get_title(wv.gobj()); Glib::ustring title{c_title ? c_title : "(Untitled)"}; tab.tab_title.set_text(title); if (visable_tab.webview == &wv) { set_title(title); } }); return n; } void Browser::show_webview(unsigned int page_num, WebView& wv) { visable_tab = VisableTab{page_num, wv}; // Update navbar/titlebar with the current state of the webview being // shown. auto c_title = webkit_web_view_get_title(wv.gobj()); set_title(c_title ? c_title : "volo"); update_histnav(wv); nav_entry.set_uri(wv.get_uri()); page_signals = { { back.signal_clicked().connect([&wv] { wv.go_back(); }), fwd.signal_clicked().connect([&wv] { wv.go_forward(); }), wv.connect_back_forward_list_changed([this](WebKitBackForwardList *bfl) { if (visable_tab.bfl == bfl) { update_histnav(*visable_tab.webview); } }), wv.connect_notify_uri([this, &wv] { nav_entry.set_uri(wv.get_uri()); }), nav_entry.connect_refresh([&wv] { wv.reload(); }), } }; } void Browser::update_histnav(WebView& wv) { const auto p = wv.gobj(); back.set_sensitive(webkit_web_view_can_go_back(p)); fwd.set_sensitive(webkit_web_view_can_go_forward(p)); } void Browser::switch_page(unsigned int page_num) noexcept { // Disconnect previous WebView's signals before showing and connecting // the new WebView. for (auto& sig : page_signals) { sig.disconnect(); } show_webview(page_num, tabs.at(page_num)->wv); } int main(int argc, char **argv) { const auto app = Gtk::Application::create(argc, argv, "org.jrick.volo"); Browser b; return app->run(b); }
Comment fix.
Comment fix.
C++
isc
jrick/volo
cb8ef7403cb068abd1b6284610f48297fe7c4a87
digitanks/src/digitanks/structures/collector.cpp
digitanks/src/digitanks/structures/collector.cpp
#include "collector.h" #include <renderer/renderer.h> #include <ui/digitankswindow.h> #include <ui/hud.h> #include <digitanksteam.h> #include <digitanksgame.h> REGISTER_ENTITY(CCollector); NETVAR_TABLE_BEGIN(CCollector); NETVAR_DEFINE(CEntityHandle<CResource>, m_hResource); NETVAR_TABLE_END(); SAVEDATA_TABLE_BEGIN(CCollector); SAVEDATA_DEFINE(CSaveData::DATA_NETVAR, CEntityHandle<CResource>, m_hResource); SAVEDATA_TABLE_END(); INPUTS_TABLE_BEGIN(CCollector); INPUTS_TABLE_END(); void CCollector::Spawn() { BaseClass::Spawn(); SetModel(_T("models/structures/psu.obj")); } void CCollector::Precache() { BaseClass::Precache(); PrecacheModel(_T("models/structures/psu.obj")); } void CCollector::ClientSpawn() { BaseClass::ClientSpawn(); if (GameNetwork()->IsHost() && !GetResource()) { SetResource(CResource::FindClosestResource(GetOrigin(), GetResourceType())); if (GetResource()) GetResource()->SetCollector(this); else Delete(); } } void CCollector::UpdateInfo(tstring& s) { tstring p; s = _T(""); s += _T("POWER SUPPLY UNIT\n"); s += _T("Resource collector\n \n"); if (GetTeam()) { s += _T("Team: ") + GetTeam()->GetTeamName() + _T("\n"); if (GetDigitanksTeam() == DigitanksGame()->GetCurrentLocalDigitanksTeam()) s += _T(" Friendly\n \n"); else s += _T(" Hostile\n \n"); } else { s += _T("Team: Neutral\n \n"); } if (IsConstructing()) { s += _T("(Constructing)\n"); s += sprintf(tstring("Turns left: %d\n"), GetTurnsRemainingToConstruct()); return; } if (GetSupplier() && m_hSupplyLine != NULL) { s += sprintf(tstring("Power: %.1f/turn\n"), GetPowerProduced()); s += sprintf(tstring("Efficiency: %d\n"), (int)(m_hSupplier->GetChildEfficiency() * m_hSupplyLine->GetIntegrity() * 100)); return; } } float CCollector::GetPowerProduced() const { if (!m_hSupplyLine || GetSupplier() == NULL) return 0; return 1.2f * m_hSupplier->GetChildEfficiency() * m_hSupplyLine->GetIntegrity(); } REGISTER_ENTITY(CBattery); NETVAR_TABLE_BEGIN(CBattery); NETVAR_TABLE_END(); SAVEDATA_TABLE_BEGIN(CBattery); SAVEDATA_TABLE_END(); INPUTS_TABLE_BEGIN(CBattery); INPUTS_TABLE_END(); void CBattery::Spawn() { BaseClass::Spawn(); SetModel(_T("models/structures/battery.obj")); } void CBattery::Precache() { BaseClass::Precache(); PrecacheModel(_T("models/structures/battery.obj")); } void CBattery::SetupMenu(menumode_t eMenuMode) { CHUD* pHUD = DigitanksWindow()->GetHUD(); tstring p; if (!IsConstructing() && !IsUpgrading() && CanStructureUpgrade()) { pHUD->SetButtonTexture(0, "PSU"); if (UpgradeCost() <= GetDigitanksTeam()->GetPower()) { pHUD->SetButtonListener(0, CHUD::BeginUpgrade); pHUD->SetButtonColor(0, Color(50, 50, 50)); } tstring s; s += _T("UPGRADE TO POWER SUPPLY UNIT\n \n"); s += _T("Power Supply Units provide 2 additional Power per turn. Upgrading will make this structure inactive until the upgrade is complete.\n \n"); s += sprintf(tstring("Turns to upgrade: %d Turns\n \n"), GetTurnsToUpgrade()); s += _T("Shortcut: Q"); pHUD->SetButtonInfo(0, s); pHUD->SetButtonTooltip(0, _T("Upgrade To PSU")); } } void CBattery::UpdateInfo(tstring& s) { tstring p; s = _T(""); s += _T("CAPACITOR\n"); s += _T("Resource collector\n \n"); if (GetTeam()) { s += _T("Team: ") + GetTeam()->GetTeamName() + _T("\n"); if (GetDigitanksTeam() == DigitanksGame()->GetCurrentLocalDigitanksTeam()) s += _T(" Friendly\n \n"); else s += _T(" Hostile\n \n"); } else { s += _T("Team: Neutral\n \n"); } if (IsConstructing()) { s += _T("(Constructing)\n"); s += sprintf(tstring("Turns left: %d\n"), GetTurnsRemainingToConstruct()); return; } if (IsUpgrading()) { s += _T("(Upgrading to Power Supply Unit)\n"); s += sprintf(tstring("Turns left: %d\n"), GetTurnsRemainingToUpgrade()); return; } if (m_hSupplier != NULL && m_hSupplyLine != NULL) { s += sprintf(tstring("Power Supplied: %.1f\n"), GetPowerProduced()); s += sprintf(tstring("Efficiency: %d\n"), (int)(m_hSupplier->GetChildEfficiency() * m_hSupplyLine->GetIntegrity() * 100)); return; } } bool CBattery::CanStructureUpgrade() { if (!GetDigitanksTeam()) return false; return GetDigitanksTeam()->CanBuildPSUs(); } void CBattery::UpgradeComplete() { if (!GameNetwork()->IsHost()) return; CCollector* pCollector = GameServer()->Create<CCollector>("CCollector"); pCollector->SetConstructing(false); pCollector->SetOrigin(GetOrigin()); GetTeam()->AddEntity(pCollector); pCollector->SetSupplier(GetSupplier()); pCollector->SetResource(GetResource()); GetResource()->SetCollector(pCollector); pCollector->CalculateVisibility(); Delete(); GetDigitanksTeam()->AddActionItem(pCollector, ACTIONTYPE_UPGRADE); } float CBattery::GetPowerProduced() const { if (!m_hSupplyLine || !m_hSupplier) return 0; return 0.5f * m_hSupplier->GetChildEfficiency() * m_hSupplyLine->GetIntegrity(); }
#include "collector.h" #include <renderer/renderer.h> #include <ui/digitankswindow.h> #include <ui/hud.h> #include <digitanksteam.h> #include <digitanksgame.h> REGISTER_ENTITY(CCollector); NETVAR_TABLE_BEGIN(CCollector); NETVAR_DEFINE(CEntityHandle<CResource>, m_hResource); NETVAR_TABLE_END(); SAVEDATA_TABLE_BEGIN(CCollector); SAVEDATA_DEFINE(CSaveData::DATA_NETVAR, CEntityHandle<CResource>, m_hResource); SAVEDATA_TABLE_END(); INPUTS_TABLE_BEGIN(CCollector); INPUTS_TABLE_END(); void CCollector::Spawn() { BaseClass::Spawn(); SetModel(_T("models/structures/psu.obj")); } void CCollector::Precache() { BaseClass::Precache(); PrecacheModel(_T("models/structures/psu.obj")); } void CCollector::ClientSpawn() { BaseClass::ClientSpawn(); if (GameNetwork()->IsHost() && !GetResource()) { SetResource(CResource::FindClosestResource(GetOrigin(), GetResourceType())); if (GetResource()) GetResource()->SetCollector(this); else Delete(); } } void CCollector::UpdateInfo(tstring& s) { tstring p; s = _T(""); s += _T("POWER SUPPLY UNIT\n"); s += _T("Resource collector\n \n"); if (GetTeam()) { s += _T("Team: ") + GetTeam()->GetTeamName() + _T("\n"); if (GetDigitanksTeam() == DigitanksGame()->GetCurrentLocalDigitanksTeam()) s += _T(" Friendly\n \n"); else s += _T(" Hostile\n \n"); } else { s += _T("Team: Neutral\n \n"); } if (IsConstructing()) { s += _T("(Constructing)\n"); s += sprintf(tstring("Turns left: %d\n"), GetTurnsRemainingToConstruct()); return; } if (GetSupplier() && m_hSupplyLine != NULL) { s += sprintf(tstring("Power: %.1f/turn\n"), GetPowerProduced()); s += sprintf(tstring("Efficiency: %d\n"), (int)(m_hSupplier->GetChildEfficiency() * m_hSupplyLine->GetIntegrity() * 100)); return; } } float CCollector::GetPowerProduced() const { if (!m_hSupplyLine || GetSupplier() == NULL) return 0; return 1.2f * m_hSupplier->GetChildEfficiency() * m_hSupplyLine->GetIntegrity(); } REGISTER_ENTITY(CBattery); NETVAR_TABLE_BEGIN(CBattery); NETVAR_TABLE_END(); SAVEDATA_TABLE_BEGIN(CBattery); SAVEDATA_TABLE_END(); INPUTS_TABLE_BEGIN(CBattery); INPUTS_TABLE_END(); void CBattery::Spawn() { BaseClass::Spawn(); SetModel(_T("models/structures/battery.obj")); } void CBattery::Precache() { BaseClass::Precache(); PrecacheModel(_T("models/structures/battery.obj")); } void CBattery::SetupMenu(menumode_t eMenuMode) { CHUD* pHUD = DigitanksWindow()->GetHUD(); tstring p; if (!IsConstructing() && !IsUpgrading() && CanStructureUpgrade()) { pHUD->SetButtonTexture(0, "PSU"); if (UpgradeCost() <= GetDigitanksTeam()->GetPower()) { pHUD->SetButtonListener(0, CHUD::BeginUpgrade); pHUD->SetButtonColor(0, Color(50, 50, 50)); } tstring s; s += _T("UPGRADE TO POWER SUPPLY UNIT\n \n"); s += _T("Power Supply Units provide 2 additional Power per turn. Upgrading will make this structure inactive until the upgrade is complete.\n \n"); s += sprintf(tstring("Turns to upgrade: %d Turns\n \n"), GetTurnsToUpgrade()); s += _T("Shortcut: Q"); pHUD->SetButtonInfo(0, s); pHUD->SetButtonTooltip(0, _T("Upgrade To PSU")); } } void CBattery::UpdateInfo(tstring& s) { tstring p; s = _T(""); s += _T("CAPACITOR\n"); s += _T("Resource collector\n \n"); if (GetTeam()) { s += _T("Team: ") + GetTeam()->GetTeamName() + _T("\n"); if (GetDigitanksTeam() == DigitanksGame()->GetCurrentLocalDigitanksTeam()) s += _T(" Friendly\n \n"); else s += _T(" Hostile\n \n"); } else { s += _T("Team: Neutral\n \n"); } if (IsConstructing()) { s += _T("(Constructing)\n"); s += sprintf(tstring("Turns left: %d\n"), GetTurnsRemainingToConstruct()); return; } if (IsUpgrading()) { s += _T("(Upgrading to Power Supply Unit)\n"); s += sprintf(tstring("Turns left: %d\n"), GetTurnsRemainingToUpgrade()); return; } if (m_hSupplier != NULL && m_hSupplyLine != NULL) { s += sprintf(tstring("Power Supplied: %.1f\n"), GetPowerProduced()); s += sprintf(tstring("Efficiency: %d\n"), (int)(m_hSupplier->GetChildEfficiency() * m_hSupplyLine->GetIntegrity() * 100)); return; } } bool CBattery::CanStructureUpgrade() { if (!GetDigitanksTeam()) return false; return GetDigitanksTeam()->CanBuildPSUs(); } void CBattery::UpgradeComplete() { if (!GameNetwork()->IsHost()) return; CCollector* pCollector = GameServer()->Create<CCollector>("CCollector"); pCollector->SetConstructing(false); pCollector->SetOrigin(GetOrigin()); GetTeam()->AddEntity(pCollector); pCollector->SetSupplier(GetSupplier()); if (GetSupplier()) GetSupplier()->AddChild(pCollector); pCollector->SetResource(GetResource()); GetResource()->SetCollector(pCollector); pCollector->CalculateVisibility(); Delete(); GetDigitanksTeam()->AddActionItem(pCollector, ACTIONTYPE_UPGRADE); } float CBattery::GetPowerProduced() const { if (!m_hSupplyLine || !m_hSupplier) return 0; return 0.5f * m_hSupplier->GetChildEfficiency() * m_hSupplyLine->GetIntegrity(); }
Fix bug where upgraded PSU's got disconnected.
Fix bug where upgraded PSU's got disconnected.
C++
bsd-3-clause
BSVino/Digitanks,BSVino/Digitanks,BSVino/Digitanks,BSVino/Digitanks
8a721460c98532688ef09def39382db9d535d5d8
cyber/croutine/croutine.cc
cyber/croutine/croutine.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/croutine/croutine.h" #include <utility> #include "cyber/base/concurrent_object_pool.h" #include "cyber/common/global_data.h" #include "cyber/common/log.h" #include "cyber/croutine/routine_context.h" #include "cyber/event/perf_event_cache.h" namespace apollo { namespace cyber { namespace croutine { using apollo::cyber::event::PerfEventCache; using apollo::cyber::event::SchedPerf; thread_local CRoutine *CRoutine::current_routine_; thread_local std::shared_ptr<RoutineContext> CRoutine::main_context_; namespace { std::shared_ptr<base::CCObjectPool<RoutineContext>> context_pool = nullptr; void CRoutineEntry(void *arg) { CRoutine *r = static_cast<CRoutine *>(arg); r->Run(); CRoutine::Yield(RoutineState::FINISHED); } } // namespace CRoutine::CRoutine(const std::function<void()> &func) : func_(func) { if (unlikely(context_pool == nullptr)) { auto routine_num = 100; auto &global_conf = common::GlobalData::Instance()->Config(); if (global_conf.has_scheduler_conf() && global_conf.scheduler_conf().has_routine_num()) { routine_num = global_conf.scheduler_conf().routine_num(); } context_pool.reset(new base::CCObjectPool<RoutineContext>(routine_num)); } context_ = context_pool->GetObject(); CHECK_NOTNULL(context_); MakeContext(CRoutineEntry, this, context_.get()); state_ = RoutineState::READY; updated_.test_and_set(std::memory_order_release); } CRoutine::~CRoutine() { context_ = nullptr; } RoutineState CRoutine::Resume() { if (unlikely(force_stop_)) { state_ = RoutineState::FINISHED; return state_; } if (unlikely(state_ != RoutineState::READY)) { AERROR << "Invalid Routine State!"; return state_; } current_routine_ = this; PerfEventCache::Instance()->AddSchedEvent( SchedPerf::SWAP_IN, id_, processor_id_, static_cast<int>(state_)); SwapContext(GetMainContext(), this->GetContext()); PerfEventCache::Instance()->AddSchedEvent( SchedPerf::SWAP_OUT, id_, processor_id_, static_cast<int>(state_)); return state_; } void CRoutine::Routine() { while (true) { AINFO << "inner routine" << std::endl; usleep(1000000); } } void CRoutine::Stop() { force_stop_ = true; } } // namespace croutine } // namespace cyber } // namespace apollo
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/croutine/croutine.h" #include <utility> #include "cyber/base/concurrent_object_pool.h" #include "cyber/common/global_data.h" #include "cyber/common/log.h" #include "cyber/croutine/routine_context.h" #include "cyber/event/perf_event_cache.h" namespace apollo { namespace cyber { namespace croutine { using apollo::cyber::event::PerfEventCache; using apollo::cyber::event::SchedPerf; thread_local CRoutine *CRoutine::current_routine_; thread_local std::shared_ptr<RoutineContext> CRoutine::main_context_; namespace { std::shared_ptr<base::CCObjectPool<RoutineContext>> context_pool = nullptr; void CRoutineEntry(void *arg) { CRoutine *r = static_cast<CRoutine *>(arg); r->Run(); CRoutine::Yield(RoutineState::FINISHED); } } // namespace CRoutine::CRoutine(const std::function<void()> &func) : func_(func) { if (unlikely(context_pool == nullptr)) { auto routine_num = 100; auto &global_conf = common::GlobalData::Instance()->Config(); if (global_conf.has_scheduler_conf() && global_conf.scheduler_conf().has_routine_num()) { routine_num = global_conf.scheduler_conf().routine_num(); } context_pool.reset(new base::CCObjectPool<RoutineContext>(routine_num)); } context_ = context_pool->GetObject(); if (context_ == nullptr) { context_.reset(new RoutineContext()); } MakeContext(CRoutineEntry, this, context_.get()); state_ = RoutineState::READY; updated_.test_and_set(std::memory_order_release); } CRoutine::~CRoutine() { context_ = nullptr; } RoutineState CRoutine::Resume() { if (unlikely(force_stop_)) { state_ = RoutineState::FINISHED; return state_; } if (unlikely(state_ != RoutineState::READY)) { AERROR << "Invalid Routine State!"; return state_; } current_routine_ = this; PerfEventCache::Instance()->AddSchedEvent( SchedPerf::SWAP_IN, id_, processor_id_, static_cast<int>(state_)); SwapContext(GetMainContext(), this->GetContext()); PerfEventCache::Instance()->AddSchedEvent( SchedPerf::SWAP_OUT, id_, processor_id_, static_cast<int>(state_)); return state_; } void CRoutine::Routine() { while (true) { AINFO << "inner routine" << std::endl; usleep(1000000); } } void CRoutine::Stop() { force_stop_ = true; } } // namespace croutine } // namespace cyber } // namespace apollo
Add protect for croutine
framework: Add protect for croutine
C++
apache-2.0
ycool/apollo,wanglei828/apollo,ApolloAuto/apollo,jinghaomiao/apollo,xiaoxq/apollo,jinghaomiao/apollo,ycool/apollo,xiaoxq/apollo,jinghaomiao/apollo,ApolloAuto/apollo,ApolloAuto/apollo,wanglei828/apollo,xiaoxq/apollo,ycool/apollo,wanglei828/apollo,ApolloAuto/apollo,xiaoxq/apollo,ycool/apollo,wanglei828/apollo,jinghaomiao/apollo,ApolloAuto/apollo,ycool/apollo,jinghaomiao/apollo,jinghaomiao/apollo,ycool/apollo,wanglei828/apollo,ApolloAuto/apollo,xiaoxq/apollo,wanglei828/apollo,xiaoxq/apollo
2c0fbc0e8a07d26aa2832d29353cda0f17ce2dd9
dune/gdt/mapper/default/fv.hh
dune/gdt/mapper/default/fv.hh
// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_MAPPER_DEFAULT_FV_HH #define DUNE_GDT_MAPPER_DEFAULT_FV_HH #include <type_traits> #include <dune/common/dynvector.hh> #include <dune/common/typetraits.hh> #include <dune/stuff/common/debug.hh> #include "../../mapper/interface.hh" namespace Dune { namespace GDT { namespace Mapper { // forward template< class GridViewImp, int rangeDim = 1, int rangeDimCols = 1 > class FiniteVolume { static_assert(AlwaysFalse< GridViewImp >::value, "Not available for these dimensions!"); }; template< class GridViewImp, int rangeDim, int rangeDimCols > class FiniteVolumeTraits { static_assert(rangeDim >= 1, "Really?"); static_assert(rangeDimCols >= 1, "Really?"); public: typedef GridViewImp GridViewType; typedef FiniteVolume< GridViewType, rangeDim, rangeDimCols> derived_type; typedef typename GridViewImp::IndexSet BackendType; typedef typename GridViewType::template Codim< 0 >::Entity EntityType; }; template< class GridViewImp > class FiniteVolume< GridViewImp, 1, 1 > : public MapperInterface< FiniteVolumeTraits< GridViewImp, 1, 1 > > { typedef MapperInterface< FiniteVolumeTraits< GridViewImp, 1, 1 > > InterfaceType; public: typedef FiniteVolumeTraits< GridViewImp, 1, 1 > Traits; typedef typename Traits::GridViewType GridViewType; typedef typename Traits::BackendType BackendType; typedef typename Traits::EntityType EntityType; FiniteVolume(const GridViewType& grid_view) : backend_(grid_view.indexSet()) {} const BackendType& backend() const { return backend_; } size_t size() const { return backend_.size(0); } size_t numDofs(const EntityType& /*entity*/) const { return 1; } size_t maxNumDofs() const { return 1; } void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const { if (ret.size() < 1) ret.resize(1); ret[0] = mapToGlobal(entity, 0); } // ... globalIndices(...) using InterfaceType::globalIndices; size_t mapToGlobal(const EntityType& entity, const size_t& UNUSED_UNLESS_DEBUG(localIndex)) const { assert(localIndex == 0); return backend_.index(entity); } private: const BackendType& backend_; }; // class FiniteVolume< ..., 1, 1 > template< class GridViewImp, int rangeDim > class FiniteVolume< GridViewImp, rangeDim, 1 > : public MapperInterface< FiniteVolumeTraits< GridViewImp, rangeDim, 1 > > { typedef MapperInterface< FiniteVolumeTraits< GridViewImp, rangeDim, 1 > > InterfaceType; static const unsigned int dimRange = rangeDim; public: typedef internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > Traits; typedef typename Traits::GridViewType GridViewType; typedef typename Traits::BackendType BackendType; typedef typename Traits::EntityType EntityType; FiniteVolume(const GridViewType& grid_view) : backend_(grid_view.indexSet()) {} const BackendType& backend() const { return backend_; } size_t size() const { return dimRange * backend_.size(0); } size_t numDofs(const EntityType& /*entity*/) const { return dimRange; } size_t maxNumDofs() const { return dimRange; } void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const { if (ret.size() < dimRange) ret.resize(dimRange); const size_t base = dimRange * backend_.index(entity); for (size_t ii = 0; ii < dimRange; ++ii) ret[ii] = base + ii; } // ... globalIndices(...) using InterfaceType::globalIndices; size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const { assert(localIndex < dimRange); return (dimRange * backend_.index(entity)) + localIndex; } private: const BackendType& backend_; }; // class FiniteVolume< ..., rangeDim, 1 > } // namespace Mapper } // namespace GDT } // namespace Dune #endif // DUNE_GDT_MAPPER_DEFAULT_FV_HH
// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_MAPPER_DEFAULT_FV_HH #define DUNE_GDT_MAPPER_DEFAULT_FV_HH #include <type_traits> #include <dune/common/dynvector.hh> #include <dune/common/typetraits.hh> #include <dune/stuff/common/debug.hh> #include "../../mapper/interface.hh" namespace Dune { namespace GDT { namespace Mapper { // forward template< class GridViewImp, int rangeDim = 1, int rangeDimCols = 1 > class FiniteVolume { static_assert(AlwaysFalse< GridViewImp >::value, "Not available for these dimensions!"); }; namespace internal { template< class GridViewImp, int rangeDim, int rangeDimCols > class FiniteVolumeTraits { static_assert(rangeDim >= 1, "Really?"); static_assert(rangeDimCols >= 1, "Really?"); public: typedef GridViewImp GridViewType; typedef FiniteVolume< GridViewType, rangeDim, rangeDimCols> derived_type; typedef typename GridViewImp::IndexSet BackendType; typedef typename GridViewType::template Codim< 0 >::Entity EntityType; }; } // namespace internal template< class GridViewImp > class FiniteVolume< GridViewImp, 1, 1 > : public MapperInterface< internal::FiniteVolumeTraits< GridViewImp, 1, 1 > > { typedef MapperInterface< internal::FiniteVolumeTraits< GridViewImp, 1, 1 > > InterfaceType; public: typedef internal::FiniteVolumeTraits< GridViewImp, 1, 1 > Traits; typedef typename Traits::GridViewType GridViewType; typedef typename Traits::BackendType BackendType; typedef typename Traits::EntityType EntityType; FiniteVolume(const GridViewType& grid_view) : backend_(grid_view.indexSet()) {} const BackendType& backend() const { return backend_; } size_t size() const { return backend_.size(0); } size_t numDofs(const EntityType& /*entity*/) const { return 1; } size_t maxNumDofs() const { return 1; } void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const { if (ret.size() < 1) ret.resize(1); ret[0] = mapToGlobal(entity, 0); } // ... globalIndices(...) using InterfaceType::globalIndices; size_t mapToGlobal(const EntityType& entity, const size_t& UNUSED_UNLESS_DEBUG(localIndex)) const { assert(localIndex == 0); return backend_.index(entity); } private: const BackendType& backend_; }; // class FiniteVolume< ..., 1, 1 > template< class GridViewImp, int rangeDim > class FiniteVolume< GridViewImp, rangeDim, 1 > : public MapperInterface< internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > > { typedef MapperInterface< internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > > InterfaceType; static const unsigned int dimRange = rangeDim; public: typedef internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > Traits; typedef typename Traits::GridViewType GridViewType; typedef typename Traits::BackendType BackendType; typedef typename Traits::EntityType EntityType; FiniteVolume(const GridViewType& grid_view) : backend_(grid_view.indexSet()) {} const BackendType& backend() const { return backend_; } size_t size() const { return dimRange * backend_.size(0); } size_t numDofs(const EntityType& /*entity*/) const { return dimRange; } size_t maxNumDofs() const { return dimRange; } void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const { if (ret.size() < dimRange) ret.resize(dimRange); const size_t base = dimRange * backend_.index(entity); for (size_t ii = 0; ii < dimRange; ++ii) ret[ii] = base + ii; } // ... globalIndices(...) using InterfaceType::globalIndices; size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const { assert(localIndex < dimRange); return (dimRange * backend_.index(entity)) + localIndex; } private: const BackendType& backend_; }; // class FiniteVolume< ..., rangeDim, 1 > } // namespace Mapper } // namespace GDT } // namespace Dune #endif // DUNE_GDT_MAPPER_DEFAULT_FV_HH
move traits to internal namespace
[mapper.default.fv] move traits to internal namespace
C++
bsd-2-clause
ftalbrecht/dune-gdt,BarbaraV/dune-gdt
1dfb95de22990708b0172826803796c803d0b4f9
editor/editor_spin_slider.cpp
editor/editor_spin_slider.cpp
#include "editor_spin_slider.h" #include "editor_scale.h" #include "os/input.h" String EditorSpinSlider::get_text_value() const { int zeros = Math::step_decimals(get_step()); return String::num(get_value(), zeros); } void EditorSpinSlider::_gui_input(const Ref<InputEvent> &p_event) { Ref<InputEventMouseButton> mb = p_event; if (mb.is_valid() && mb->get_button_index() == BUTTON_LEFT) { if (mb->is_pressed()) { if (updown_offset != -1 && mb->get_position().x > updown_offset) { //there is an updown, so use it. if (mb->get_position().y < get_size().height / 2) { set_value(get_value() + get_step()); } else { set_value(get_value() - get_step()); } return; } else { grabbing_spinner_attempt = true; grabbing_spinner = false; grabbing_spinner_mouse_pos = Input::get_singleton()->get_mouse_position(); } } else { if (grabbing_spinner_attempt) { if (grabbing_spinner) { Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE); Input::get_singleton()->warp_mouse_position(grabbing_spinner_mouse_pos); update(); } else { Rect2 gr = get_global_rect(); value_input->set_text(get_text_value()); value_input->set_position(gr.position); value_input->set_size(gr.size); value_input->call_deferred("show_modal"); value_input->call_deferred("grab_focus"); value_input->call_deferred("select_all"); } grabbing_spinner = false; grabbing_spinner_attempt = false; } } } Ref<InputEventMouseMotion> mm = p_event; if (mm.is_valid()) { if (grabbing_spinner_attempt) { if (!grabbing_spinner) { Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED); grabbing_spinner = true; } double v = get_value(); double diff_x = mm->get_relative().x; diff_x = Math::pow(ABS(diff_x), 1.8f) * SGN(diff_x); diff_x *= 0.1; v += diff_x * get_step(); set_value(v); } else if (updown_offset != -1) { bool new_hover = (mm->get_position().x > updown_offset); if (new_hover != hover_updown) { hover_updown = new_hover; update(); } } } Ref<InputEventKey> k = p_event; if (k.is_valid() && k->is_pressed() && k->is_action("ui_accept")) { Rect2 gr = get_global_rect(); value_input->set_text(get_text_value()); value_input->set_position(gr.position); value_input->set_size(gr.size); value_input->call_deferred("show_modal"); value_input->call_deferred("grab_focus"); value_input->call_deferred("select_all"); } } void EditorSpinSlider::_value_input_closed() { set_value(value_input->get_text().to_double()); } void EditorSpinSlider::_value_input_entered(const String &p_text) { set_value(p_text.to_double()); value_input->hide(); } void EditorSpinSlider::_grabber_gui_input(const Ref<InputEvent> &p_event) { Ref<InputEventMouseButton> mb = p_event; if (mb.is_valid() && mb->get_button_index() == BUTTON_LEFT) { if (mb->is_pressed()) { grabbing_grabber = true; grabbing_ratio = get_as_ratio(); grabbing_from = grabber->get_transform().xform(mb->get_position()).x; } else { grabbing_grabber = false; } } Ref<InputEventMouseMotion> mm = p_event; if (mm.is_valid() && grabbing_grabber) { float grabbing_ofs = (grabber->get_transform().xform(mm->get_position()).x - grabbing_from) / float(grabber_range); set_as_ratio(grabbing_ratio + grabbing_ofs); update(); } } void EditorSpinSlider::_notification(int p_what) { if (p_what == MainLoop::NOTIFICATION_WM_FOCUS_OUT || p_what == MainLoop::NOTIFICATION_WM_FOCUS_OUT) { if (grabbing_spinner) { Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE); grabbing_spinner = false; grabbing_spinner_attempt = false; } } if (p_what == NOTIFICATION_DRAW) { updown_offset = -1; Ref<StyleBox> sb = get_stylebox("normal", "LineEdit"); draw_style_box(sb, Rect2(Vector2(), get_size())); Ref<Font> font = get_font("font", "LineEdit"); int avail_width = get_size().width - sb->get_minimum_size().width - sb->get_minimum_size().width; avail_width -= font->get_string_size(label).width; Ref<Texture> updown = get_icon("updown", "SpinBox"); if (get_step() == 1) { avail_width -= updown->get_width(); } if (has_focus()) { Ref<StyleBox> focus = get_stylebox("focus", "LineEdit"); draw_style_box(focus, Rect2(Vector2(), get_size())); } String numstr = get_text_value(); int vofs = (get_size().height - font->get_height()) / 2 + font->get_ascent(); Color fc = get_color("font_color", "LineEdit"); int label_ofs = sb->get_offset().x + avail_width; draw_string(font, Vector2(label_ofs, vofs), label, fc * Color(1, 1, 1, 0.5)); draw_string(font, Vector2(sb->get_offset().x, vofs), numstr, fc, avail_width); if (get_step() == 1) { Ref<Texture> updown = get_icon("updown", "SpinBox"); int updown_vofs = (get_size().height - updown->get_height()) / 2; updown_offset = get_size().width - sb->get_margin(MARGIN_RIGHT) - updown->get_width(); Color c(1, 1, 1); if (hover_updown) { c *= Color(1.2, 1.2, 1.2); } draw_texture(updown, Vector2(updown_offset, updown_vofs), c); if (grabber->is_visible()) { grabber->hide(); } } else if (!hide_slider) { int grabber_w = 4 * EDSCALE; int width = get_size().width - sb->get_minimum_size().width - grabber_w; int ofs = sb->get_offset().x; int svofs = (get_size().height + vofs) / 2 - 1; Color c = fc; c.a = 0.2; draw_rect(Rect2(ofs, svofs + 1, width, 2 * EDSCALE), c); int gofs = get_as_ratio() * width; c.a = 0.9; Rect2 grabber_rect = Rect2(ofs + gofs, svofs + 1, grabber_w, 2 * EDSCALE); draw_rect(grabber_rect, c); bool display_grabber = (mouse_over_spin || mouse_over_grabber) && !grabbing_spinner; if (grabber->is_visible() != display_grabber) { if (display_grabber) { grabber->show(); } else { grabber->hide(); } } if (display_grabber) { Ref<Texture> grabber_tex; if (mouse_over_grabber) { grabber_tex = get_icon("grabber_highlight", "HSlider"); } else { grabber_tex = get_icon("grabber", "HSlider"); } if (grabber->get_texture() != grabber_tex) { grabber->set_texture(grabber_tex); } grabber->set_size(Size2(0, 0)); grabber->set_position(get_global_position() + grabber_rect.position + grabber_rect.size * 0.5 - grabber->get_size() * 0.5); grabber_range = width; } } } if (p_what == NOTIFICATION_MOUSE_ENTER) { mouse_over_spin = true; update(); } if (p_what == NOTIFICATION_MOUSE_EXIT) { mouse_over_spin = false; update(); } } Size2 EditorSpinSlider::get_minimum_size() const { Ref<StyleBox> sb = get_stylebox("normal", "LineEdit"); Ref<Font> font = get_font("font", "LineEdit"); Size2 ms = sb->get_minimum_size(); ms.height += font->get_height(); return ms; } void EditorSpinSlider::set_hide_slider(bool p_hide) { hide_slider = p_hide; update(); } bool EditorSpinSlider::is_hiding_slider() const { return hide_slider; } void EditorSpinSlider::set_label(const String &p_label) { label = p_label; update(); } String EditorSpinSlider::get_label() const { return label; } void EditorSpinSlider::_grabber_mouse_entered() { mouse_over_grabber = true; update(); } void EditorSpinSlider::_grabber_mouse_exited() { mouse_over_grabber = false; update(); } void EditorSpinSlider::_bind_methods() { ClassDB::bind_method(D_METHOD("set_label", "label"), &EditorSpinSlider::set_label); ClassDB::bind_method(D_METHOD("get_label"), &EditorSpinSlider::get_label); ClassDB::bind_method(D_METHOD("_gui_input"), &EditorSpinSlider::_gui_input); ClassDB::bind_method(D_METHOD("_grabber_mouse_entered"), &EditorSpinSlider::_grabber_mouse_entered); ClassDB::bind_method(D_METHOD("_grabber_mouse_exited"), &EditorSpinSlider::_grabber_mouse_exited); ClassDB::bind_method(D_METHOD("_grabber_gui_input"), &EditorSpinSlider::_grabber_gui_input); ClassDB::bind_method(D_METHOD("_value_input_closed"), &EditorSpinSlider::_value_input_closed); ClassDB::bind_method(D_METHOD("_value_input_entered"), &EditorSpinSlider::_value_input_entered); ADD_PROPERTY(PropertyInfo(Variant::STRING, "label"), "set_label", "get_label"); } EditorSpinSlider::EditorSpinSlider() { grabbing_spinner_attempt = false; grabbing_spinner = false; set_focus_mode(FOCUS_ALL); updown_offset = -1; hover_updown = false; grabber = memnew(TextureRect); add_child(grabber); grabber->hide(); grabber->set_as_toplevel(true); grabber->set_mouse_filter(MOUSE_FILTER_STOP); grabber->connect("mouse_entered", this, "_grabber_mouse_entered"); grabber->connect("mouse_exited", this, "_grabber_mouse_exited"); grabber->connect("gui_input", this, "_grabber_gui_input"); mouse_over_spin = false; mouse_over_grabber = false; grabbing_grabber = false; grabber_range = 1; value_input = memnew(LineEdit); add_child(value_input); value_input->set_as_toplevel(true); value_input->hide(); value_input->connect("modal_closed", this, "_value_input_closed"); value_input->connect("text_entered", this, "_value_input_entered"); hide_slider = false; }
#include "editor_spin_slider.h" #include "editor_scale.h" #include "os/input.h" String EditorSpinSlider::get_text_value() const { int zeros = Math::step_decimals(get_step()); return String::num(get_value(), zeros); } void EditorSpinSlider::_gui_input(const Ref<InputEvent> &p_event) { Ref<InputEventMouseButton> mb = p_event; if (mb.is_valid() && mb->get_button_index() == BUTTON_LEFT) { if (mb->is_pressed()) { if (updown_offset != -1 && mb->get_position().x > updown_offset) { //there is an updown, so use it. if (mb->get_position().y < get_size().height / 2) { set_value(get_value() + get_step()); } else { set_value(get_value() - get_step()); } return; } else { grabbing_spinner_attempt = true; grabbing_spinner = false; grabbing_spinner_mouse_pos = Input::get_singleton()->get_mouse_position(); } } else { if (grabbing_spinner_attempt) { if (grabbing_spinner) { Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE); Input::get_singleton()->warp_mouse_position(grabbing_spinner_mouse_pos); update(); } else { Rect2 gr = get_global_rect(); value_input->set_text(get_text_value()); value_input->set_position(gr.position); value_input->set_size(gr.size); value_input->call_deferred("show_modal"); value_input->call_deferred("grab_focus"); value_input->call_deferred("select_all"); } grabbing_spinner = false; grabbing_spinner_attempt = false; } } } Ref<InputEventMouseMotion> mm = p_event; if (mm.is_valid()) { if (grabbing_spinner_attempt) { if (!grabbing_spinner) { Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED); grabbing_spinner = true; } double v = get_value(); double diff_x = mm->get_relative().x; diff_x = Math::pow(ABS(diff_x), 1.8) * SGN(diff_x); diff_x *= 0.1; v += diff_x * get_step(); set_value(v); } else if (updown_offset != -1) { bool new_hover = (mm->get_position().x > updown_offset); if (new_hover != hover_updown) { hover_updown = new_hover; update(); } } } Ref<InputEventKey> k = p_event; if (k.is_valid() && k->is_pressed() && k->is_action("ui_accept")) { Rect2 gr = get_global_rect(); value_input->set_text(get_text_value()); value_input->set_position(gr.position); value_input->set_size(gr.size); value_input->call_deferred("show_modal"); value_input->call_deferred("grab_focus"); value_input->call_deferred("select_all"); } } void EditorSpinSlider::_value_input_closed() { set_value(value_input->get_text().to_double()); } void EditorSpinSlider::_value_input_entered(const String &p_text) { set_value(p_text.to_double()); value_input->hide(); } void EditorSpinSlider::_grabber_gui_input(const Ref<InputEvent> &p_event) { Ref<InputEventMouseButton> mb = p_event; if (mb.is_valid() && mb->get_button_index() == BUTTON_LEFT) { if (mb->is_pressed()) { grabbing_grabber = true; grabbing_ratio = get_as_ratio(); grabbing_from = grabber->get_transform().xform(mb->get_position()).x; } else { grabbing_grabber = false; } } Ref<InputEventMouseMotion> mm = p_event; if (mm.is_valid() && grabbing_grabber) { float grabbing_ofs = (grabber->get_transform().xform(mm->get_position()).x - grabbing_from) / float(grabber_range); set_as_ratio(grabbing_ratio + grabbing_ofs); update(); } } void EditorSpinSlider::_notification(int p_what) { if (p_what == MainLoop::NOTIFICATION_WM_FOCUS_OUT || p_what == MainLoop::NOTIFICATION_WM_FOCUS_OUT) { if (grabbing_spinner) { Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE); grabbing_spinner = false; grabbing_spinner_attempt = false; } } if (p_what == NOTIFICATION_DRAW) { updown_offset = -1; Ref<StyleBox> sb = get_stylebox("normal", "LineEdit"); draw_style_box(sb, Rect2(Vector2(), get_size())); Ref<Font> font = get_font("font", "LineEdit"); int avail_width = get_size().width - sb->get_minimum_size().width - sb->get_minimum_size().width; avail_width -= font->get_string_size(label).width; Ref<Texture> updown = get_icon("updown", "SpinBox"); if (get_step() == 1) { avail_width -= updown->get_width(); } if (has_focus()) { Ref<StyleBox> focus = get_stylebox("focus", "LineEdit"); draw_style_box(focus, Rect2(Vector2(), get_size())); } String numstr = get_text_value(); int vofs = (get_size().height - font->get_height()) / 2 + font->get_ascent(); Color fc = get_color("font_color", "LineEdit"); int label_ofs = sb->get_offset().x + avail_width; draw_string(font, Vector2(label_ofs, vofs), label, fc * Color(1, 1, 1, 0.5)); draw_string(font, Vector2(sb->get_offset().x, vofs), numstr, fc, avail_width); if (get_step() == 1) { Ref<Texture> updown = get_icon("updown", "SpinBox"); int updown_vofs = (get_size().height - updown->get_height()) / 2; updown_offset = get_size().width - sb->get_margin(MARGIN_RIGHT) - updown->get_width(); Color c(1, 1, 1); if (hover_updown) { c *= Color(1.2, 1.2, 1.2); } draw_texture(updown, Vector2(updown_offset, updown_vofs), c); if (grabber->is_visible()) { grabber->hide(); } } else if (!hide_slider) { int grabber_w = 4 * EDSCALE; int width = get_size().width - sb->get_minimum_size().width - grabber_w; int ofs = sb->get_offset().x; int svofs = (get_size().height + vofs) / 2 - 1; Color c = fc; c.a = 0.2; draw_rect(Rect2(ofs, svofs + 1, width, 2 * EDSCALE), c); int gofs = get_as_ratio() * width; c.a = 0.9; Rect2 grabber_rect = Rect2(ofs + gofs, svofs + 1, grabber_w, 2 * EDSCALE); draw_rect(grabber_rect, c); bool display_grabber = (mouse_over_spin || mouse_over_grabber) && !grabbing_spinner; if (grabber->is_visible() != display_grabber) { if (display_grabber) { grabber->show(); } else { grabber->hide(); } } if (display_grabber) { Ref<Texture> grabber_tex; if (mouse_over_grabber) { grabber_tex = get_icon("grabber_highlight", "HSlider"); } else { grabber_tex = get_icon("grabber", "HSlider"); } if (grabber->get_texture() != grabber_tex) { grabber->set_texture(grabber_tex); } grabber->set_size(Size2(0, 0)); grabber->set_position(get_global_position() + grabber_rect.position + grabber_rect.size * 0.5 - grabber->get_size() * 0.5); grabber_range = width; } } } if (p_what == NOTIFICATION_MOUSE_ENTER) { mouse_over_spin = true; update(); } if (p_what == NOTIFICATION_MOUSE_EXIT) { mouse_over_spin = false; update(); } } Size2 EditorSpinSlider::get_minimum_size() const { Ref<StyleBox> sb = get_stylebox("normal", "LineEdit"); Ref<Font> font = get_font("font", "LineEdit"); Size2 ms = sb->get_minimum_size(); ms.height += font->get_height(); return ms; } void EditorSpinSlider::set_hide_slider(bool p_hide) { hide_slider = p_hide; update(); } bool EditorSpinSlider::is_hiding_slider() const { return hide_slider; } void EditorSpinSlider::set_label(const String &p_label) { label = p_label; update(); } String EditorSpinSlider::get_label() const { return label; } void EditorSpinSlider::_grabber_mouse_entered() { mouse_over_grabber = true; update(); } void EditorSpinSlider::_grabber_mouse_exited() { mouse_over_grabber = false; update(); } void EditorSpinSlider::_bind_methods() { ClassDB::bind_method(D_METHOD("set_label", "label"), &EditorSpinSlider::set_label); ClassDB::bind_method(D_METHOD("get_label"), &EditorSpinSlider::get_label); ClassDB::bind_method(D_METHOD("_gui_input"), &EditorSpinSlider::_gui_input); ClassDB::bind_method(D_METHOD("_grabber_mouse_entered"), &EditorSpinSlider::_grabber_mouse_entered); ClassDB::bind_method(D_METHOD("_grabber_mouse_exited"), &EditorSpinSlider::_grabber_mouse_exited); ClassDB::bind_method(D_METHOD("_grabber_gui_input"), &EditorSpinSlider::_grabber_gui_input); ClassDB::bind_method(D_METHOD("_value_input_closed"), &EditorSpinSlider::_value_input_closed); ClassDB::bind_method(D_METHOD("_value_input_entered"), &EditorSpinSlider::_value_input_entered); ADD_PROPERTY(PropertyInfo(Variant::STRING, "label"), "set_label", "get_label"); } EditorSpinSlider::EditorSpinSlider() { grabbing_spinner_attempt = false; grabbing_spinner = false; set_focus_mode(FOCUS_ALL); updown_offset = -1; hover_updown = false; grabber = memnew(TextureRect); add_child(grabber); grabber->hide(); grabber->set_as_toplevel(true); grabber->set_mouse_filter(MOUSE_FILTER_STOP); grabber->connect("mouse_entered", this, "_grabber_mouse_entered"); grabber->connect("mouse_exited", this, "_grabber_mouse_exited"); grabber->connect("gui_input", this, "_grabber_gui_input"); mouse_over_spin = false; mouse_over_grabber = false; grabbing_grabber = false; grabber_range = 1; value_input = memnew(LineEdit); add_child(value_input); value_input->set_as_toplevel(true); value_input->hide(); value_input->connect("modal_closed", this, "_value_input_closed"); value_input->connect("text_entered", this, "_value_input_entered"); hide_slider = false; }
Fix compile error with clang
Fix compile error with clang
C++
mit
honix/godot,Paulloz/godot,sanikoyes/godot,okamstudio/godot,BastiaanOlij/godot,Valentactive/godot,guilhermefelipecgs/godot,godotengine/godot,mcanders/godot,ZuBsPaCe/godot,vkbsb/godot,godotengine/godot,DmitriySalnikov/godot,ZuBsPaCe/godot,DmitriySalnikov/godot,firefly2442/godot,akien-mga/godot,akien-mga/godot,vnen/godot,okamstudio/godot,josempans/godot,Paulloz/godot,ex/godot,ex/godot,Zylann/godot,groud/godot,josempans/godot,vkbsb/godot,MarianoGnu/godot,BastiaanOlij/godot,vnen/godot,MarianoGnu/godot,akien-mga/godot,NateWardawg/godot,Zylann/godot,firefly2442/godot,RandomShaper/godot,pkowal1982/godot,Zylann/godot,akien-mga/godot,Zylann/godot,Zylann/godot,Paulloz/godot,honix/godot,pkowal1982/godot,okamstudio/godot,okamstudio/godot,okamstudio/godot,josempans/godot,pkowal1982/godot,akien-mga/godot,pkowal1982/godot,firefly2442/godot,MarianoGnu/godot,pkowal1982/godot,guilhermefelipecgs/godot,akien-mga/godot,okamstudio/godot,sanikoyes/godot,Zylann/godot,Valentactive/godot,godotengine/godot,sanikoyes/godot,RandomShaper/godot,vnen/godot,Faless/godot,godotengine/godot,vnen/godot,RandomShaper/godot,vkbsb/godot,mcanders/godot,Valentactive/godot,vnen/godot,firefly2442/godot,okamstudio/godot,BastiaanOlij/godot,Faless/godot,honix/godot,MarianoGnu/godot,Zylann/godot,Shockblast/godot,ZuBsPaCe/godot,BastiaanOlij/godot,DmitriySalnikov/godot,RandomShaper/godot,ZuBsPaCe/godot,NateWardawg/godot,vkbsb/godot,Faless/godot,Paulloz/godot,ex/godot,NateWardawg/godot,Shockblast/godot,Faless/godot,akien-mga/godot,akien-mga/godot,Valentactive/godot,NateWardawg/godot,sanikoyes/godot,guilhermefelipecgs/godot,firefly2442/godot,mcanders/godot,groud/godot,ex/godot,groud/godot,okamstudio/godot,vkbsb/godot,MarianoGnu/godot,Zylann/godot,mcanders/godot,Shockblast/godot,ZuBsPaCe/godot,groud/godot,sanikoyes/godot,Shockblast/godot,BastiaanOlij/godot,Paulloz/godot,ex/godot,godotengine/godot,BastiaanOlij/godot,groud/godot,godotengine/godot,ex/godot,firefly2442/godot,honix/godot,MarianoGnu/godot,RandomShaper/godot,Shockblast/godot,guilhermefelipecgs/godot,pkowal1982/godot,Paulloz/godot,MarianoGnu/godot,Faless/godot,groud/godot,NateWardawg/godot,vnen/godot,guilhermefelipecgs/godot,mcanders/godot,vkbsb/godot,ZuBsPaCe/godot,RandomShaper/godot,godotengine/godot,ZuBsPaCe/godot,Shockblast/godot,mcanders/godot,vnen/godot,BastiaanOlij/godot,josempans/godot,josempans/godot,pkowal1982/godot,godotengine/godot,sanikoyes/godot,NateWardawg/godot,NateWardawg/godot,Shockblast/godot,vkbsb/godot,ex/godot,guilhermefelipecgs/godot,DmitriySalnikov/godot,Paulloz/godot,honix/godot,Faless/godot,sanikoyes/godot,DmitriySalnikov/godot,guilhermefelipecgs/godot,josempans/godot,sanikoyes/godot,firefly2442/godot,guilhermefelipecgs/godot,okamstudio/godot,josempans/godot,vnen/godot,DmitriySalnikov/godot,honix/godot,pkowal1982/godot,NateWardawg/godot,RandomShaper/godot,DmitriySalnikov/godot,Shockblast/godot,josempans/godot,Faless/godot,okamstudio/godot,Valentactive/godot,vkbsb/godot,Valentactive/godot,NateWardawg/godot,BastiaanOlij/godot,firefly2442/godot,Valentactive/godot,MarianoGnu/godot,ex/godot,Valentactive/godot,ZuBsPaCe/godot,Faless/godot
aca4d730eca663941beb71f281aa70651471a28e
tools/tankview/tankview.cpp
tools/tankview/tankview.cpp
// tankview.cpp : Defines the entry point for the application. // #include "tankview.h" #include "Model.h" #include "config.h" #include "TextUtils.h" // for the stupid debug openGLcount model uses #ifdef DEBUG int __beginendCount; #endif class Application : public SimpleDisplayEventCallbacks { public: Application(); virtual void key ( int key, bool down, const ModiferKeys& mods ); virtual void mouseButton( int key, int x, int y, bool down ); virtual void mouseMoved( int x, int y ); int run ( void ); protected: bool init ( void ); void drawGridAndBounds ( void ); void loadModels ( void ); void drawModels ( void ); void drawObjectNormals ( OBJModel &model ); SimpleDisplay display; SimpleDisplayCamera *camera; OBJModel base,turret,barrel,lTread,rTread; unsigned int red,green,blue,purple,black,current; bool moveKeysDown[3]; int mousePos[2]; }; const char* convertPath ( const char* path ) { static std::string temp; if (!path) return NULL; temp = path; #ifdef _WIN32 temp = TextUtils::replace_all(temp,std::string("/"),std::string("\\")); #endif return temp.c_str(); } Application::Application() : display(800,600,false,"tankview") { camera = NULL; for (int i = 0; i<3; i++) moveKeysDown[i] = false; } void Application::drawGridAndBounds ( void ) { glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glBegin(GL_LINES); // axis markers glColor4f(1,0,0,0.25f); glVertex3f(0,0,0); glVertex3f(1,0,0); glColor4f(0,1,0,0.25f); glVertex3f(0,0,0); glVertex3f(0,1,0); glColor4f(0,0,1,0.25f); glVertex3f(0,0,0); glVertex3f(0,0,1); // grid glColor4f(1,1,1,0.125f); float grid = 10.0f; float increment = 0.25f; for( float i = -grid; i <= grid; i += increment ) { glVertex3f(i,grid,0); glVertex3f(i,-grid,0); glVertex3f(grid,i,0); glVertex3f(-grid,i,0); } // tank bbox glColor4f(0,1,1,0.25f); float width = 1.4f; float height = 2.05f; float front = 4.94f; float back = -3.10f; // front glVertex3f(front,-width,0); glVertex3f(front,width,0); glVertex3f(front,width,0); glVertex3f(front,width,height); glVertex3f(front,-width,height); glVertex3f(front,width,height); glVertex3f(front,-width,0); glVertex3f(front,-width,height); // back glVertex3f(back,-width,0); glVertex3f(back,width,0); glVertex3f(back,width,0); glVertex3f(back,width,height); glVertex3f(back,-width,height); glVertex3f(back,width,height); glVertex3f(back,-width,0); glVertex3f(back,-width,height); // sides glVertex3f(back,-width,0); glVertex3f(front,-width,0); glVertex3f(back,width,0); glVertex3f(front,width,0); glVertex3f(back,-width,height); glVertex3f(front,-width,height); glVertex3f(back,width,height); glVertex3f(front,width,height); glEnd(); glColor4f(1,1,1,1); } void Application::loadModels ( void ) { barrel.read(convertPath("./data/geometry/tank/std/barrel.obj")); base.read(convertPath("./data/geometry/tank/std/body.obj")); turret.read(convertPath("./data/geometry/tank/std/turret.obj")); lTread.read(convertPath("./data/geometry/tank/std/lcasing.obj")); rTread.read(convertPath("/.data/geometry/tank/std/rcasing.obj")); red = display.loadImage(convertPath("./data/skins/red/tank.png")); green = display.loadImage(convertPath("./data/skins/green/tank.png")); blue = display.loadImage(convertPath("./data/skins/blue/tank.png")); purple = display.loadImage(convertPath("./data/skins/purple/tank.png")); black = display.loadImage(convertPath("./data/skins/rogue/tank.png")); current = green; } void Application::drawModels ( void ) { base.draw(); lTread.draw(); rTread.draw(); turret.draw(); barrel.draw(); } void Application::drawObjectNormals ( OBJModel &model ) { glBegin(GL_LINES); for ( size_t f = 0; f < model.faces.size(); f++ ) { for ( size_t v = 0; v < model.faces[f].verts.size(); v++ ) { size_t vIndex = model.faces[f].verts[v]; if ( vIndex < model.vertList.size() ) { OBJVert vert = model.vertList[vIndex]; size_t nIndex = model.faces[f].norms[v]; if ( nIndex < model.normList.size() ) { vert.glVertex(); vert += model.normList[nIndex]; vert.glVertex(); } } } } glEnd(); } bool Application::init ( void ) { camera = new SimpleDisplayCamera; display.addEventCallback(this); // load up the models loadModels(); camera->rotateGlob(-90,1,0,0); camera->moveLoc(0,0,-20); camera->moveLoc(0,1.5f,0); //setup light glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); float v[4] = {1}; v[0] = v[1] = v[2] = 0.125f; glLightfv (GL_LIGHT0, GL_AMBIENT,v); v[0] = v[1] = v[2] = 0.75f; glLightfv (GL_LIGHT0, GL_DIFFUSE,v); v[0] = v[1] = v[2] = 0; glLightfv (GL_LIGHT0, GL_SPECULAR,v); return true; } int Application::run ( void ) { if (!init()) return -1; while (display.update()) { display.clear(); camera->applyView(); drawGridAndBounds(); // draw normals glColor4f(1,0,0,1); drawObjectNormals(base); glColor4f(1,1,0,1); drawObjectNormals(barrel); glColor4f(0,1,1,1); drawObjectNormals(turret); glColor4f(0,0,1,1); drawObjectNormals(lTread); glColor4f(0,1,0,1); drawObjectNormals(lTread); glColor4f(1,1,1,1); glEnable(GL_TEXTURE_2D); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); float v[4] = {1}; v[0] = v[1] = v[2] = 20.f; glLightfv (GL_LIGHT0, GL_POSITION,v); display.bindImage(current); drawModels(); camera->removeView(); display.flip(); //display.yeld(0.5f); } display.kill(); return 0; } void Application::key ( int key, bool down, const ModiferKeys& mods ) { if (!camera || !down) return; switch(key) { case SD_KEY_ESCAPE: display.quit(); break; case SD_KEY_UP: if (mods.alt) camera->rotateLoc(2.5f,1,0,0); else if (mods.ctl) camera->moveLoc(0,0,0.25f); else camera->moveLoc(0,0.25f,0); break; case SD_KEY_DOWN: if (mods.alt) camera->rotateLoc(-2.5f,1,0,0); else if (mods.ctl) camera->moveLoc(0,0,-0.25f); else camera->moveLoc(0,-0.25f,0); break; case SD_KEY_LEFT: if (mods.alt) camera->rotateLoc(2.5f,0,1,0); else camera->moveLoc(-0.25f,0,0); break; case SD_KEY_RIGHT: if (mods.alt) camera->rotateLoc(-2.5f,0,1,0); else camera->moveLoc(0.25f,0,0); break; case SD_KEY_F1: current = red; break; case SD_KEY_F2: current = green; break; case SD_KEY_F3: current = blue; break; case SD_KEY_F4: current = purple; break; case SD_KEY_F5: current = black; break; } } void Application::mouseButton( int key, int x, int y, bool down ) { mousePos[0] = x; mousePos[1] = y; moveKeysDown[key-1] = down; } void Application::mouseMoved( int x, int y ) { int mouseDelta[2]; mouseDelta[0] = x - mousePos[0]; mouseDelta[1] = y - mousePos[1]; if ( moveKeysDown[0] ) { camera->moveLoc(-mouseDelta[0]*0.0125f,-mouseDelta[1]*0.0125f,0); } else if ( moveKeysDown[1] ) camera->moveLoc(0,0,mouseDelta[1]*0.025f); if ( moveKeysDown[2] ) { camera->rotateLoc(mouseDelta[1]*0.025f,1,0,0); camera->rotateGlob(mouseDelta[0]*0.025f,0,0,-1); } mousePos[0] = x; mousePos[1] = y; } #ifdef _WIN32 int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR lpCmdLine, int nShowCmd ) { #else int main ( int argc, char* argv[] ) { #endif Application app; return app.run(); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8
// tankview.cpp : Defines the entry point for the application. // #include "tankview.h" #include "Model.h" #include "config.h" #include "TextUtils.h" // for the stupid debug openGLcount model uses #ifdef DEBUG int __beginendCount; #endif class Application : public SimpleDisplayEventCallbacks { public: Application(); virtual void key ( int key, bool down, const ModiferKeys& mods ); virtual void mouseButton( int key, int x, int y, bool down ); virtual void mouseMoved( int x, int y ); int run ( void ); protected: bool init ( void ); void drawGridAndBounds ( void ); void loadModels ( void ); void drawModels ( void ); void drawObjectNormals ( OBJModel &model ); SimpleDisplay display; SimpleDisplayCamera *camera; OBJModel base,turret,barrel,lTread,rTread; unsigned int red,green,blue,purple,black,current; bool moveKeysDown[3]; int mousePos[2]; bool drawDebugNormals; }; const char* convertPath ( const char* path ) { static std::string temp; if (!path) return NULL; temp = path; #ifdef _WIN32 temp = TextUtils::replace_all(temp,std::string("/"),std::string("\\")); #endif return temp.c_str(); } Application::Application() : display(800,600,false,"tankview") { camera = NULL; drawDebugNormals = false; for (int i = 0; i<3; i++) moveKeysDown[i] = false; } void Application::drawGridAndBounds ( void ) { glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glBegin(GL_LINES); // axis markers glColor4f(1,0,0,0.25f); glVertex3f(0,0,0); glVertex3f(1,0,0); glColor4f(0,1,0,0.25f); glVertex3f(0,0,0); glVertex3f(0,1,0); glColor4f(0,0,1,0.25f); glVertex3f(0,0,0); glVertex3f(0,0,1); // grid glColor4f(1,1,1,0.125f); float grid = 10.0f; float increment = 0.25f; for( float i = -grid; i <= grid; i += increment ) { glVertex3f(i,grid,0); glVertex3f(i,-grid,0); glVertex3f(grid,i,0); glVertex3f(-grid,i,0); } // tank bbox glColor4f(0,1,1,0.25f); float width = 1.4f; float height = 2.05f; float front = 4.94f; float back = -3.10f; // front glVertex3f(front,-width,0); glVertex3f(front,width,0); glVertex3f(front,width,0); glVertex3f(front,width,height); glVertex3f(front,-width,height); glVertex3f(front,width,height); glVertex3f(front,-width,0); glVertex3f(front,-width,height); // back glVertex3f(back,-width,0); glVertex3f(back,width,0); glVertex3f(back,width,0); glVertex3f(back,width,height); glVertex3f(back,-width,height); glVertex3f(back,width,height); glVertex3f(back,-width,0); glVertex3f(back,-width,height); // sides glVertex3f(back,-width,0); glVertex3f(front,-width,0); glVertex3f(back,width,0); glVertex3f(front,width,0); glVertex3f(back,-width,height); glVertex3f(front,-width,height); glVertex3f(back,width,height); glVertex3f(front,width,height); glEnd(); glColor4f(1,1,1,1); } void Application::loadModels ( void ) { barrel.read(convertPath("./data/geometry/tank/std/barrel.obj")); base.read(convertPath("./data/geometry/tank/std/body.obj")); turret.read(convertPath("./data/geometry/tank/std/turret.obj")); lTread.read(convertPath("./data/geometry/tank/std/lcasing.obj")); rTread.read(convertPath("/.data/geometry/tank/std/rcasing.obj")); red = display.loadImage(convertPath("./data/skins/red/tank.png")); green = display.loadImage(convertPath("./data/skins/green/tank.png")); blue = display.loadImage(convertPath("./data/skins/blue/tank.png")); purple = display.loadImage(convertPath("./data/skins/purple/tank.png")); black = display.loadImage(convertPath("./data/skins/rogue/tank.png")); current = green; } void Application::drawModels ( void ) { base.draw(); lTread.draw(); rTread.draw(); turret.draw(); barrel.draw(); } void Application::drawObjectNormals ( OBJModel &model ) { glBegin(GL_LINES); for ( size_t f = 0; f < model.faces.size(); f++ ) { for ( size_t v = 0; v < model.faces[f].verts.size(); v++ ) { size_t vIndex = model.faces[f].verts[v]; if ( vIndex < model.vertList.size() ) { OBJVert vert = model.vertList[vIndex]; size_t nIndex = model.faces[f].norms[v]; if ( nIndex < model.normList.size() ) { vert.glVertex(); vert += model.normList[nIndex]; vert.glVertex(); } } } } glEnd(); } bool Application::init ( void ) { camera = new SimpleDisplayCamera; display.addEventCallback(this); // load up the models loadModels(); camera->rotateGlob(-90,1,0,0); camera->moveLoc(0,0,-20); camera->moveLoc(0,1.5f,0); //setup light glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); float v[4] = {1}; v[0] = v[1] = v[2] = 0.125f; glLightfv (GL_LIGHT0, GL_AMBIENT,v); v[0] = v[1] = v[2] = 0.75f; glLightfv (GL_LIGHT0, GL_DIFFUSE,v); v[0] = v[1] = v[2] = 0; glLightfv (GL_LIGHT0, GL_SPECULAR,v); return true; } int Application::run ( void ) { if (!init()) return -1; while (display.update()) { display.clear(); camera->applyView(); drawGridAndBounds(); // draw normals if (drawDebugNormals) { glColor4f(1,0,0,1); drawObjectNormals(base); glColor4f(1,1,0,1); drawObjectNormals(barrel); glColor4f(0,1,1,1); drawObjectNormals(turret); glColor4f(0,0,1,1); drawObjectNormals(lTread); glColor4f(0,1,0,1); drawObjectNormals(lTread); } glColor4f(1,1,1,1); glEnable(GL_TEXTURE_2D); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); float v[4] = {1}; v[0] = v[1] = v[2] = 20.f; glLightfv (GL_LIGHT0, GL_POSITION,v); display.bindImage(current); drawModels(); camera->removeView(); display.flip(); //display.yeld(0.5f); } display.kill(); return 0; } void Application::key ( int key, bool down, const ModiferKeys& mods ) { if (!camera || !down) return; switch(key) { case SD_KEY_ESCAPE: display.quit(); break; case SD_KEY_UP: if (mods.alt) camera->rotateLoc(2.5f,1,0,0); else if (mods.ctl) camera->moveLoc(0,0,0.25f); else camera->moveLoc(0,0.25f,0); break; case SD_KEY_DOWN: if (mods.alt) camera->rotateLoc(-2.5f,1,0,0); else if (mods.ctl) camera->moveLoc(0,0,-0.25f); else camera->moveLoc(0,-0.25f,0); break; case SD_KEY_LEFT: if (mods.alt) camera->rotateLoc(2.5f,0,1,0); else camera->moveLoc(-0.25f,0,0); break; case SD_KEY_RIGHT: if (mods.alt) camera->rotateLoc(-2.5f,0,1,0); else camera->moveLoc(0.25f,0,0); break; case SD_KEY_F1: current = red; break; case SD_KEY_F2: current = green; break; case SD_KEY_F3: current = blue; break; case SD_KEY_F4: current = purple; break; case SD_KEY_F5: current = black; break; } } void Application::mouseButton( int key, int x, int y, bool down ) { mousePos[0] = x; mousePos[1] = y; moveKeysDown[key-1] = down; } void Application::mouseMoved( int x, int y ) { int mouseDelta[2]; mouseDelta[0] = x - mousePos[0]; mouseDelta[1] = y - mousePos[1]; if ( moveKeysDown[0] ) { camera->moveLoc(-mouseDelta[0]*0.0125f,-mouseDelta[1]*0.0125f,0); } else if ( moveKeysDown[1] ) camera->moveLoc(0,0,mouseDelta[1]*0.025f); if ( moveKeysDown[2] ) { camera->rotateLoc(mouseDelta[1]*0.025f,1,0,0); camera->rotateGlob(mouseDelta[0]*0.025f,0,0,-1); } mousePos[0] = x; mousePos[1] = y; } #ifdef _WIN32 int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR lpCmdLine, int nShowCmd ) { #else int main ( int argc, char* argv[] ) { #endif Application app; return app.run(); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8
make normal drawing optional and draw the models properly now
make normal drawing optional and draw the models properly now
C++
lgpl-2.1
kongr45gpen/bzflag-import-1,kongr45gpen/bzflag-import-1,kongr45gpen/bzflag-import-1,kongr45gpen/bzflag-import-1,kongr45gpen/bzflag-import-1,kongr45gpen/bzflag-import-1
1117d68077fa35a325a3466741c8409bd5545d11
tests/pool.cc
tests/pool.cc
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Libmemcached Client and Server * * Copyright (C) 2011 Data Differential, http://datadifferential.com/ * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <config.h> #include <libtest/test.hpp> using namespace libtest; #include <vector> #include <iostream> #include <string> #include <cerrno> #include <semaphore.h> #include <libmemcached/memcached.h> #include <libmemcached/util.h> #include <tests/pool.h> test_return_t memcached_pool_test(memcached_st *) { memcached_return_t rc; const char *config_string= "--SERVER=host10.example.com --SERVER=host11.example.com --SERVER=host10.example.com --POOL-MIN=10 --POOL-MAX=32"; char buffer[2048]; rc= libmemcached_check_configuration(config_string, sizeof(config_string) -1, buffer, sizeof(buffer)); test_true_got(rc != MEMCACHED_SUCCESS, buffer); memcached_pool_st* pool= memcached_pool(config_string, strlen(config_string)); test_true_got(pool, strerror(errno)); memcached_st *memc= memcached_pool_pop(pool, false, &rc); test_true(rc == MEMCACHED_SUCCESS); test_true(memc); /* Release the memc_ptr that was pulled from the pool */ memcached_pool_push(pool, memc); /* Destroy the pool. */ memcached_pool_destroy(pool); return TEST_SUCCESS; } #define POOL_SIZE 10 test_return_t connection_pool_test(memcached_st *memc) { memcached_pool_st* pool= memcached_pool_create(memc, 5, POOL_SIZE); test_true(pool); memcached_st *mmc[POOL_SIZE]; // Fill up our array that we will store the memc that are in the pool for (size_t x= 0; x < POOL_SIZE; ++x) { memcached_return_t rc; mmc[x]= memcached_pool_fetch(pool, NULL, &rc); test_compare(MEMCACHED_SUCCESS, rc); test_true(mmc[x]); } // All memc should be gone { memcached_return_t rc; test_null(memcached_pool_fetch(pool, NULL, &rc)); test_compare(MEMCACHED_NOTFOUND, rc); } // Release them.. for (size_t x= 0; x < POOL_SIZE; ++x) { if (mmc[x]) { test_compare(MEMCACHED_SUCCESS, memcached_pool_release(pool, mmc[x])); } } test_true(memcached_pool_destroy(pool) == memc); return TEST_SUCCESS; } test_return_t connection_pool2_test(memcached_st *memc) { memcached_pool_st* pool= memcached_pool_create(memc, 5, POOL_SIZE); test_true(pool); memcached_st *mmc[POOL_SIZE]; // Fill up our array that we will store the memc that are in the pool for (size_t x= 0; x < POOL_SIZE; ++x) { memcached_return_t rc; mmc[x]= memcached_pool_fetch(pool, NULL, &rc); test_compare(MEMCACHED_SUCCESS, rc); test_true(mmc[x]); } // All memc should be gone { memcached_return_t rc; test_null(memcached_pool_fetch(pool, NULL, &rc)); test_compare(MEMCACHED_NOTFOUND, rc); } // verify that I can do ops with all connections test_compare(MEMCACHED_SUCCESS, memcached_set(mmc[0], test_literal_param("key"), "0", 1, 0, 0)); for (uint64_t x= 0; x < POOL_SIZE; ++x) { uint64_t number_value; test_compare(MEMCACHED_SUCCESS, memcached_increment(mmc[x], test_literal_param("key"), 1, &number_value)); test_compare(number_value, (x+1)); } // Release them.. for (size_t x= 0; x < POOL_SIZE; ++x) { test_compare(MEMCACHED_SUCCESS, memcached_pool_release(pool, mmc[x])); } /* verify that I can set behaviors on the pool when I don't have all * of the connections in the pool. It should however be enabled * when I push the item into the pool */ mmc[0]= memcached_pool_fetch(pool, NULL, NULL); test_true(mmc[0]); test_compare(MEMCACHED_SUCCESS, memcached_pool_behavior_set(pool, MEMCACHED_BEHAVIOR_IO_MSG_WATERMARK, 9999)); { memcached_return_t rc; mmc[1]= memcached_pool_fetch(pool, NULL, &rc); test_true(mmc[1]); test_compare(MEMCACHED_SUCCESS, rc); } test_compare(UINT64_C(9999), memcached_behavior_get(mmc[1], MEMCACHED_BEHAVIOR_IO_MSG_WATERMARK)); test_compare(MEMCACHED_SUCCESS, memcached_pool_release(pool, mmc[1])); test_compare(MEMCACHED_SUCCESS, memcached_pool_release(pool, mmc[0])); { memcached_return_t rc; mmc[0]= memcached_pool_fetch(pool, NULL, &rc); test_true(mmc[0]); test_compare(MEMCACHED_SUCCESS, rc); } test_compare(UINT64_C(9999), memcached_behavior_get(mmc[0], MEMCACHED_BEHAVIOR_IO_MSG_WATERMARK)); test_compare(MEMCACHED_SUCCESS, memcached_pool_release(pool, mmc[0])); test_true(memcached_pool_destroy(pool) == memc); return TEST_SUCCESS; } struct test_pool_context_st { volatile memcached_return_t rc; memcached_pool_st* pool; memcached_st* mmc; sem_t _lock; test_pool_context_st(memcached_pool_st *pool_arg, memcached_st *memc_arg): rc(MEMCACHED_FAILURE), pool(pool_arg), mmc(memc_arg) { sem_init(&_lock, 0, 0); } void wait() { sem_wait(&_lock); } void release() { sem_post(&_lock); } ~test_pool_context_st() { sem_destroy(&_lock); } }; static void* connection_release(void *arg) { test_pool_context_st *resource= static_cast<test_pool_context_st *>(arg); assert(resource); if (resource == NULL) { abort(); } // Release all of the memc we are holding resource->rc= memcached_pool_release(resource->pool, resource->mmc); resource->release(); pthread_exit(arg); } test_return_t connection_pool3_test(memcached_st *memc) { #ifdef __APPLE__ return TEST_SKIPPED; #endif memcached_pool_st* pool= memcached_pool_create(memc, 1, 1); test_true(pool); memcached_st *pool_memc; { memcached_return_t rc; pool_memc= memcached_pool_fetch(pool, NULL, &rc); test_compare(MEMCACHED_SUCCESS, rc); test_true(pool_memc); } /* @note This comment was written to describe what was believed to be the original authors intent. This portion of the test creates a thread that will wait until told to free a memcached_st that will be grabbed by the main thread. It is believed that this tests whether or not we are handling ownership correctly. */ pthread_t tid; test_pool_context_st item(pool, pool_memc); test_zero(pthread_create(&tid, NULL, connection_release, &item)); item.wait(); memcached_return_t rc; memcached_st *pop_memc; // We do a hard loop, and try N times int counter= 5; do { struct timespec relative_time= { 0, 0 }; pop_memc= memcached_pool_fetch(pool, &relative_time, &rc); if (memcached_success(rc)) { break; } if (memcached_failed(rc)) { test_null(pop_memc); test_true(rc != MEMCACHED_TIMEOUT); // As long as relative_time is zero, MEMCACHED_TIMEOUT is invalid } } while (--counter); if (memcached_failed(rc)) // Cleanup thread since we will exit once we test. { pthread_join(tid, NULL); test_compare(MEMCACHED_SUCCESS, rc); } { int pthread_ret= pthread_join(tid, NULL); test_true(pthread_ret == 0 or pthread_ret == ESRCH); } test_compare(MEMCACHED_SUCCESS, rc); test_true(pool_memc == pop_memc); test_true(memcached_pool_destroy(pool) == memc); return TEST_SUCCESS; }
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Libmemcached Client and Server * * Copyright (C) 2011 Data Differential, http://datadifferential.com/ * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <config.h> #include <libtest/test.hpp> using namespace libtest; #include <vector> #include <iostream> #include <string> #include <cerrno> #include <semaphore.h> #include <libmemcached/memcached.h> #include <libmemcached/util.h> #include <tests/pool.h> #ifndef __INTEL_COMPILER #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif test_return_t memcached_pool_test(memcached_st *) { memcached_return_t rc; const char *config_string= "--SERVER=host10.example.com --SERVER=host11.example.com --SERVER=host10.example.com --POOL-MIN=10 --POOL-MAX=32"; char buffer[2048]; rc= libmemcached_check_configuration(config_string, sizeof(config_string) -1, buffer, sizeof(buffer)); test_true_got(rc != MEMCACHED_SUCCESS, buffer); memcached_pool_st* pool= memcached_pool(config_string, strlen(config_string)); test_true_got(pool, strerror(errno)); memcached_st *memc= memcached_pool_pop(pool, false, &rc); test_true(rc == MEMCACHED_SUCCESS); test_true(memc); /* Release the memc_ptr that was pulled from the pool */ memcached_pool_push(pool, memc); /* Destroy the pool. */ memcached_pool_destroy(pool); return TEST_SUCCESS; } #define POOL_SIZE 10 test_return_t connection_pool_test(memcached_st *memc) { memcached_pool_st* pool= memcached_pool_create(memc, 5, POOL_SIZE); test_true(pool); memcached_st *mmc[POOL_SIZE]; // Fill up our array that we will store the memc that are in the pool for (size_t x= 0; x < POOL_SIZE; ++x) { memcached_return_t rc; mmc[x]= memcached_pool_fetch(pool, NULL, &rc); test_compare(MEMCACHED_SUCCESS, rc); test_true(mmc[x]); } // All memc should be gone { memcached_return_t rc; test_null(memcached_pool_fetch(pool, NULL, &rc)); test_compare(MEMCACHED_NOTFOUND, rc); } // Release them.. for (size_t x= 0; x < POOL_SIZE; ++x) { if (mmc[x]) { test_compare(MEMCACHED_SUCCESS, memcached_pool_release(pool, mmc[x])); } } test_true(memcached_pool_destroy(pool) == memc); return TEST_SUCCESS; } test_return_t connection_pool2_test(memcached_st *memc) { memcached_pool_st* pool= memcached_pool_create(memc, 5, POOL_SIZE); test_true(pool); memcached_st *mmc[POOL_SIZE]; // Fill up our array that we will store the memc that are in the pool for (size_t x= 0; x < POOL_SIZE; ++x) { memcached_return_t rc; mmc[x]= memcached_pool_fetch(pool, NULL, &rc); test_compare(MEMCACHED_SUCCESS, rc); test_true(mmc[x]); } // All memc should be gone { memcached_return_t rc; test_null(memcached_pool_fetch(pool, NULL, &rc)); test_compare(MEMCACHED_NOTFOUND, rc); } // verify that I can do ops with all connections test_compare(MEMCACHED_SUCCESS, memcached_set(mmc[0], test_literal_param("key"), "0", 1, 0, 0)); for (uint64_t x= 0; x < POOL_SIZE; ++x) { uint64_t number_value; test_compare(MEMCACHED_SUCCESS, memcached_increment(mmc[x], test_literal_param("key"), 1, &number_value)); test_compare(number_value, (x+1)); } // Release them.. for (size_t x= 0; x < POOL_SIZE; ++x) { test_compare(MEMCACHED_SUCCESS, memcached_pool_release(pool, mmc[x])); } /* verify that I can set behaviors on the pool when I don't have all * of the connections in the pool. It should however be enabled * when I push the item into the pool */ mmc[0]= memcached_pool_fetch(pool, NULL, NULL); test_true(mmc[0]); test_compare(MEMCACHED_SUCCESS, memcached_pool_behavior_set(pool, MEMCACHED_BEHAVIOR_IO_MSG_WATERMARK, 9999)); { memcached_return_t rc; mmc[1]= memcached_pool_fetch(pool, NULL, &rc); test_true(mmc[1]); test_compare(MEMCACHED_SUCCESS, rc); } test_compare(UINT64_C(9999), memcached_behavior_get(mmc[1], MEMCACHED_BEHAVIOR_IO_MSG_WATERMARK)); test_compare(MEMCACHED_SUCCESS, memcached_pool_release(pool, mmc[1])); test_compare(MEMCACHED_SUCCESS, memcached_pool_release(pool, mmc[0])); { memcached_return_t rc; mmc[0]= memcached_pool_fetch(pool, NULL, &rc); test_true(mmc[0]); test_compare(MEMCACHED_SUCCESS, rc); } test_compare(UINT64_C(9999), memcached_behavior_get(mmc[0], MEMCACHED_BEHAVIOR_IO_MSG_WATERMARK)); test_compare(MEMCACHED_SUCCESS, memcached_pool_release(pool, mmc[0])); test_true(memcached_pool_destroy(pool) == memc); return TEST_SUCCESS; } struct test_pool_context_st { volatile memcached_return_t rc; memcached_pool_st* pool; memcached_st* mmc; sem_t _lock; test_pool_context_st(memcached_pool_st *pool_arg, memcached_st *memc_arg): rc(MEMCACHED_FAILURE), pool(pool_arg), mmc(memc_arg) { sem_init(&_lock, 0, 0); } void wait() { sem_wait(&_lock); } void release() { sem_post(&_lock); } ~test_pool_context_st() { sem_destroy(&_lock); } }; static void* connection_release(void *arg) { test_pool_context_st *resource= static_cast<test_pool_context_st *>(arg); assert(resource); if (resource == NULL) { abort(); } // Release all of the memc we are holding resource->rc= memcached_pool_release(resource->pool, resource->mmc); resource->release(); pthread_exit(arg); } test_return_t connection_pool3_test(memcached_st *memc) { #ifdef __APPLE__ return TEST_SKIPPED; #endif memcached_pool_st* pool= memcached_pool_create(memc, 1, 1); test_true(pool); memcached_st *pool_memc; { memcached_return_t rc; pool_memc= memcached_pool_fetch(pool, NULL, &rc); test_compare(MEMCACHED_SUCCESS, rc); test_true(pool_memc); } /* @note This comment was written to describe what was believed to be the original authors intent. This portion of the test creates a thread that will wait until told to free a memcached_st that will be grabbed by the main thread. It is believed that this tests whether or not we are handling ownership correctly. */ pthread_t tid; test_pool_context_st item(pool, pool_memc); test_zero(pthread_create(&tid, NULL, connection_release, &item)); item.wait(); memcached_return_t rc; memcached_st *pop_memc; // We do a hard loop, and try N times int counter= 5; do { struct timespec relative_time= { 0, 0 }; pop_memc= memcached_pool_fetch(pool, &relative_time, &rc); if (memcached_success(rc)) { break; } if (memcached_failed(rc)) { test_null(pop_memc); test_true(rc != MEMCACHED_TIMEOUT); // As long as relative_time is zero, MEMCACHED_TIMEOUT is invalid } } while (--counter); if (memcached_failed(rc)) // Cleanup thread since we will exit once we test. { pthread_join(tid, NULL); test_compare(MEMCACHED_SUCCESS, rc); } { int pthread_ret= pthread_join(tid, NULL); test_true(pthread_ret == 0 or pthread_ret == ESRCH); } test_compare(MEMCACHED_SUCCESS, rc); test_true(pool_memc == pop_memc); test_true(memcached_pool_destroy(pool) == memc); return TEST_SUCCESS; }
Fix Ubuntu compile find.
Fix Ubuntu compile find.
C++
bsd-3-clause
bigbes/libmemcached,Distrotech/libmemcached,Distrotech/libmemcached,bigbes/libmemcached,bigbes/libmemcached,Distrotech/libmemcached
aac679bfee34bb89b19acf25b4e6555632efa6d1
plugins/sound/renderer/ds3d/sndrdr.cpp
plugins/sound/renderer/ds3d/sndrdr.cpp
/* Copyright (C) 1998, 1999 by Nathaniel 'NooTe' Saint Martin Copyright (C) 1998, 1999 by Jorrit Tyberghein Written by Nathaniel 'NooTe' Saint Martin This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdio.h> #include <windows.h> #include <initguid.h> #include "dsound.h" #include "sysdef.h" #include "cscom/com.h" #include "cssndrdr/ds3d/sndrdr.h" #include "cssndrdr/ds3d/sndlstn.h" #include "cssndrdr/ds3d/sndsrc.h" #include "isystem.h" #include "isndlstn.h" #include "isndsrc.h" IMPLEMENT_UNKNOWN_NODELETE (csSoundRenderDS3D) BEGIN_INTERFACE_TABLE(csSoundRenderDS3D) IMPLEMENTS_INTERFACE(ISoundRender) END_INTERFACE_TABLE() csSoundRenderDS3D::csSoundRenderDS3D(ISystem* piSystem) : m_pListener(NULL) { m_p3DAudioRenderer = NULL; m_piSystem = piSystem; m_pListener = new csSoundListenerDS3D (); } csSoundRenderDS3D::~csSoundRenderDS3D() { if(m_pListener) delete m_pListener; } STDMETHODIMP csSoundRenderDS3D::GetListener(ISoundListener** ppv ) { if (!m_pListener) { *ppv = NULL; return E_OUTOFMEMORY; } return m_pListener->QueryInterface (IID_ISoundListener, (void**)ppv); } STDMETHODIMP csSoundRenderDS3D::CreateSource(ISoundSource** ppv, csSoundBuffer *snd) { csSoundSourceDS3D* pNew = new csSoundSourceDS3D (); if (!pNew) { *ppv = 0; return E_OUTOFMEMORY; } pNew->CreateSource(this, snd); return pNew->QueryInterface (IID_ISoundSource, (void**)ppv); } STDMETHODIMP csSoundRenderDS3D::Open() { HRESULT hr; SysPrintf (MSG_INITIALIZATION, "\nSoundRender DirectSound3D selected\n"); if (FAILED(hr = DirectSoundCreate(NULL, &m_p3DAudioRenderer, NULL))) { SysPrintf(MSG_FATAL_ERROR, "Error : Cannot Initialize DirectSound3D !"); Close(); return(hr); } DWORD dwLevel = DSSCL_NORMAL; if (FAILED(hr = m_p3DAudioRenderer->SetCooperativeLevel(GetForegroundWindow(), dwLevel))) { SysPrintf(MSG_FATAL_ERROR, "Error : Cannot Set Cooperative Level!"); Close(); return(hr); } m_pListener->CreateListener(this); return S_OK; } STDMETHODIMP csSoundRenderDS3D::Close() { HRESULT hr; if(m_pListener) { m_pListener->DestroyListener(); m_pListener->Release(); } if (m_p3DAudioRenderer) { if ((hr = m_p3DAudioRenderer->Release()) < DS_OK) return(hr); m_p3DAudioRenderer = NULL; } return S_OK; } STDMETHODIMP csSoundRenderDS3D::Update() { return S_OK; } STDMETHODIMP csSoundRenderDS3D::SetVolume(float vol) { long dsvol; if (m_pListener) { m_pListener->m_pDS3DPrimaryBuffer->SetVolume(dsvol); } return S_OK; } STDMETHODIMP csSoundRenderDS3D::GetVolume(float *vol) { long dsvol; if (m_pListener) { m_pListener->m_pDS3DPrimaryBuffer->GetVolume(&dsvol); } return S_OK; } STDMETHODIMP csSoundRenderDS3D::PlayEphemeral(csSoundBuffer *snd) { return S_OK; } void csSoundRenderDS3D::SysPrintf(int mode, char* szMsg, ...) { char buf[1024]; va_list arg; va_start (arg, szMsg); vsprintf (buf, szMsg, arg); va_end (arg); m_piSystem->Print(mode, buf); }
/* Copyright (C) 1998, 1999 by Nathaniel 'NooTe' Saint Martin Copyright (C) 1998, 1999 by Jorrit Tyberghein Written by Nathaniel 'NooTe' Saint Martin This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdio.h> #include <windows.h> #include <initguid.h> #include "dsound.h" #include "sysdef.h" #include "cscom/com.h" #include "cssndrdr/ds3d/sndrdr.h" #include "cssndrdr/ds3d/sndlstn.h" #include "cssndrdr/ds3d/sndsrc.h" #include "isystem.h" #include "isndlstn.h" #include "isndsrc.h" IMPLEMENT_UNKNOWN_NODELETE (csSoundRenderDS3D) BEGIN_INTERFACE_TABLE(csSoundRenderDS3D) IMPLEMENTS_INTERFACE(ISoundRender) END_INTERFACE_TABLE() csSoundRenderDS3D::csSoundRenderDS3D(ISystem* piSystem) : m_pListener(NULL) { m_p3DAudioRenderer = NULL; m_piSystem = piSystem; m_pListener = new csSoundListenerDS3D (); } csSoundRenderDS3D::~csSoundRenderDS3D() { if(m_pListener) delete m_pListener; } STDMETHODIMP csSoundRenderDS3D::GetListener(ISoundListener** ppv ) { if (!m_pListener) { *ppv = NULL; return E_OUTOFMEMORY; } return m_pListener->QueryInterface (IID_ISoundListener, (void**)ppv); } STDMETHODIMP csSoundRenderDS3D::CreateSource(ISoundSource** ppv, csSoundBuffer *snd) { csSoundSourceDS3D* pNew = new csSoundSourceDS3D (); if (!pNew) { *ppv = 0; return E_OUTOFMEMORY; } pNew->CreateSource(this, snd); return pNew->QueryInterface (IID_ISoundSource, (void**)ppv); } STDMETHODIMP csSoundRenderDS3D::Open() { HRESULT hr; SysPrintf (MSG_INITIALIZATION, "\nSoundRender DirectSound3D selected\n"); if (FAILED(hr = DirectSoundCreate(NULL, &m_p3DAudioRenderer, NULL))) { SysPrintf(MSG_FATAL_ERROR, "Error : Cannot Initialize DirectSound3D !"); Close(); return(hr); } DWORD dwLevel = DSSCL_NORMAL; if (FAILED(hr = m_p3DAudioRenderer->SetCooperativeLevel(GetForegroundWindow(), dwLevel))) { SysPrintf(MSG_FATAL_ERROR, "Error : Cannot Set Cooperative Level!"); Close(); return(hr); } m_pListener->CreateListener(this); return S_OK; } STDMETHODIMP csSoundRenderDS3D::Close() { HRESULT hr; if(m_pListener) { m_pListener->DestroyListener(); m_pListener->Release(); } if (m_p3DAudioRenderer) { if ((hr = m_p3DAudioRenderer->Release()) < DS_OK) return(hr); m_p3DAudioRenderer = NULL; } return S_OK; } STDMETHODIMP csSoundRenderDS3D::Update() { return S_OK; } STDMETHODIMP csSoundRenderDS3D::SetVolume(float vol) { long dsvol = DSBVOLUME_MIN + (DSBVOLUME_MAX-DSBVOLUME_MIN)*vol; if (m_pListener) { m_pListener->m_pDS3DPrimaryBuffer->SetVolume(dsvol); } return S_OK; } STDMETHODIMP csSoundRenderDS3D::GetVolume(float *vol) { long dsvol; if (m_pListener) { m_pListener->m_pDS3DPrimaryBuffer->GetVolume(&dsvol); } *vol = (float)(dsvol-DSBVOLUME_MIN)/(float)(DSBVOLUME_MAX-DSBVOLUME_MIN); return S_OK; } STDMETHODIMP csSoundRenderDS3D::PlayEphemeral(csSoundBuffer *snd) { return S_OK; } void csSoundRenderDS3D::SysPrintf(int mode, char* szMsg, ...) { char buf[1024]; va_list arg; va_start (arg, szMsg); vsprintf (buf, szMsg, arg); va_end (arg); m_piSystem->Print(mode, buf); }
Support for proper volume setting.
Support for proper volume setting. git-svn-id: 28d9401aa571d5108e51b194aae6f24ca5964c06@598 8cc4aa7f-3514-0410-904f-f2cc9021211c
C++
lgpl-2.1
crystalspace/CS,crystalspace/CS,crystalspace/CS,crystalspace/CS,crystalspace/CS,crystalspace/CS,crystalspace/CS,crystalspace/CS
e757785d0741a4ec3957fc65720d1a7c331d30cb
rf-server/main.cc
rf-server/main.cc
/* * Copyright 2011 Fundação CPqD * * 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 <syslog.h> #include <sys/types.h> #include <sys/socket.h> #include <stdlib.h> #include <cstring> #include <unistd.h> #include <fcntl.h> #include <pthread.h> #include <signal.h> #include "ClientConnection.hh" #include "rfserver.hh" #include "ControllerConnection.hh" #include "TCPSocket.hh" #include "cpqd.hh" #include "RFCtlMessageProcessor.hh" #include "RawMessage.hh" const uint32_t TCP_PORT = 5678; const uint32_t MAX_CONNECTIONS = 10; #define SYSLOGFACILITY LOG_LOCAL7 #define DEFAULTCTLIP "127.0.0.1" #define DEFAULTCTLPORT 7890 using std::memset; RouteFlowServer rfSrv(TCP_PORT, VIRT_N_FORWARD_PLANE); int main(int argc, char **argv) { timeval t; int sockFd, connCount; socklen_t cliLength; struct sockaddr_in servAddr; int8_t ret = SUCCESS; openlog("rf-server", LOG_PID, SYSLOGFACILITY); ControllerConnection qfController; ttag_Address RemoteAdd; uint32_t TCPPort; TCPSocket * tcpSocket = NULL; RFCtlMessageProcessor * rfmp = NULL; RawMessage * msg = NULL; rfmp = new RFCtlMessageProcessor(); msg = new RawMessage(); string IP = DEFAULTCTLIP; TCPPort = DEFAULTCTLPORT; /* * Initializing the TCP Socket. */ tcpSocket = new TCPSocket(); /* * Setting the FD of the TCP Socket. */ tcpSocket->open(); ret = strToAddress(IP, RemoteAdd); /* * Connecting to the controller via IP = RemoteAdd, port = port. */ uint32_t i = 0; do { ret = tcpSocket->connect(RemoteAdd, TCPPort); i++; syslog(LOG_INFO, "We are in attempt number: %d ", i); if (ret != SUCCESS) { sleep(2); } } while ((ret != SUCCESS)); qfController.setCommunicator(tcpSocket); qfController.setMessageProcessor(rfmp); qfController.setMessage((IPCMessage *) msg); qfController.arg((void *) &rfSrv); /* * Starting Controller Connection Thread */ qfController.start(); rfSrv.qfCtlConnection = &qfController; ClientConnection qfClient; qfClient.arg((void *) &rfSrv); (void) (argc); (void) (argv); t.tv_sec = 0; t.tv_usec = 1000; do { sockFd = socket(AF_INET, SOCK_STREAM, 0); if (sockFd < 0) { syslog(LOG_ERR, "Could not open a new socket"); // return -1; } sleep(2); } while (sockFd < 0); qfClient.start(); /* TODO * Get TCP port from main arguments. */ uint16_t tcpport = TCP_PORT; /*VM Connection.*/ std::memset((char *) &servAddr, 0, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = INADDR_ANY; servAddr.sin_port = htons(tcpport); int bindsocketret = 0; while (bind(sockFd, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0) { syslog(LOG_INFO, "Could not bind server socket"); sleep(2); } syslog(LOG_INFO, "Finally bound to VM sockets"); listen(sockFd, MAX_CONNECTIONS); /* sockFd should be in "blocking" mode to avoid wasting CPU time unnecessarily */ /* int flags = fcntl(sockFd, F_GETFL); flags &= ~O_NONBLOCK; fcntl(sockFd, F_SETFL, flags | O_NONBLOCK); */ cliLength = sizeof(struct sockaddr_in); connCount = 0; while (1) { struct sockaddr_in vmAddr; int vmSockFd; vmSockFd = accept(sockFd, (struct sockaddr *) &vmAddr, &cliLength); if (vmSockFd > 0) { char buffer[ETH_PKT_SIZE]; std::memset(buffer, 0, ETH_PKT_SIZE); if (rfSrv.recv_msg(vmSockFd, (RFMessage *) buffer, ETH_PKT_SIZE) <= 0) { close(vmSockFd); continue; } RFVMMsg * regMsg = (RFVMMsg *) buffer; RFVMMsg msg; msg.setDstIP(vmAddr.sin_addr.s_addr); msg.setSrcIP("10.4.1.26"); while (rfSrv.lockvmList() < 0) ; std::list<RFVirtualMachine>::iterator iter; bool alreadyregVmId = 0; for (iter = rfSrv.m_vmList.begin(); iter != rfSrv.m_vmList.end(); iter++) { if (iter->getVmId() == regMsg->getVMId()) { alreadyregVmId = 1; } } rfSrv.unlockvmList(); if (RFP_CMD_REGISTER == regMsg->getType() && !alreadyregVmId) { uint64_t vmId = regMsg->getVMId(); msg.setVMId(vmId); msg.setType(RFP_CMD_ACCPET); RFVirtualMachine newVM; newVM.setVmId(vmId); newVM.setSockFd(vmSockFd); newVM.setIpAddr(vmAddr.sin_addr.s_addr); newVM.setTcpPort(vmAddr.sin_port); newVM.setMode(RFP_VM_MODE_STANDBY); newVM.setVMAddr(&vmAddr); if (rfSrv.send_msg(vmSockFd, &msg) <= 0) { syslog(LOG_ERR, "Could not write to VM socket"); } bool found = 0; uint8_t ports; /* TODO The code below appear on the method datapath_join_event * Change it in further versions to let main.cc more clean. */ if (!rfSrv.m_dpIdleList.empty()) { //If there is an Idle Datapath. Dp2Vm_t vm2dptmp; vm2dptmp.dpId = rfSrv.Vm2DpMap(vmId); syslog(LOG_DEBUG, "Dp = %lld, VM = %lld", vm2dptmp.dpId, vmId); if (vm2dptmp.dpId != 0) { //The VM has a Datapath assigned to it? syslog(LOG_DEBUG, "Has a Datapath assigned."); std::list<Datapath_t>::iterator iter; for (iter = rfSrv.m_dpIdleList.begin(); iter != rfSrv.m_dpIdleList.end(); iter++) { /* The idle datapath belongs to some VM?*/ if (vm2dptmp.dpId == iter->dpId) { newVM.setMode(RFP_VM_MODE_RUNNING); //Set VM mode to running (local definition) Datapath_t newDP; newDP.dpId = iter->dpId; newDP.nports = iter->nports; newVM.setDpId(newDP); ports = iter->nports; rfSrv.m_dpIdleList.erase(iter); found = 1; break; } } } else { std::list<Datapath_t>::iterator iter; for (iter = rfSrv.m_dpIdleList.begin(); iter != rfSrv.m_dpIdleList.end(); iter++) { if (rfSrv.Dp2VmMap(iter->dpId == 0)) { //Is there an Idle Datapath without any VM assigned to it? newVM.setMode(RFP_VM_MODE_RUNNING); //Set VM mode to running (local definition) Datapath_t newDP; newDP.dpId = iter->dpId; newDP.nports = iter->nports; newVM.setDpId(newDP); ports = iter->nports; rfSrv.m_dpIdleList.erase(iter); vm2dptmp.vmId = newVM.getVmId(); vm2dptmp.dpId = newVM.getDpId().dpId; rfSrv.m_Dp2VmList.push_front(vm2dptmp); syslog( LOG_DEBUG, "Dp = %lld, VM = %lld added to the List", vm2dptmp.dpId, vm2dptmp.vmId); found = 1; break; } } } if (found) { /* Install RIPv2 default flow. */ rfSrv.send_flow_msg(newVM.getDpId().dpId, RFO_RIPV2); /* Install OSPF default flow. */ rfSrv.send_flow_msg(newVM.getDpId().dpId, RFO_OSPF); /* Install ARP default flow. */ rfSrv.send_flow_msg(newVM.getDpId().dpId, RFO_ARP); /* Configuration message to the slave. */ RFVMMsg logmsg; logmsg.setDstIP(newVM.getIpAddr()); logmsg.setSrcIP("10.4.1.26"); logmsg.setVMId(newVM.getVmId()); logmsg.setType(RFP_CMD_VM_CONFIG); logmsg.setDpId(newVM.getDpId().dpId); logmsg.setMode(RFP_VM_MODE_RUNNING); logmsg.setWildcard(RFP_VM_MODE | RFP_VM_DPID | RFP_VM_NPORTS); logmsg.setNPorts(ports); if (rfSrv.send_msg(newVM.getSockFd(), &logmsg) <= 0) { syslog(LOG_ERR, "Could not write to VM socket"); } } else { syslog( LOG_INFO, "The Datapath assigned to VM: %lld isn't connected", newVM.getVmId()); } } while (rfSrv.lockvmList() < 0); rfSrv.m_vmList.push_back(newVM); syslog(LOG_INFO, "A new VM was registered: VmId=%lld", vmId); rfSrv.unlockvmList(); }/* VmId already registered or msg type unknown. */ else { msg.setType(RFP_CMD_REJECT); syslog(LOG_INFO, "Connection refused: VmId already registered."); if (rfSrv.send_msg(vmSockFd, &msg) <= 0) { syslog(LOG_ERR, "Could not write to VM socket"); } close(vmSockFd); } } } close(sockFd); return 0; }
/* * Copyright 2011 Fundação CPqD * * 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 <syslog.h> #include <sys/types.h> #include <sys/socket.h> #include <stdlib.h> #include <cstring> #include <unistd.h> #include <fcntl.h> #include <pthread.h> #include <signal.h> #include "ClientConnection.hh" #include "rfserver.hh" #include "ControllerConnection.hh" #include "TCPSocket.hh" #include "cpqd.hh" #include "RFCtlMessageProcessor.hh" #include "RawMessage.hh" const uint32_t TCP_PORT = 5678; const uint32_t MAX_CONNECTIONS = 10; #define SYSLOGFACILITY LOG_LOCAL7 #define DEFAULTCTLIP "127.0.0.1" #define DEFAULTCTLPORT 7890 using std::memset; RouteFlowServer rfSrv(TCP_PORT, VIRT_N_FORWARD_PLANE); int main(int argc, char **argv) { timeval t; int sockFd, connCount; socklen_t cliLength; struct sockaddr_in servAddr; int8_t ret = SUCCESS; openlog("rf-server", LOG_PID, SYSLOGFACILITY); ControllerConnection qfController; ttag_Address RemoteAdd; uint32_t TCPPort; TCPSocket * tcpSocket = NULL; RFCtlMessageProcessor * rfmp = NULL; RawMessage * msg = NULL; rfmp = new RFCtlMessageProcessor(); msg = new RawMessage(); string IP = DEFAULTCTLIP; TCPPort = DEFAULTCTLPORT; /* * Initializing the TCP Socket. */ tcpSocket = new TCPSocket(); /* * Setting the FD of the TCP Socket. */ tcpSocket->open(); ret = strToAddress(IP, RemoteAdd); /* * Connecting to the controller via IP = RemoteAdd, port = port. */ uint32_t i = 0; do { ret = tcpSocket->connect(RemoteAdd, TCPPort); i++; syslog(LOG_INFO, "We are in attempt number: %d ", i); if (ret != SUCCESS) { sleep(2); } } while ((ret != SUCCESS)); qfController.setCommunicator(tcpSocket); qfController.setMessageProcessor(rfmp); qfController.setMessage((IPCMessage *) msg); qfController.arg((void *) &rfSrv); /* * Starting Controller Connection Thread */ qfController.start(); rfSrv.qfCtlConnection = &qfController; ClientConnection qfClient; qfClient.arg((void *) &rfSrv); (void) (argc); (void) (argv); t.tv_sec = 0; t.tv_usec = 1000; do { sockFd = socket(AF_INET, SOCK_STREAM, 0); if (sockFd < 0) { syslog(LOG_ERR, "Could not open a new socket"); // return -1; } sleep(2); } while (sockFd < 0); qfClient.start(); /* TODO * Get TCP port from main arguments. */ uint16_t tcpport = TCP_PORT; /*VM Connection.*/ std::memset((char *) &servAddr, 0, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = INADDR_ANY; servAddr.sin_port = htons(tcpport); int bindsocketret = 0; while (bind(sockFd, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0) { syslog(LOG_INFO, "Could not bind server socket"); sleep(2); } syslog(LOG_INFO, "Finally bound to VM sockets"); listen(sockFd, MAX_CONNECTIONS); /* sockFd should be in "blocking" mode to avoid wasting CPU time unnecessarily */ /* int flags = fcntl(sockFd, F_GETFL); flags &= ~O_NONBLOCK; fcntl(sockFd, F_SETFL, flags | O_NONBLOCK); */ cliLength = sizeof(struct sockaddr_in); connCount = 0; while (1) { struct sockaddr_in vmAddr; int vmSockFd; vmSockFd = accept(sockFd, (struct sockaddr *) &vmAddr, &cliLength); if (vmSockFd > 0) { char buffer[ETH_PKT_SIZE]; std::memset(buffer, 0, ETH_PKT_SIZE); if (rfSrv.recv_msg(vmSockFd, (RFMessage *) buffer, ETH_PKT_SIZE) <= 0) { close(vmSockFd); continue; } RFVMMsg * regMsg = (RFVMMsg *) buffer; RFVMMsg msg; msg.setDstIP(vmAddr.sin_addr.s_addr); msg.setSrcIP("10.4.1.26"); while (rfSrv.lockvmList() < 0) ; std::list<RFVirtualMachine>::iterator iter; bool alreadyregVmId = 0; for (iter = rfSrv.m_vmList.begin(); iter != rfSrv.m_vmList.end(); iter++) { if (iter->getVmId() == regMsg->getVMId()) { alreadyregVmId = 1; } } rfSrv.unlockvmList(); if (RFP_CMD_REGISTER == regMsg->getType() && !alreadyregVmId) { uint64_t vmId = regMsg->getVMId(); msg.setVMId(vmId); msg.setType(RFP_CMD_ACCPET); RFVirtualMachine newVM; newVM.setVmId(vmId); newVM.setSockFd(vmSockFd); newVM.setIpAddr(vmAddr.sin_addr.s_addr); newVM.setTcpPort(vmAddr.sin_port); newVM.setMode(RFP_VM_MODE_STANDBY); newVM.setVMAddr(&vmAddr); if (rfSrv.send_msg(vmSockFd, &msg) <= 0) { syslog(LOG_ERR, "Could not write to VM socket"); } bool found = 0; uint8_t ports; /* TODO The code below appear on the method datapath_join_event * Change it in further versions to let main.cc more clean. */ if (!rfSrv.m_dpIdleList.empty()) { //If there is an Idle Datapath. Dp2Vm_t vm2dptmp; vm2dptmp.dpId = rfSrv.Vm2DpMap(vmId); syslog(LOG_DEBUG, "Dp = %lld, VM = %lld", vm2dptmp.dpId, vmId); if (vm2dptmp.dpId != 0) { //The VM has a Datapath assigned to it? syslog(LOG_DEBUG, "Has a Datapath assigned."); std::list<Datapath_t>::iterator iter; for (iter = rfSrv.m_dpIdleList.begin(); iter != rfSrv.m_dpIdleList.end(); iter++) { /* The idle datapath belongs to some VM?*/ if (vm2dptmp.dpId == iter->dpId) { newVM.setMode(RFP_VM_MODE_RUNNING); //Set VM mode to running (local definition) Datapath_t newDP; newDP.dpId = iter->dpId; newDP.nports = iter->nports; newVM.setDpId(newDP); ports = iter->nports; rfSrv.m_dpIdleList.erase(iter); found = 1; break; } } } else { std::list<Datapath_t>::iterator iter; for (iter = rfSrv.m_dpIdleList.begin(); iter != rfSrv.m_dpIdleList.end(); iter++) { if (rfSrv.Dp2VmMap(iter->dpId == 0)) { //Is there an Idle Datapath without any VM assigned to it? newVM.setMode(RFP_VM_MODE_RUNNING); //Set VM mode to running (local definition) Datapath_t newDP; newDP.dpId = iter->dpId; newDP.nports = iter->nports; newVM.setDpId(newDP); ports = iter->nports; rfSrv.m_dpIdleList.erase(iter); vm2dptmp.vmId = newVM.getVmId(); vm2dptmp.dpId = newVM.getDpId().dpId; rfSrv.m_Dp2VmList.push_front(vm2dptmp); syslog( LOG_DEBUG, "Dp = %lld, VM = %lld added to the List", vm2dptmp.dpId, vm2dptmp.vmId); found = 1; break; } } } if (found) { /* Install flows to recieve essential traffic. */ rfSrv.send_flow_msg(newVM.getDpId().dpId, RFO_RIPV2); rfSrv.send_flow_msg(newVM.getDpId().dpId, RFO_OSPF); rfSrv.send_flow_msg(newVM.getDpId().dpId, RFO_ARP); rfSrv.send_flow_msg(newVM.getDpId().dpId, RFO_BGP); rfSrv.send_flow_msg(newVM.getDpId().dpId, RFO_ICMP); /* Configuration message to the slave. */ RFVMMsg logmsg; logmsg.setDstIP(newVM.getIpAddr()); logmsg.setSrcIP("10.4.1.26"); logmsg.setVMId(newVM.getVmId()); logmsg.setType(RFP_CMD_VM_CONFIG); logmsg.setDpId(newVM.getDpId().dpId); logmsg.setMode(RFP_VM_MODE_RUNNING); logmsg.setWildcard(RFP_VM_MODE | RFP_VM_DPID | RFP_VM_NPORTS); logmsg.setNPorts(ports); if (rfSrv.send_msg(newVM.getSockFd(), &logmsg) <= 0) { syslog(LOG_ERR, "Could not write to VM socket"); } } else { syslog( LOG_INFO, "The Datapath assigned to VM: %lld isn't connected", newVM.getVmId()); } } while (rfSrv.lockvmList() < 0); rfSrv.m_vmList.push_back(newVM); syslog(LOG_INFO, "A new VM was registered: VmId=%lld", vmId); rfSrv.unlockvmList(); }/* VmId already registered or msg type unknown. */ else { msg.setType(RFP_CMD_REJECT); syslog(LOG_INFO, "Connection refused: VmId already registered."); if (rfSrv.send_msg(vmSockFd, &msg) <= 0) { syslog(LOG_ERR, "Could not write to VM socket"); } close(vmSockFd); } } } close(sockFd); return 0; }
Install BGP,ICMP flows to DP when a VM joins and associates with it.
Install BGP,ICMP flows to DP when a VM joins and associates with it.
C++
apache-2.0
raphaelvrosa/RouteFlow,c3m3gyanesh/RouteFlow-OpenConfig,CPqD/RouteFlow,arazmj/RouteFlow,rsanger/RouteFlow,routeflow/RouteFlow,raphaelvrosa/RouteFlow,ralph-mikera/RouteFlow-1,c3m3gyanesh/RouteFlow-OpenConfig,CPqD/RouteFlow,CPqD/RouteFlow,arazmj/RouteFlow,arazmj/RouteFlow,ralph-mikera/RouteFlow-1,routeflow/RouteFlow,ralph-mikera/RouteFlow-1,raphaelvrosa/RouteFlow,srijanmishra/RouteFlow,CPqD/RouteFlow,ralph-mikera/RouteFlow-1,ralph-mikera/RouteFlow-1,ralph-mikera/RouteFlow-1,routeflow/RouteFlow,raphaelvrosa/RouteFlow,rsanger/RouteFlow,srijanmishra/RouteFlow,routeflow/RouteFlow,rsanger/RouteFlow,raphaelvrosa/RouteFlow,routeflow/RouteFlow,srijanmishra/RouteFlow,arazmj/RouteFlow,srijanmishra/RouteFlow,rsanger/RouteFlow,CPqD/RouteFlow,c3m3gyanesh/RouteFlow-OpenConfig,srijanmishra/RouteFlow,arazmj/RouteFlow,rsanger/RouteFlow,arazmj/RouteFlow,rsanger/RouteFlow,c3m3gyanesh/RouteFlow-OpenConfig,raphaelvrosa/RouteFlow,c3m3gyanesh/RouteFlow-OpenConfig,c3m3gyanesh/RouteFlow-OpenConfig
381a8b1b40b55dc4831c96d36e2f53219d212fcf
ksp_plugin_test/interface_external_test.cpp
ksp_plugin_test/interface_external_test.cpp
#include "ksp_plugin/interface.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "ksp_plugin_test/fake_plugin.hpp" #include "testing_utilities/componentwise.hpp" #include "testing_utilities/is_near.hpp" #include "testing_utilities/matchers.hpp" #include "testing_utilities/solar_system_factory.hpp" namespace principia { namespace interface { using astronomy::ICRS; using base::make_not_null_unique; using ksp_plugin::GUID; using ksp_plugin::Navigation; using ksp_plugin::PartId; using ksp_plugin::FakePlugin; using ksp_plugin::Vessel; using physics::SolarSystem; using quantities::Sqrt; using quantities::si::Centi; using quantities::si::Hour; using quantities::si::Kilo; using quantities::si::Kilogram; using quantities::si::Metre; using quantities::si::Micro; using quantities::si::Milli; using quantities::si::Newton; using quantities::si::Tonne; using testing_utilities::Componentwise; using testing_utilities::IsOk; using testing_utilities::IsNear; using testing_utilities::SolarSystemFactory; using ::testing::AllOf; using ::testing::Eq; using ::testing::Gt; using ::testing::Lt; namespace { constexpr PartId part_id = 1729; constexpr char const* vessel_guid = "NCC 1701-D"; constexpr char const* part_name = "Picard's desk"; constexpr char const* vessel_name = "Enterprise"; } // namespace class InterfaceExternalTest : public ::testing::Test { protected: InterfaceExternalTest() : plugin_(SolarSystem<ICRS>( SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt", SOLUTION_DIR / "astronomy" / "sol_initial_state_jd_2451545_000000000.proto.txt")) { physics::KeplerianElements<Barycentric> low_earth_orbit; low_earth_orbit.eccentricity = 0; low_earth_orbit.semimajor_axis = 6783 * Kilo(Metre); low_earth_orbit.inclination = 0 * Degree; low_earth_orbit.longitude_of_ascending_node = 0 * Radian; low_earth_orbit.argument_of_periapsis = 0 * Radian; low_earth_orbit.mean_anomaly = 0 * Radian; vessel_ = &plugin_.AddVesselInEarthOrbit( vessel_guid, vessel_name, part_id, part_name, low_earth_orbit); } FakePlugin plugin_; Vessel* vessel_; }; TEST_F(InterfaceExternalTest, GetNearestPlannedCoastDegreesOfFreedom) { plugin_.CreateFlightPlan( vessel_guid, plugin_.CurrentTime() + 24 * Hour, 1 * Tonne); // This variable is necessary in VS 2017 15.8 preview 3 because putting the // list initialization directly in the call below causes the frame to be // destroyed after the call. auto burn = ksp_plugin::Burn{ 180 * Kilo(Newton), 4.56 * Kilo(Newton) * Second / Kilogram, plugin_.NewBodyCentredNonRotatingNavigationFrame( SolarSystemFactory::Earth), plugin_.CurrentTime() + 30 * Second, Velocity<Frenet<Navigation>>( {1000 * Metre / Second, 0 * Metre / Second, 0 * Metre / Second}), /*is_inertially_fixed=*/false}; vessel_->flight_plan().Append(std::move(burn)); QP result; auto const to_world = plugin_.renderer().BarycentricToWorld(plugin_.PlanetariumRotation()); auto const status = principia__ExternalGetNearestPlannedCoastDegreesOfFreedom( &plugin_, SolarSystemFactory::Earth, vessel_guid, /*manoeuvre_index=*/0, /*reference_position=*/ToXYZ( to_world(Displacement<Barycentric>( {-100'000 * Kilo(Metre), 0 * Metre, 0 * Metre})).coordinates() / Metre), &result); EXPECT_THAT(base::Status(static_cast<base::Error>(status.error), ""), IsOk()); auto const barycentric_result = to_world.Inverse()(FromQP<RelativeDegreesOfFreedom<World>>(result)); // The reference position is far above the apoapsis, so the result is roughly // the apoapsis. EXPECT_THAT( barycentric_result, Componentwise(Componentwise(IsNear(-12'000 * Kilo(Metre)), IsNear(-120 * Kilo(Metre)), AllOf(Gt(-50 * Metre), Lt(50 * Metre))), Componentwise(IsNear(-6.6 * Metre / Second), IsNear(-4.9 * Kilo(Metre) / Second), AllOf(Gt(-1 * Centi(Metre) / Second), Lt(1 * Centi(Metre) / Second))))); } TEST_F(InterfaceExternalTest, Geopotential) { XY coefficient; double radius; auto status = principia__ExternalGetGeopotentialCoefficient( &plugin_, SolarSystemFactory::Earth, /*degree=*/2, /*order=*/0, &coefficient); EXPECT_THAT(base::Status(static_cast<base::Error>(status.error), ""), IsOk()); EXPECT_THAT(-coefficient.x * Sqrt(5), IsNear(1.08e-3)); EXPECT_THAT(coefficient.y, Eq(0)); status = principia__ExternalGetGeopotentialCoefficient( &plugin_, SolarSystemFactory::Earth, /*degree=*/3, /*order=*/1, &coefficient); EXPECT_THAT(base::Status(static_cast<base::Error>(status.error), ""), IsOk()); EXPECT_THAT(coefficient.x, IsNear(2.03e-6)); EXPECT_THAT(coefficient.y, IsNear(0.248e-6)); status = principia__ExternalGetGeopotentialCoefficient( &plugin_, SolarSystemFactory::Earth, /*degree=*/1729, /*order=*/163, &coefficient); EXPECT_THAT(base::Status(static_cast<base::Error>(status.error), ""), IsOk()); EXPECT_THAT(coefficient.x, Eq(0)); EXPECT_THAT(coefficient.y, Eq(0)); status = principia__ExternalGetGeopotentialReferenceRadius( &plugin_, SolarSystemFactory::Earth, &radius); EXPECT_THAT(base::Status(static_cast<base::Error>(status.error), ""), IsOk()); EXPECT_THAT(radius, Eq(6'378'136.3)); status = principia__ExternalGetGeopotentialCoefficient( &plugin_, SolarSystemFactory::Ariel, /*degree=*/2, /*order=*/2, &coefficient); EXPECT_THAT(base::Status(static_cast<base::Error>(status.error), ""), IsOk()); EXPECT_THAT(coefficient.x, Eq(0)); EXPECT_THAT(coefficient.y, Eq(0)); status = principia__ExternalGetGeopotentialCoefficient( &plugin_, SolarSystemFactory::Ariel, /*degree=*/0, /*order=*/0, &coefficient); EXPECT_THAT(base::Status(static_cast<base::Error>(status.error), ""), IsOk()); EXPECT_THAT(coefficient.x, Eq(1)); EXPECT_THAT(coefficient.y, Eq(0)); status = principia__ExternalGetGeopotentialReferenceRadius( &plugin_, SolarSystemFactory::Ariel, &radius); EXPECT_THAT(base::Status(static_cast<base::Error>(status.error), ""), IsOk()); EXPECT_THAT(radius, Eq(578'900)); } } // namespace interface } // namespace principia
#include "ksp_plugin/interface.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "ksp_plugin_test/fake_plugin.hpp" #include "testing_utilities/componentwise.hpp" #include "testing_utilities/is_near.hpp" #include "testing_utilities/matchers.hpp" #include "testing_utilities/solar_system_factory.hpp" namespace principia { namespace interface { using astronomy::ICRS; using base::make_not_null_unique; using ksp_plugin::GUID; using ksp_plugin::Navigation; using ksp_plugin::PartId; using ksp_plugin::FakePlugin; using ksp_plugin::Vessel; using physics::SolarSystem; using quantities::Sqrt; using quantities::si::Centi; using quantities::si::Hour; using quantities::si::Kilo; using quantities::si::Kilogram; using quantities::si::Metre; using quantities::si::Micro; using quantities::si::Milli; using quantities::si::Newton; using quantities::si::Tonne; using testing_utilities::Componentwise; using testing_utilities::IsOk; using testing_utilities::IsNear; using testing_utilities::SolarSystemFactory; using ::testing::AllOf; using ::testing::Eq; using ::testing::Gt; using ::testing::Lt; namespace { constexpr PartId part_id = 1729; constexpr char const* vessel_guid = "NCC 1701-D"; constexpr char const* part_name = "Picard's desk"; constexpr char const* vessel_name = "Enterprise"; } // namespace class InterfaceExternalTest : public ::testing::Test { protected: InterfaceExternalTest() : plugin_(SolarSystem<ICRS>( SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt", SOLUTION_DIR / "astronomy" / "sol_initial_state_jd_2451545_000000000.proto.txt")) { physics::KeplerianElements<Barycentric> low_earth_orbit; low_earth_orbit.eccentricity = 0; low_earth_orbit.semimajor_axis = 6783 * Kilo(Metre); low_earth_orbit.inclination = 0 * Degree; low_earth_orbit.longitude_of_ascending_node = 0 * Radian; low_earth_orbit.argument_of_periapsis = 0 * Radian; low_earth_orbit.mean_anomaly = 0 * Radian; vessel_ = &plugin_.AddVesselInEarthOrbit( vessel_guid, vessel_name, part_id, part_name, low_earth_orbit); } FakePlugin plugin_; Vessel* vessel_; }; TEST_F(InterfaceExternalTest, GetNearestPlannedCoastDegreesOfFreedom) { plugin_.CreateFlightPlan( vessel_guid, plugin_.CurrentTime() + 24 * Hour, 1 * Tonne); // This variable is necessary in VS 2017 15.8 preview 3 because putting the // list initialization directly in the call below causes the frame to be // destroyed after the call. auto burn = ksp_plugin::Burn{ 180 * Kilo(Newton), 4.56 * Kilo(Newton) * Second / Kilogram, plugin_.NewBodyCentredNonRotatingNavigationFrame( SolarSystemFactory::Earth), plugin_.CurrentTime() + 30 * Second, Velocity<Frenet<Navigation>>( {1000 * Metre / Second, 0 * Metre / Second, 0 * Metre / Second}), /*is_inertially_fixed=*/false}; vessel_->flight_plan().Append(std::move(burn)); QP result; auto const to_world = plugin_.renderer().BarycentricToWorld(plugin_.PlanetariumRotation()); auto const status = principia__ExternalGetNearestPlannedCoastDegreesOfFreedom( &plugin_, SolarSystemFactory::Earth, vessel_guid, /*manoeuvre_index=*/0, /*reference_position=*/ToXYZ( to_world(Displacement<Barycentric>( {-100'000 * Kilo(Metre), 0 * Metre, 0 * Metre})).coordinates() / Metre), &result); EXPECT_THAT(base::Status(static_cast<base::Error>(status.error), ""), IsOk()); auto const barycentric_result = to_world.Inverse()(FromQP<RelativeDegreesOfFreedom<World>>(result)); // The reference position is far above the apoapsis, so the result is roughly // the apoapsis. EXPECT_THAT( barycentric_result, Componentwise(Componentwise(IsNear(-12'000 * Kilo(Metre)), IsNear(-120 * Kilo(Metre)), AllOf(Gt(-50 * Metre), Lt(50 * Metre))), Componentwise(IsNear(-6.6 * Metre / Second), IsNear(-4.9 * Kilo(Metre) / Second), AllOf(Gt(-1 * Centi(Metre) / Second), Lt(1 * Centi(Metre) / Second))))); } TEST_F(InterfaceExternalTest, Geopotential) { XY coefficient; double radius; auto status = principia__ExternalGeopotentialGetCoefficient( &plugin_, SolarSystemFactory::Earth, /*degree=*/2, /*order=*/0, &coefficient); EXPECT_THAT(base::Status(static_cast<base::Error>(status.error), ""), IsOk()); EXPECT_THAT(-coefficient.x * Sqrt(5), IsNear(1.08e-3)); EXPECT_THAT(coefficient.y, Eq(0)); status = principia__ExternalGeopotentialGetCoefficient( &plugin_, SolarSystemFactory::Earth, /*degree=*/3, /*order=*/1, &coefficient); EXPECT_THAT(base::Status(static_cast<base::Error>(status.error), ""), IsOk()); EXPECT_THAT(coefficient.x, IsNear(2.03e-6)); EXPECT_THAT(coefficient.y, IsNear(0.248e-6)); status = principia__ExternalGeopotentialGetCoefficient( &plugin_, SolarSystemFactory::Earth, /*degree=*/1729, /*order=*/163, &coefficient); EXPECT_THAT(base::Status(static_cast<base::Error>(status.error), ""), IsOk()); EXPECT_THAT(coefficient.x, Eq(0)); EXPECT_THAT(coefficient.y, Eq(0)); status = principia__ExternalGeopotentialGetReferenceRadius( &plugin_, SolarSystemFactory::Earth, &radius); EXPECT_THAT(base::Status(static_cast<base::Error>(status.error), ""), IsOk()); EXPECT_THAT(radius, Eq(6'378'136.3)); status = principia__ExternalGeopotentialGetCoefficient( &plugin_, SolarSystemFactory::Ariel, /*degree=*/2, /*order=*/2, &coefficient); EXPECT_THAT(base::Status(static_cast<base::Error>(status.error), ""), IsOk()); EXPECT_THAT(coefficient.x, Eq(0)); EXPECT_THAT(coefficient.y, Eq(0)); status = principia__ExternalGeopotentialGetCoefficient( &plugin_, SolarSystemFactory::Ariel, /*degree=*/0, /*order=*/0, &coefficient); EXPECT_THAT(base::Status(static_cast<base::Error>(status.error), ""), IsOk()); EXPECT_THAT(coefficient.x, Eq(1)); EXPECT_THAT(coefficient.y, Eq(0)); status = principia__ExternalGeopotentialGetReferenceRadius( &plugin_, SolarSystemFactory::Ariel, &radius); EXPECT_THAT(base::Status(static_cast<base::Error>(status.error), ""), IsOk()); EXPECT_THAT(radius, Eq(578'900)); } } // namespace interface } // namespace principia
rename in the test too
rename in the test too
C++
mit
mockingbirdnest/Principia,pleroy/Principia,eggrobin/Principia,eggrobin/Principia,mockingbirdnest/Principia,eggrobin/Principia,mockingbirdnest/Principia,mockingbirdnest/Principia,pleroy/Principia,pleroy/Principia,pleroy/Principia
839cf217e24de58f07d683ab357d27d94791e1e2
training/augment_grammar.cc
training/augment_grammar.cc
#include <iostream> #include <vector> #include <boost/program_options.hpp> #include <boost/program_options/variables_map.hpp> #include "rule_lexer.h" #include "trule.h" #include "filelib.h" #include "tdict.h" #include "lm/model.hh" #include "lm/enumerate_vocab.hh" #include "wordid.h" namespace po = boost::program_options; using namespace std; vector<lm::WordIndex> word_map; lm::ngram::ProbingModel* ngram; struct VMapper : public lm::ngram::EnumerateVocab { VMapper(vector<lm::WordIndex>* out) : out_(out), kLM_UNKNOWN_TOKEN(0) { out_->clear(); } void Add(lm::WordIndex index, const StringPiece &str) { const WordID cdec_id = TD::Convert(str.as_string()); if (cdec_id >= out_->size()) out_->resize(cdec_id + 1, kLM_UNKNOWN_TOKEN); (*out_)[cdec_id] = index; } vector<lm::WordIndex>* out_; const lm::WordIndex kLM_UNKNOWN_TOKEN; }; bool InitCommandLine(int argc, char** argv, po::variables_map* conf) { po::options_description opts("Configuration options"); opts.add_options() ("source_lm,l",po::value<string>(),"Source language LM (KLM)") ("add_shape_types,s", "Add rule shape types"); po::options_description clo("Command line options"); clo.add_options() ("config", po::value<string>(), "Configuration file") ("help,h", "Print this help message and exit"); po::options_description dconfig_options, dcmdline_options; dconfig_options.add(opts); dcmdline_options.add(opts).add(clo); po::store(parse_command_line(argc, argv, dcmdline_options), *conf); if (conf->count("config")) { ifstream config((*conf)["config"].as<string>().c_str()); po::store(po::parse_config_file(config, dconfig_options), *conf); } po::notify(*conf); if (conf->count("help")) { cerr << "Usage " << argv[0] << " [OPTIONS]\n"; cerr << dcmdline_options << endl; return false; } return true; } template <class Model> float Score(const vector<WordID>& str, const Model &model) { typename Model::State state, out; lm::FullScoreReturn ret; float total = 0.0f; state = model.NullContextState(); for (int i = 0; i < str.size(); ++i) { lm::WordIndex vocab = ((str[i] < word_map.size() && str[i] > 0) ? word_map[str[i]] : 0); ret = model.FullScore(state, vocab, out); total += ret.prob; state = out; } return total; } static void RuleHelper(const TRulePtr& new_rule, const unsigned int ctf_level, const TRulePtr& coarse_rule, void* extra) { cout << *new_rule << " SrcLM=" << Score(new_rule->f_, *ngram) << endl; } int main(int argc, char** argv) { po::variables_map conf; if (!InitCommandLine(argc, argv, &conf)) return 1; if (conf.count("source_lm")) { lm::ngram::Config kconf; VMapper vm(&word_map); kconf.enumerate_vocab = &vm; ngram = new lm::ngram::ProbingModel(conf["source_lm"].as<string>().c_str(), kconf); cerr << "Loaded " << (int)ngram->Order() << "-gram KenLM (MapSize=" << word_map.size() << ")\n"; } else { ngram = NULL; } assert(ngram); RuleLexer::ReadRules(&cin, &RuleHelper, NULL); return 0; }
#include <iostream> #include <vector> #include <boost/program_options.hpp> #include <boost/program_options/variables_map.hpp> #include "rule_lexer.h" #include "trule.h" #include "filelib.h" #include "tdict.h" #include "lm/model.hh" #include "lm/enumerate_vocab.hh" #include "wordid.h" namespace po = boost::program_options; using namespace std; vector<lm::WordIndex> word_map; lm::ngram::ProbingModel* ngram; struct VMapper : public lm::ngram::EnumerateVocab { VMapper(vector<lm::WordIndex>* out) : out_(out), kLM_UNKNOWN_TOKEN(0) { out_->clear(); } void Add(lm::WordIndex index, const StringPiece &str) { const WordID cdec_id = TD::Convert(str.as_string()); if (cdec_id >= out_->size()) out_->resize(cdec_id + 1, kLM_UNKNOWN_TOKEN); (*out_)[cdec_id] = index; } vector<lm::WordIndex>* out_; const lm::WordIndex kLM_UNKNOWN_TOKEN; }; bool InitCommandLine(int argc, char** argv, po::variables_map* conf) { po::options_description opts("Configuration options"); opts.add_options() ("source_lm,l",po::value<string>(),"Source language LM (KLM)") ("add_shape_types,s", "Add rule shape types"); po::options_description clo("Command line options"); clo.add_options() ("config", po::value<string>(), "Configuration file") ("help,h", "Print this help message and exit"); po::options_description dconfig_options, dcmdline_options; dconfig_options.add(opts); dcmdline_options.add(opts).add(clo); po::store(parse_command_line(argc, argv, dcmdline_options), *conf); if (conf->count("config")) { ifstream config((*conf)["config"].as<string>().c_str()); po::store(po::parse_config_file(config, dconfig_options), *conf); } po::notify(*conf); if (conf->count("help")) { cerr << "Usage " << argv[0] << " [OPTIONS]\n"; cerr << dcmdline_options << endl; return false; } return true; } lm::WordIndex kSOS; template <class Model> float Score(const vector<WordID>& str, const Model &model) { typename Model::State state, out; lm::FullScoreReturn ret; float total = 0.0f; state = model.NullContextState(); for (int i = 0; i < str.size(); ++i) { lm::WordIndex vocab = ((str[i] < word_map.size() && str[i] > 0) ? word_map[str[i]] : 0); if (vocab == kSOS) { state = model.BeginSentenceState(); } else { ret = model.FullScore(state, vocab, out); total += ret.prob; state = out; } } return total; } static void RuleHelper(const TRulePtr& new_rule, const unsigned int ctf_level, const TRulePtr& coarse_rule, void* extra) { cout << *new_rule << " SrcLM=" << Score(new_rule->f_, *ngram) << endl; } int main(int argc, char** argv) { po::variables_map conf; if (!InitCommandLine(argc, argv, &conf)) return 1; if (conf.count("source_lm")) { lm::ngram::Config kconf; VMapper vm(&word_map); kconf.enumerate_vocab = &vm; ngram = new lm::ngram::ProbingModel(conf["source_lm"].as<string>().c_str(), kconf); kSOS = word_map[TD::Convert("<s>")]; cerr << "Loaded " << (int)ngram->Order() << "-gram KenLM (MapSize=" << word_map.size() << ")\n"; cerr << " <s> = " << kSOS << endl; } else { ngram = NULL; } assert(ngram); RuleLexer::ReadRules(&cin, &RuleHelper, NULL); return 0; }
deal with SOS
deal with SOS
C++
apache-2.0
agesmundo/FasterCubePruning,pks/cdec-dtrain-legacy,kho/mr-cdec,pks/cdec-dtrain-legacy,agesmundo/FasterCubePruning,agesmundo/FasterCubePruning,pks/cdec-dtrain-legacy,pks/cdec-dtrain-legacy,agesmundo/FasterCubePruning,kho/mr-cdec,kho/mr-cdec,agesmundo/FasterCubePruning,kho/mr-cdec,pks/cdec-dtrain-legacy,pks/cdec-dtrain-legacy,agesmundo/FasterCubePruning,kho/mr-cdec,kho/mr-cdec
52291bf1f1d5aad480b11b5378f0d85d94e5dc74
engine/src/Methcla/Memory.hpp
engine/src/Methcla/Memory.hpp
// Copyright 2012-2013 Samplecount S.L. // // 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 METHCLA_MEMORY_HPP_INCLUDED #define METHCLA_MEMORY_HPP_INCLUDED #include <algorithm> #include <boost/assert.hpp> #include <cstddef> #include <cstdint> namespace Methcla { namespace Memory { class Alignment { public: Alignment(size_t alignment) : m_alignment(std::max(alignment, sizeof(void*))) { BOOST_ASSERT_MSG( (m_alignment & (m_alignment - 1)) == 0, "Alignment must be a power of two" ); } Alignment(const Alignment&) = default; operator size_t () const { return m_alignment; } template <typename T> bool isAligned(T size) const { return isAligned(m_alignment, size); } template <typename T> T align(T size) const { return align(m_alignment, size); } template <typename T> size_t padding(T size) const { return padding(m_alignment, size); } // Aligning pointers template <typename T> bool isAligned(T* ptr) const { return isAligned(reinterpret_cast<uintptr_t>(ptr)); } template <typename T> T* align(T* ptr) const { return reinterpret_cast<T*>(align(reinterpret_cast<uintptr_t>(ptr))); } template <typename T> size_t padding(T* ptr) const { return padding(reinterpret_cast<uintptr_t>(ptr)); } // Static alignment functions template <typename T> static bool isAligned(size_t alignment, T n) { return (n & ~(alignment-1)) == n; } template <typename T> static T align(size_t alignment, T n) { return (n + alignment) & ~(alignment-1); } template <typename T> static size_t padding(size_t alignment, T n) { return align(alignment, n) - n; } private: size_t m_alignment; }; //* Default alignment. static const Alignment kDefaultAlignment( #if defined(__ANDROID__) alignof(max_align_t) #else alignof(std::max_align_t) #endif ); //* Alignment needed for data accessed by SIMD instructions. static const Alignment kSIMDAlignment(16); //* Allocate memory of `size` bytes. // // @throw std::invalid_argument // @throw std::bad_alloc void* alloc(size_t size); //* Allocate aligned memory of `size` bytes. // // @throw std::invalid_argument // @throw std::bad_alloc void* allocAligned(Alignment align, size_t size); //* Free memory allocated by this allocator. void free(void* ptr) noexcept; //* Allocate memory for `n` elements of type `T`. // // @throw std::invalid_argument // @throw std::bad_alloc template <typename T> T* allocOf(size_t n=1) { return static_cast<T*>(alloc(n * sizeof(T))); } //* Allocate aligned memory for `n` elements of type `T`. // // @throw std::invalid_argument // @throw std::bad_alloc template <typename T> T* allocAlignedOf(Alignment align, size_t n=1) { return static_cast<T*>(allocAligned(align, n * sizeof(T))); } } } #endif // METHCLA_MEMORY_HPP_INCLUDED
// Copyright 2012-2013 Samplecount S.L. // // 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 METHCLA_MEMORY_HPP_INCLUDED #define METHCLA_MEMORY_HPP_INCLUDED #include <algorithm> #include <boost/assert.hpp> #include <cstddef> #include <cstdint> namespace Methcla { namespace Memory { class Alignment { public: Alignment(size_t alignment) : m_alignment(std::max(alignment, sizeof(void*))) { BOOST_ASSERT_MSG( (m_alignment & (m_alignment - 1)) == 0, "Alignment must be a power of two" ); } Alignment(const Alignment&) = default; operator size_t () const { return m_alignment; } template <typename T> bool isAligned(T size) const { return isAligned(m_alignment, size); } template <typename T> T align(T size) const { return align(m_alignment, size); } template <typename T> size_t padding(T size) const { return padding(m_alignment, size); } // Aligning pointers template <typename T> bool isAligned(T* ptr) const { return isAligned(reinterpret_cast<uintptr_t>(ptr)); } template <typename T> T* align(T* ptr) const { return reinterpret_cast<T*>(align(reinterpret_cast<uintptr_t>(ptr))); } template <typename T> size_t padding(T* ptr) const { return padding(reinterpret_cast<uintptr_t>(ptr)); } // Static alignment functions template <typename T> static bool isAligned(size_t alignment, T n) { return (n & ~(alignment-1)) == n; } template <typename T> static T align(size_t alignment, T n) { return (n + alignment) & ~(alignment-1); } template <typename T> static size_t padding(size_t alignment, T n) { return align(alignment, n) - n; } private: size_t m_alignment; }; //* Default alignment. static const Alignment kDefaultAlignment( #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ <= 8) alignof(max_align_t) #else alignof(std::max_align_t) #endif ); //* Alignment needed for data accessed by SIMD instructions. static const Alignment kSIMDAlignment(16); //* Allocate memory of `size` bytes. // // @throw std::invalid_argument // @throw std::bad_alloc void* alloc(size_t size); //* Allocate aligned memory of `size` bytes. // // @throw std::invalid_argument // @throw std::bad_alloc void* allocAligned(Alignment align, size_t size); //* Free memory allocated by this allocator. void free(void* ptr) noexcept; //* Allocate memory for `n` elements of type `T`. // // @throw std::invalid_argument // @throw std::bad_alloc template <typename T> T* allocOf(size_t n=1) { return static_cast<T*>(alloc(n * sizeof(T))); } //* Allocate aligned memory for `n` elements of type `T`. // // @throw std::invalid_argument // @throw std::bad_alloc template <typename T> T* allocAlignedOf(Alignment align, size_t n=1) { return static_cast<T*>(allocAligned(align, n * sizeof(T))); } } } #endif // METHCLA_MEMORY_HPP_INCLUDED
Check for gcc <= 4.8 instead of Android
Check for gcc <= 4.8 instead of Android
C++
apache-2.0
samplecount/methcla,samplecount/methcla,samplecount/methcla,samplecount/methcla,samplecount/methcla,samplecount/methcla
fb799608d49df1f25b12a6e0de93690a11928dde
lib/DebugInfo/PDB/Raw/MappedBlockStream.cpp
lib/DebugInfo/PDB/Raw/MappedBlockStream.cpp
//===- MappedBlockStream.cpp - Reads stream data from a PDBFile -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/PDB/Raw/MappedBlockStream.h" #include "llvm/DebugInfo/PDB/Raw/PDBFile.h" #include "llvm/DebugInfo/PDB/Raw/RawError.h" using namespace llvm; using namespace llvm::pdb; MappedBlockStream::MappedBlockStream(uint32_t StreamIdx, const PDBFile &File) : Pdb(File) { if (StreamIdx >= Pdb.getNumStreams()) { StreamLength = 0; } else { StreamLength = Pdb.getStreamByteSize(StreamIdx); BlockList = Pdb.getStreamBlockList(StreamIdx); } } Error MappedBlockStream::readBytes(uint32_t Offset, uint32_t Size, ArrayRef<uint8_t> &Buffer) const { // Make sure we aren't trying to read beyond the end of the stream. if (Buffer.size() > StreamLength) return make_error<RawError>(raw_error_code::insufficient_buffer); if (Offset > StreamLength - Buffer.size()) return make_error<RawError>(raw_error_code::insufficient_buffer); if (tryReadContiguously(Offset, Size, Buffer)) return Error::success(); auto CacheIter = CacheMap.find(Offset); if (CacheIter != CacheMap.end()) { // In a more general solution, we would need to guarantee that the // cached allocation is at least the requested size. In practice, since // these are CodeView / PDB records, we know they are always formatted // the same way and never change, so we should never be requesting two // allocations from the same address with different sizes. Buffer = ArrayRef<uint8_t>(CacheIter->second, Size); return Error::success(); } // Otherwise allocate a large enough buffer in the pool, memcpy the data // into it, and return an ArrayRef to that. uint8_t *WriteBuffer = Pool.Allocate<uint8_t>(Size); if (auto EC = readBytes(Offset, MutableArrayRef<uint8_t>(WriteBuffer, Size))) return EC; CacheMap.insert(std::make_pair(Offset, WriteBuffer)); Buffer = ArrayRef<uint8_t>(WriteBuffer, Size); return Error::success(); } bool MappedBlockStream::tryReadContiguously(uint32_t Offset, uint32_t Size, ArrayRef<uint8_t> &Buffer) const { // Attempt to fulfill the request with a reference directly into the stream. // This can work even if the request crosses a block boundary, provided that // all subsequent blocks are contiguous. For example, a 10k read with a 4k // block size can be filled with a reference if, from the starting offset, // 3 blocks in a row are contiguous. uint32_t BlockNum = Offset / Pdb.getBlockSize(); uint32_t OffsetInBlock = Offset % Pdb.getBlockSize(); uint32_t BytesFromFirstBlock = std::min(Size, Pdb.getBlockSize() - OffsetInBlock); uint32_t NumAdditionalBlocks = llvm::alignTo(Size - BytesFromFirstBlock, Pdb.getBlockSize()) / Pdb.getBlockSize(); uint32_t RequiredContiguousBlocks = NumAdditionalBlocks + 1; uint32_t E = BlockList[BlockNum]; for (uint32_t I = 0; I < RequiredContiguousBlocks; ++I, ++E) { if (BlockList[I + BlockNum] != E) return false; } uint32_t FirstBlockAddr = BlockList[BlockNum]; StringRef Str = Pdb.getBlockData(FirstBlockAddr, Pdb.getBlockSize()); Str = Str.drop_front(OffsetInBlock); Buffer = ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Str.data()), Size); return true; } Error MappedBlockStream::readBytes(uint32_t Offset, MutableArrayRef<uint8_t> Buffer) const { uint32_t BlockNum = Offset / Pdb.getBlockSize(); uint32_t OffsetInBlock = Offset % Pdb.getBlockSize(); // Make sure we aren't trying to read beyond the end of the stream. if (Buffer.size() > StreamLength) return make_error<RawError>(raw_error_code::insufficient_buffer); if (Offset > StreamLength - Buffer.size()) return make_error<RawError>(raw_error_code::insufficient_buffer); uint32_t BytesLeft = Buffer.size(); uint32_t BytesWritten = 0; uint8_t *WriteBuffer = Buffer.data(); while (BytesLeft > 0) { uint32_t StreamBlockAddr = BlockList[BlockNum]; StringRef Data = Pdb.getBlockData(StreamBlockAddr, Pdb.getBlockSize()); const char *ChunkStart = Data.data() + OffsetInBlock; uint32_t BytesInChunk = std::min(BytesLeft, Pdb.getBlockSize() - OffsetInBlock); ::memcpy(WriteBuffer + BytesWritten, ChunkStart, BytesInChunk); BytesWritten += BytesInChunk; BytesLeft -= BytesInChunk; ++BlockNum; OffsetInBlock = 0; } return Error::success(); }
//===- MappedBlockStream.cpp - Reads stream data from a PDBFile -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/PDB/Raw/MappedBlockStream.h" #include "llvm/DebugInfo/PDB/Raw/PDBFile.h" #include "llvm/DebugInfo/PDB/Raw/RawError.h" using namespace llvm; using namespace llvm::pdb; MappedBlockStream::MappedBlockStream(uint32_t StreamIdx, const PDBFile &File) : Pdb(File) { if (StreamIdx >= Pdb.getNumStreams()) { StreamLength = 0; } else { StreamLength = Pdb.getStreamByteSize(StreamIdx); BlockList = Pdb.getStreamBlockList(StreamIdx); } } Error MappedBlockStream::readBytes(uint32_t Offset, uint32_t Size, ArrayRef<uint8_t> &Buffer) const { // Make sure we aren't trying to read beyond the end of the stream. if (Size > StreamLength) return make_error<RawError>(raw_error_code::insufficient_buffer); if (Offset > StreamLength - Size) return make_error<RawError>(raw_error_code::insufficient_buffer); if (tryReadContiguously(Offset, Size, Buffer)) return Error::success(); auto CacheIter = CacheMap.find(Offset); if (CacheIter != CacheMap.end()) { // In a more general solution, we would need to guarantee that the // cached allocation is at least the requested size. In practice, since // these are CodeView / PDB records, we know they are always formatted // the same way and never change, so we should never be requesting two // allocations from the same address with different sizes. Buffer = ArrayRef<uint8_t>(CacheIter->second, Size); return Error::success(); } // Otherwise allocate a large enough buffer in the pool, memcpy the data // into it, and return an ArrayRef to that. uint8_t *WriteBuffer = Pool.Allocate<uint8_t>(Size); if (auto EC = readBytes(Offset, MutableArrayRef<uint8_t>(WriteBuffer, Size))) return EC; CacheMap.insert(std::make_pair(Offset, WriteBuffer)); Buffer = ArrayRef<uint8_t>(WriteBuffer, Size); return Error::success(); } bool MappedBlockStream::tryReadContiguously(uint32_t Offset, uint32_t Size, ArrayRef<uint8_t> &Buffer) const { // Attempt to fulfill the request with a reference directly into the stream. // This can work even if the request crosses a block boundary, provided that // all subsequent blocks are contiguous. For example, a 10k read with a 4k // block size can be filled with a reference if, from the starting offset, // 3 blocks in a row are contiguous. uint32_t BlockNum = Offset / Pdb.getBlockSize(); uint32_t OffsetInBlock = Offset % Pdb.getBlockSize(); uint32_t BytesFromFirstBlock = std::min(Size, Pdb.getBlockSize() - OffsetInBlock); uint32_t NumAdditionalBlocks = llvm::alignTo(Size - BytesFromFirstBlock, Pdb.getBlockSize()) / Pdb.getBlockSize(); uint32_t RequiredContiguousBlocks = NumAdditionalBlocks + 1; uint32_t E = BlockList[BlockNum]; for (uint32_t I = 0; I < RequiredContiguousBlocks; ++I, ++E) { if (BlockList[I + BlockNum] != E) return false; } uint32_t FirstBlockAddr = BlockList[BlockNum]; StringRef Str = Pdb.getBlockData(FirstBlockAddr, Pdb.getBlockSize()); Str = Str.drop_front(OffsetInBlock); Buffer = ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Str.data()), Size); return true; } Error MappedBlockStream::readBytes(uint32_t Offset, MutableArrayRef<uint8_t> Buffer) const { uint32_t BlockNum = Offset / Pdb.getBlockSize(); uint32_t OffsetInBlock = Offset % Pdb.getBlockSize(); // Make sure we aren't trying to read beyond the end of the stream. if (Buffer.size() > StreamLength) return make_error<RawError>(raw_error_code::insufficient_buffer); if (Offset > StreamLength - Buffer.size()) return make_error<RawError>(raw_error_code::insufficient_buffer); uint32_t BytesLeft = Buffer.size(); uint32_t BytesWritten = 0; uint8_t *WriteBuffer = Buffer.data(); while (BytesLeft > 0) { uint32_t StreamBlockAddr = BlockList[BlockNum]; StringRef Data = Pdb.getBlockData(StreamBlockAddr, Pdb.getBlockSize()); const char *ChunkStart = Data.data() + OffsetInBlock; uint32_t BytesInChunk = std::min(BytesLeft, Pdb.getBlockSize() - OffsetInBlock); ::memcpy(WriteBuffer + BytesWritten, ChunkStart, BytesInChunk); BytesWritten += BytesInChunk; BytesLeft -= BytesInChunk; ++BlockNum; OffsetInBlock = 0; } return Error::success(); }
Fix size check when reading stream bytes.
[pdb] Fix size check when reading stream bytes. We were accidentally bounds checking the read against the output ArrayRef instead of against the size of the read. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@271040 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm
276851c8b947757bcb64f885d96778cfe601d496
src/software/SfM/ImageCollection_F_ACRobust.hpp
src/software/SfM/ImageCollection_F_ACRobust.hpp
#pragma once #include "openMVG/multiview/solver_fundamental_kernel.hpp" #include "openMVG/robust_estimation/robust_estimator_ACRansac.hpp" #include "openMVG/robust_estimation/robust_estimator_ACRansacKernelAdaptator.hpp" using namespace openMVG; using namespace openMVG::robust; //-- A contrario Functor to filter putative corresponding points struct GeometricFilter_FMatrix_AC { GeometricFilter_FMatrix_AC(double dPrecision, size_t iteration = 4096) : m_dPrecision(dPrecision), m_stIteration(iteration) {}; /// Robust fitting of the FUNDAMENTAL matrix void Fit( const Mat & xA, const std::pair<size_t, size_t> & imgSizeA, const Mat & xB, const std::pair<size_t, size_t> & imgSizeB, std::vector<size_t> & vec_inliers) const { vec_inliers.resize(0); // Define the AContrario adapted Fundamental matrix solver typedef ACKernelAdaptor< openMVG::fundamental::kernel::SevenPointSolver, openMVG::fundamental::kernel::SimpleError, UnnormalizerT, Mat3> KernelType; KernelType kernel(xA, imgSizeA.first, imgSizeA.second, xB, imgSizeB.first, imgSizeB.second, true); // Robustly estimate the Fundamental matrix with A Contrario ransac Mat3 F; double upper_bound_precision = m_dPrecision; std::pair<double,double> ACRansacOut = ACRANSAC(kernel, vec_inliers, m_stIteration, &F, upper_bound_precision); const double & threshold = ACRansacOut.first; const double & NFA = ACRansacOut.second; if (vec_inliers.size() < KernelType::MINIMUM_SAMPLES *2.5) { vec_inliers.clear(); } } double m_dPrecision; //upper_bound of the precision size_t m_stIteration; //maximal number of iteration used };
#pragma once #include <limits> #include "openMVG/multiview/solver_fundamental_kernel.hpp" #include "openMVG/robust_estimation/robust_estimator_ACRansac.hpp" #include "openMVG/robust_estimation/robust_estimator_ACRansacKernelAdaptator.hpp" using namespace openMVG; using namespace openMVG::robust; //-- A contrario Functor to filter putative corresponding points struct GeometricFilter_FMatrix_AC { GeometricFilter_FMatrix_AC( double dPrecision = std::numeric_limits<double>::infinity(), size_t iteration = 4096) : m_dPrecision(dPrecision), m_stIteration(iteration) {}; /// Robust fitting of the FUNDAMENTAL matrix void Fit( const Mat & xA, const std::pair<size_t, size_t> & imgSizeA, const Mat & xB, const std::pair<size_t, size_t> & imgSizeB, std::vector<size_t> & vec_inliers) const { vec_inliers.resize(0); // Define the AContrario adapted Fundamental matrix solver typedef ACKernelAdaptor< openMVG::fundamental::kernel::SevenPointSolver, openMVG::fundamental::kernel::SimpleError, UnnormalizerT, Mat3> KernelType; KernelType kernel(xA, imgSizeA.first, imgSizeA.second, xB, imgSizeB.first, imgSizeB.second, true); // Robustly estimate the Fundamental matrix with A Contrario ransac Mat3 F; double upper_bound_precision = m_dPrecision; std::pair<double,double> ACRansacOut = ACRANSAC(kernel, vec_inliers, m_stIteration, &F, upper_bound_precision); const double & threshold = ACRansacOut.first; const double & NFA = ACRansacOut.second; if (vec_inliers.size() < KernelType::MINIMUM_SAMPLES *2.5) { vec_inliers.clear(); } } double m_dPrecision; //upper_bound of the precision size_t m_stIteration; //maximal number of iteration used };
add default argument
add default argument
C++
mpl-2.0
Smozeley/openMVG,yoshidaken/openMVG,danylaksono/openMVG,Vinzza/openMVG,danylaksono/openMVG,openMVG/openMVG,mojovski/openMVG,Smozeley/openMVG,openMVG/openMVG,mojovski/openMVG,caymard/openMVG,caymard/openMVG,caymard/openMVG,yoshidaken/openMVG,openMVG/openMVG,danylaksono/openMVG,poparteu/openMVG,Vinzza/openMVG,poparteu/openMVG,yoshidaken/openMVG,openMVG/openMVG,poparteu/openMVG,poparteu/openMVG,Smozeley/openMVG,mojovski/openMVG,Vinzza/openMVG,openMVG/openMVG
5289944461feffd1993412ad04841510d5c2bccb
examples/maxcommonsubseq/testmaxcommonsubseq.cpp
examples/maxcommonsubseq/testmaxcommonsubseq.cpp
/* Copyright (c) 2013 Quanta Research Cambridge, Inc * * 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 <stdio.h> #include <sys/mman.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <semaphore.h> #include <ctime> #include <monkit.h> #include <mp.h> #include "StdDmaIndication.h" #include <sys/types.h> #include <sys/stat.h> #include "MaxcommonsubseqIndicationWrapper.h" #include "MaxcommonsubseqRequestProxy.h" #include "GeneratedTypes.h" #include "DmaConfigProxy.h" sem_t test_sem; sem_t setup_sem; int sw_match_cnt = 0; int hw_match_cnt = 0; class MaxcommonsubseqIndication : public MaxcommonsubseqIndicationWrapper { public: MaxcommonsubseqIndication(unsigned int id) : MaxcommonsubseqIndicationWrapper(id){}; virtual void setupAComplete() { fprintf(stderr, "setupAComplete\n"); sem_post(&setup_sem); } virtual void setupBComplete() { fprintf(stderr, "setupBComplete\n"); sem_post(&setup_sem); } virtual void fetchComplete() { fprintf(stderr, "fetchComplete\n"); sem_post(&setup_sem); } virtual void searchResult (int v){ fprintf(stderr, "searchResult = %d\n", v); sem_post(&test_sem); } }; int main(int argc, const char **argv) { MaxcommonsubseqRequestProxy *device = 0; DmaConfigProxy *dma = 0; MaxcommonsubseqIndication *deviceIndication = 0; DmaIndication *dmaIndication = 0; fprintf(stderr, "%s %s\n", __DATE__, __TIME__); device = new MaxcommonsubseqRequestProxy(IfcNames_MaxcommonsubseqRequest); dma = new DmaConfigProxy(IfcNames_DmaConfig); deviceIndication = new MaxcommonsubseqIndication(IfcNames_MaxcommonsubseqIndication); dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication); if(sem_init(&test_sem, 1, 0)){ fprintf(stderr, "failed to init test_sem\n"); return -1; } if(sem_init(&setup_sem, 1, 0)){ fprintf(stderr, "failed to init setup_sem\n"); return -1; } pthread_t tid; fprintf(stderr, "creating exec thread\n"); if(pthread_create(&tid, NULL, portalExec, NULL)){ fprintf(stderr, "error creating exec thread\n"); exit(1); } fprintf(stderr, "simple tests\n"); PortalAlloc *strAAlloc; PortalAlloc *strBAlloc; PortalAlloc *fetchAlloc; unsigned int alloc_len = 128; unsigned int fetch_len = alloc_len * alloc_len; int rcA, rcB, rcFetch; struct stat statAbuf, statBbuf, statFetchbuf; dma->alloc(fetch_len*sizeof(uint16_t), &fetchAlloc); rcFetch = fstat(fetchAlloc->header.fd, &statFetchbuf); if (rcA < 0) perror("fstatFetch"); int *fetch = (int *)mmap(0, fetch_len * sizeof(uint16_t), PROT_READ|PROT_WRITE, MAP_SHARED, fetchAlloc->header.fd, 0); if (fetch == MAP_FAILED) perror("fetch mmap failed"); assert(fetch != MAP_FAILED); dma->alloc(alloc_len, &strAAlloc); rcA = fstat(strAAlloc->header.fd, &statAbuf); if (rcA < 0) perror("fstatA"); char *strA = (char *)mmap(0, alloc_len, PROT_READ|PROT_WRITE, MAP_SHARED, strAAlloc->header.fd, 0); if (strA == MAP_FAILED) perror("strA mmap failed"); assert(strA != MAP_FAILED); dma->alloc(alloc_len, &strBAlloc); rcB = fstat(strBAlloc->header.fd, &statBbuf); if (rcA < 0) perror("fstatB"); char *strB = (char *)mmap(0, alloc_len, PROT_READ|PROT_WRITE, MAP_SHARED, strBAlloc->header.fd, 0); if (strB == MAP_FAILED) perror("strB mmap failed"); assert(strB != MAP_FAILED); const char *strA_text = " a b c "; const char *strB_text = "..a........b.c...."; assert(strlen(strA_text) < alloc_len); assert(strlen(strB_text) < alloc_len); strncpy(strA, strA_text, alloc_len); strncpy(strB, strB_text, alloc_len); int strA_len = strlen(strA); int strB_len = strlen(strB); uint16_t swFetch[fetch_len]; init_timer(); start_timer(0); fprintf(stderr, "elapsed time (hw cycles): %zd\n", lap_timer(0)); dma->dCacheFlushInval(strAAlloc, strA); dma->dCacheFlushInval(strBAlloc, strB); dma->dCacheFlushInval(fetchAlloc, fetch); unsigned int ref_strAAlloc = dma->reference(strAAlloc); unsigned int ref_strBAlloc = dma->reference(strBAlloc); unsigned int ref_fetchAlloc = dma->reference(fetchAlloc); device->setupA(ref_strAAlloc, strA_len); sem_wait(&setup_sem); device->setupB(ref_strBAlloc, strB_len); sem_wait(&setup_sem); fprintf(stderr, "starting algorithm A\n"); init_timer(); start_timer(0); device->start(0); sem_wait(&test_sem); uint64_t cycles = lap_timer(0); uint64_t beats = dma->show_mem_stats(ChannelType_Read); fprintf(stderr, "hw cycles: %f\n", (float)cycles); device->fetch(ref_fetchAlloc, 0, 0, fetch_len / 2); sem_wait(&setup_sem); printf("fetch 1 finished \n"); device->fetch(ref_fetchAlloc, fetch_len, fetch_len / 2, fetch_len / 2); sem_wait(&setup_sem); printf("fetch 2 finished \n"); memcpy(swFetch, fetch, fetch_len * sizeof(uint16_t)); printf(" "); for (int j = 0; j <= strB_len; j += 1) { printf("%4d", j); } printf("\n"); printf(" "); for (int j = 0; j <= strB_len; j += 1) { printf("%4c", strB[j-1]); } printf("\n"); for (int i = 0; i <= strA_len; i += 1) { printf("%4c%4d", strA[i-1], i); for (int j = 0; j <= strB_len; j += 1) { printf("%4d", swFetch[(i << 7) + j] & 0xff); } printf("\n"); } fprintf(stderr, "starting algorithm B\n"); device->start(1); sem_wait(&test_sem); cycles = lap_timer(0); fprintf(stderr, "hw cycles: %f\n", (float)cycles); device->fetch(ref_fetchAlloc, 0, 0, fetch_len / 2); sem_wait(&setup_sem); memcpy(swFetch, fetch, fetch_len * sizeof(uint16_t)); for (int j = 0; j <= strB_len; j += 1) { printf("%4d", j); } printf("\n"); printf(" "); for (int j = 0; j <= strB_len; j += 1) { printf("%4c", strB[j-1]); } printf("\n"); for (int i = 0; i < 1; i += 1) { printf("%4c%4d", strA[i-1], i); for (int j = 0; j <= strB_len; j += 1) { printf("%4d", swFetch[(i << 7) + j] & 0xff); } printf("\n"); } close(strAAlloc->header.fd); close(strBAlloc->header.fd); close(fetchAlloc->header.fd); }
/* Copyright (c) 2013 Quanta Research Cambridge, Inc * * 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 <stdio.h> #include <sys/mman.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <semaphore.h> #include <ctime> #include <monkit.h> #include <mp.h> #include "StdDmaIndication.h" #include <sys/types.h> #include <sys/stat.h> #include "MaxcommonsubseqIndicationWrapper.h" #include "MaxcommonsubseqRequestProxy.h" #include "GeneratedTypes.h" #include "DmaConfigProxy.h" sem_t test_sem; sem_t setup_sem; int sw_match_cnt = 0; int hw_match_cnt = 0; class MaxcommonsubseqIndication : public MaxcommonsubseqIndicationWrapper { public: MaxcommonsubseqIndication(unsigned int id) : MaxcommonsubseqIndicationWrapper(id){}; virtual void setupAComplete() { fprintf(stderr, "setupAComplete\n"); sem_post(&setup_sem); } virtual void setupBComplete() { fprintf(stderr, "setupBComplete\n"); sem_post(&setup_sem); } virtual void fetchComplete() { fprintf(stderr, "fetchComplete\n"); sem_post(&setup_sem); } virtual void searchResult (int v){ fprintf(stderr, "searchResult = %d\n", v); sem_post(&test_sem); } }; int main(int argc, const char **argv) { MaxcommonsubseqRequestProxy *device = 0; DmaConfigProxy *dma = 0; MaxcommonsubseqIndication *deviceIndication = 0; DmaIndication *dmaIndication = 0; fprintf(stderr, "%s %s\n", __DATE__, __TIME__); device = new MaxcommonsubseqRequestProxy(IfcNames_MaxcommonsubseqRequest); dma = new DmaConfigProxy(IfcNames_DmaConfig); deviceIndication = new MaxcommonsubseqIndication(IfcNames_MaxcommonsubseqIndication); dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication); if(sem_init(&test_sem, 1, 0)){ fprintf(stderr, "failed to init test_sem\n"); return -1; } if(sem_init(&setup_sem, 1, 0)){ fprintf(stderr, "failed to init setup_sem\n"); return -1; } pthread_t tid; fprintf(stderr, "creating exec thread\n"); if(pthread_create(&tid, NULL, portalExec, NULL)){ fprintf(stderr, "error creating exec thread\n"); exit(1); } fprintf(stderr, "simple tests\n"); PortalAlloc *strAAlloc; PortalAlloc *strBAlloc; PortalAlloc *fetchAlloc; unsigned int alloc_len = 128; unsigned int fetch_len = alloc_len * alloc_len; int rcA, rcB, rcFetch; struct stat statAbuf, statBbuf, statFetchbuf; dma->alloc(fetch_len*sizeof(uint16_t), &fetchAlloc); rcFetch = fstat(fetchAlloc->header.fd, &statFetchbuf); if (rcA < 0) perror("fstatFetch"); int *fetch = (int *)mmap(0, fetch_len * sizeof(uint16_t), PROT_READ|PROT_WRITE, MAP_SHARED, fetchAlloc->header.fd, 0); if (fetch == MAP_FAILED) perror("fetch mmap failed"); assert(fetch != MAP_FAILED); dma->alloc(alloc_len, &strAAlloc); rcA = fstat(strAAlloc->header.fd, &statAbuf); if (rcA < 0) perror("fstatA"); char *strA = (char *)mmap(0, alloc_len, PROT_READ|PROT_WRITE, MAP_SHARED, strAAlloc->header.fd, 0); if (strA == MAP_FAILED) perror("strA mmap failed"); assert(strA != MAP_FAILED); dma->alloc(alloc_len, &strBAlloc); rcB = fstat(strBAlloc->header.fd, &statBbuf); if (rcA < 0) perror("fstatB"); char *strB = (char *)mmap(0, alloc_len, PROT_READ|PROT_WRITE, MAP_SHARED, strBAlloc->header.fd, 0); if (strB == MAP_FAILED) perror("strB mmap failed"); assert(strB != MAP_FAILED); const char *strA_text = " a b c "; const char *strB_text = "..a........b.c...."; assert(strlen(strA_text) < alloc_len); assert(strlen(strB_text) < alloc_len); strncpy(strA, strA_text, alloc_len); strncpy(strB, strB_text, alloc_len); int strA_len = strlen(strA); int strB_len = strlen(strB); uint16_t swFetch[fetch_len]; init_timer(); start_timer(0); fprintf(stderr, "elapsed time (hw cycles): %zd\n", lap_timer(0)); dma->dCacheFlushInval(strAAlloc, strA); dma->dCacheFlushInval(strBAlloc, strB); dma->dCacheFlushInval(fetchAlloc, fetch); unsigned int ref_strAAlloc = dma->reference(strAAlloc); unsigned int ref_strBAlloc = dma->reference(strBAlloc); unsigned int ref_fetchAlloc = dma->reference(fetchAlloc); device->setupA(ref_strAAlloc, strA_len); sem_wait(&setup_sem); device->setupB(ref_strBAlloc, strB_len); sem_wait(&setup_sem); fprintf(stderr, "starting algorithm A\n"); init_timer(); start_timer(0); device->start(0); sem_wait(&test_sem); uint64_t cycles = lap_timer(0); uint64_t beats = dma->show_mem_stats(ChannelType_Read); fprintf(stderr, "hw cycles: %f\n", (float)cycles); device->fetch(ref_fetchAlloc, 0, 0, fetch_len / 2); sem_wait(&setup_sem); printf("fetch 1 finished \n"); device->fetch(ref_fetchAlloc, fetch_len, fetch_len / 2, fetch_len / 2); sem_wait(&setup_sem); printf("fetch 2 finished \n"); memcpy(swFetch, fetch, fetch_len * sizeof(uint16_t)); printf(" "); for (int j = 0; j <= strB_len; j += 1) { printf("%4d", j); } printf("\n"); printf(" "); for (int j = 0; j <= strB_len; j += 1) { printf("%4c", strB[j-1]); } printf("\n"); for (int i = 0; i <= strA_len; i += 1) { printf("%4c%4d", strA[i-1], i); for (int j = 0; j <= strB_len; j += 1) { printf("%4d", swFetch[(i << 7) + j] & 0xff); } printf("\n"); } fprintf(stderr, "starting algorithm B\n"); init_timer(); start_timer(0); device->start(1); sem_wait(&test_sem); cycles = lap_timer(0); fprintf(stderr, "hw cycles: %f\n", (float)cycles); device->fetch(ref_fetchAlloc, 0, 0, fetch_len / 2); sem_wait(&setup_sem); memcpy(swFetch, fetch, fetch_len * sizeof(uint16_t)); for (int j = 0; j <= strB_len; j += 1) { printf("%4d", j); } printf("\n"); printf(" "); for (int j = 0; j <= strB_len; j += 1) { printf("%4c", strB[j-1]); } printf("\n"); for (int i = 0; i < 1; i += 1) { printf("%4c%4d", strA[i-1], i); for (int j = 0; j <= strB_len; j += 1) { printf("%4d", swFetch[(i << 7) + j] & 0xff); } printf("\n"); } close(strAAlloc->header.fd); close(strBAlloc->header.fd); close(fetchAlloc->header.fd); }
fix timer initialization
fix timer initialization
C++
mit
8l/connectal,cambridgehackers/connectal,hanw/connectal,csail-csg/connectal,csail-csg/connectal,cambridgehackers/connectal,hanw/connectal,csail-csg/connectal,csail-csg/connectal,csail-csg/connectal,chenm001/connectal,8l/connectal,8l/connectal,chenm001/connectal,cambridgehackers/connectal,8l/connectal,hanw/connectal,cambridgehackers/connectal,hanw/connectal,chenm001/connectal,8l/connectal,hanw/connectal,cambridgehackers/connectal,chenm001/connectal,chenm001/connectal
02689f2d6932c2e0311337de0f7f3e558a9f4162
src/trusted/validator_arm/actual_vs_baseline.cc
src/trusted/validator_arm/actual_vs_baseline.cc
/* * Copyright (c) 2012 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef NACL_TRUSTED_BUT_NOT_TCB #error This file is not meant for use in the TCB #endif #include "native_client/src/trusted/validator_arm/actual_vs_baseline.h" #include "gtest/gtest.h" namespace nacl_arm_test { ActualVsBaselineTester::ActualVsBaselineTester( const NamedClassDecoder& actual, DecoderTester& baseline_tester) : Arm32DecoderTester(baseline_tester.ExpectedDecoder()), actual_(actual), baseline_(baseline_tester.ExpectedDecoder()), baseline_tester_(baseline_tester), actual_decoder_(actual_.named_decoder()), baseline_decoder_(baseline_.named_decoder()) {} bool ActualVsBaselineTester::DoApplySanityChecks() { return baseline_tester_.ApplySanityChecks( inst_, baseline_tester_.GetInstDecoder()); } void ActualVsBaselineTester::ProcessMatch() { baseline_tester_.InjectInstruction(inst_); const NamedClassDecoder& decoder = baseline_tester_.GetInstDecoder(); if (!baseline_tester_.PassesParsePreconditions(inst_, decoder)) { // Parse precondition implies that this pattern is NOT supposed to // be handled by the baseline tester (because another decoder // handles it). Hence, don't do any further processing. return; } if (nacl_arm_dec::MAY_BE_SAFE == decoder.safety(inst_)) { // Run sanity baseline checks, to see that the baseline is // correct. if (!DoApplySanityChecks()) { // The sanity checks found a serious issue and already reported // it. don't bother to report additional problems. return; } // Check virtuals. Start with check if safe. If unsafe, no further // checking need be applied, since the validator will stop // processing such instructions after the safe test. if (!MayBeSafe()) return; } else { // Not safe in baseline, only compare safety, testing if not safe // in actual as well. MayBeSafe(); return; } // If reached, the instruction passed the initial safety check, and // will use the other virtual methods of the class decoders to // determine if the instruction is safe. Also verifies that we get // consistent behaviour between the actual and basline class // decoders. CheckDefs(); CheckUses(); CheckBaseAddressRegisterWritebackSmallImmediate(); CheckBaseAddressRegister(); CheckIsLiteralLoad(); CheckBranchTargetRegister(); CheckIsRelativeBranch(); CheckBranchTargetOffset(); CheckIsLiteralPoolHead(); CheckClearsBits(); CheckSetsZIfBitsClear(); } bool ActualVsBaselineTester::ApplySanityChecks( nacl_arm_dec::Instruction inst, const NamedClassDecoder& decoder) { UNREFERENCED_PARAMETER(inst); UNREFERENCED_PARAMETER(decoder); EXPECT_TRUE(false) << "Sanity Checks shouldn't be applied!"; return false; } const NamedClassDecoder& ActualVsBaselineTester::ExpectedDecoder() const { return baseline_; } bool ActualVsBaselineTester::MayBeSafe() { // Note: We don't actually check if safety is identical. All we worry // about is that the validator (in sel_ldr) accepts/rejects the same // way in terms of safety. We don't worry if the reasons for safety // failing is the same. if (actual_decoder_.safety(inst_) == nacl_arm_dec::MAY_BE_SAFE) { NC_EXPECT_EQ_PRECOND(nacl_arm_dec::MAY_BE_SAFE, baseline_decoder_.safety(inst_)); return true; } else { NC_EXPECT_NE_PRECOND(nacl_arm_dec::MAY_BE_SAFE, baseline_decoder_.safety(inst_)); return false; } } void ActualVsBaselineTester::CheckDefs() { nacl_arm_dec::RegisterList actual_defs(actual_decoder_.defs(inst_)); nacl_arm_dec::RegisterList baseline_defs(baseline_decoder_.defs(inst_)); EXPECT_TRUE(baseline_defs.Equals(actual_defs)); } void ActualVsBaselineTester::CheckUses() { nacl_arm_dec::RegisterList actual_uses(actual_decoder_.uses(inst_)); nacl_arm_dec::RegisterList baseline_uses(baseline_decoder_.uses(inst_)); EXPECT_TRUE(baseline_decoder_.uses(inst_). Equals(actual_decoder_.uses(inst_))); } void ActualVsBaselineTester::CheckBaseAddressRegisterWritebackSmallImmediate() { EXPECT_EQ( baseline_decoder_.base_address_register_writeback_small_immediate(inst_), actual_decoder_.base_address_register_writeback_small_immediate(inst_)); } void ActualVsBaselineTester::CheckBaseAddressRegister() { EXPECT_TRUE( baseline_decoder_.base_address_register(inst_).Equals( actual_decoder_.base_address_register(inst_))); } void ActualVsBaselineTester::CheckIsLiteralLoad() { EXPECT_EQ(baseline_decoder_.is_literal_load(inst_), actual_decoder_.is_literal_load(inst_)); } void ActualVsBaselineTester::CheckBranchTargetRegister() { EXPECT_TRUE( baseline_decoder_.branch_target_register(inst_).Equals( actual_decoder_.branch_target_register(inst_))); } void ActualVsBaselineTester::CheckIsRelativeBranch() { EXPECT_EQ(baseline_decoder_.is_relative_branch(inst_), actual_decoder_.is_relative_branch(inst_)); } void ActualVsBaselineTester::CheckBranchTargetOffset() { EXPECT_EQ(baseline_decoder_.branch_target_offset(inst_), actual_decoder_.branch_target_offset(inst_)); } void ActualVsBaselineTester::CheckIsLiteralPoolHead() { EXPECT_EQ(baseline_decoder_.is_literal_pool_head(inst_), actual_decoder_.is_literal_pool_head(inst_)); } // Mask to use if code bundle size is 16. static const uint32_t code_mask = 15; // Mask to use if data block is 16 bytes. static const uint32_t data16_mask = 0xFFFF; // Mask to use if data block is 24 bytes. static const uint32_t data24_mask = 0xFFFFFF; void ActualVsBaselineTester::CheckClearsBits() { // Note: We don't actually test all combinations. We just try a few. // Assuming code bundle size is 16, see if we are the same. EXPECT_EQ(baseline_decoder_.clears_bits(inst_, code_mask), actual_decoder_.clears_bits(inst_, code_mask)); // Assume data division size is 16 bytes. EXPECT_EQ(baseline_decoder_.clears_bits(inst_, data16_mask), actual_decoder_.clears_bits(inst_, data16_mask)); // Assume data division size is 24 bytes. EXPECT_EQ(baseline_decoder_.clears_bits(inst_, data24_mask), actual_decoder_.clears_bits(inst_, data24_mask)); } void ActualVsBaselineTester::CheckSetsZIfBitsClear() { // Note: We don't actually test all combinations of masks. We just // try a few. for (uint32_t i = 0; i < 15; ++i) { nacl_arm_dec::Register r(i); EXPECT_EQ(baseline_decoder_.sets_Z_if_bits_clear(inst_, r, data24_mask), actual_decoder_.sets_Z_if_bits_clear(inst_, r, data24_mask)); } } } // namespace nacl_arm_test
/* * Copyright (c) 2012 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef NACL_TRUSTED_BUT_NOT_TCB #error This file is not meant for use in the TCB #endif #include "native_client/src/trusted/validator_arm/actual_vs_baseline.h" #include "gtest/gtest.h" namespace nacl_arm_test { ActualVsBaselineTester::ActualVsBaselineTester( const NamedClassDecoder& actual, DecoderTester& baseline_tester) : Arm32DecoderTester(baseline_tester.ExpectedDecoder()), actual_(actual), baseline_(baseline_tester.ExpectedDecoder()), baseline_tester_(baseline_tester), actual_decoder_(actual_.named_decoder()), baseline_decoder_(baseline_.named_decoder()) {} bool ActualVsBaselineTester::DoApplySanityChecks() { return baseline_tester_.ApplySanityChecks( inst_, baseline_tester_.GetInstDecoder()); } void ActualVsBaselineTester::ProcessMatch() { baseline_tester_.InjectInstruction(inst_); const NamedClassDecoder& decoder = baseline_tester_.GetInstDecoder(); if (!baseline_tester_.PassesParsePreconditions(inst_, decoder)) { // Parse precondition implies that this pattern is NOT supposed to // be handled by the baseline tester (because another decoder // handles it). Hence, don't do any further processing. return; } if (nacl_arm_dec::MAY_BE_SAFE == decoder.safety(inst_)) { // Run sanity baseline checks, to see that the baseline is // correct. if (!DoApplySanityChecks()) { // The sanity checks found a serious issue and already reported // it. don't bother to report additional problems. return; } // Check virtuals. Start with check if safe. If unsafe, no further // checking need be applied, since the validator will stop // processing such instructions after the safe test. if (!MayBeSafe()) return; } else { // Not safe in baseline, only compare safety, testing if not safe // in actual as well. MayBeSafe(); return; } // If reached, the instruction passed the initial safety check, and // will use the other virtual methods of the class decoders to // determine if the instruction is safe. Also verifies that we get // consistent behaviour between the actual and basline class // decoders. CheckDefs(); CheckUses(); CheckBaseAddressRegisterWritebackSmallImmediate(); CheckBaseAddressRegister(); CheckIsLiteralLoad(); CheckBranchTargetRegister(); CheckIsRelativeBranch(); CheckBranchTargetOffset(); CheckIsLiteralPoolHead(); CheckClearsBits(); CheckSetsZIfBitsClear(); } bool ActualVsBaselineTester::ApplySanityChecks( nacl_arm_dec::Instruction inst, const NamedClassDecoder& decoder) { UNREFERENCED_PARAMETER(inst); UNREFERENCED_PARAMETER(decoder); EXPECT_TRUE(false) << "Sanity Checks shouldn't be applied!"; return false; } const NamedClassDecoder& ActualVsBaselineTester::ExpectedDecoder() const { return baseline_; } bool ActualVsBaselineTester::MayBeSafe() { // Note: We don't actually check if safety is identical. All we worry // about is that the validator (in sel_ldr) accepts/rejects the same // way in terms of safety. We don't worry if the reasons for safety // failing is the same. if (actual_decoder_.safety(inst_) == nacl_arm_dec::MAY_BE_SAFE) { NC_EXPECT_EQ_PRECOND(nacl_arm_dec::MAY_BE_SAFE, baseline_decoder_.safety(inst_)); return true; } else { NC_EXPECT_NE_PRECOND(nacl_arm_dec::MAY_BE_SAFE, baseline_decoder_.safety(inst_)); return false; } } void ActualVsBaselineTester::CheckDefs() { nacl_arm_dec::RegisterList actual_defs(actual_decoder_.defs(inst_)); nacl_arm_dec::RegisterList baseline_defs(baseline_decoder_.defs(inst_)); EXPECT_TRUE(baseline_defs.Equals(actual_defs)); } void ActualVsBaselineTester::CheckUses() { nacl_arm_dec::RegisterList actual_uses(actual_decoder_.uses(inst_)); nacl_arm_dec::RegisterList baseline_uses(baseline_decoder_.uses(inst_)); EXPECT_TRUE(baseline_uses.Equals(actual_uses)); } void ActualVsBaselineTester::CheckBaseAddressRegisterWritebackSmallImmediate() { EXPECT_EQ( baseline_decoder_.base_address_register_writeback_small_immediate(inst_), actual_decoder_.base_address_register_writeback_small_immediate(inst_)); } void ActualVsBaselineTester::CheckBaseAddressRegister() { EXPECT_TRUE( baseline_decoder_.base_address_register(inst_).Equals( actual_decoder_.base_address_register(inst_))); } void ActualVsBaselineTester::CheckIsLiteralLoad() { EXPECT_EQ(baseline_decoder_.is_literal_load(inst_), actual_decoder_.is_literal_load(inst_)); } void ActualVsBaselineTester::CheckBranchTargetRegister() { EXPECT_TRUE( baseline_decoder_.branch_target_register(inst_).Equals( actual_decoder_.branch_target_register(inst_))); } void ActualVsBaselineTester::CheckIsRelativeBranch() { EXPECT_EQ(baseline_decoder_.is_relative_branch(inst_), actual_decoder_.is_relative_branch(inst_)); } void ActualVsBaselineTester::CheckBranchTargetOffset() { EXPECT_EQ(baseline_decoder_.branch_target_offset(inst_), actual_decoder_.branch_target_offset(inst_)); } void ActualVsBaselineTester::CheckIsLiteralPoolHead() { EXPECT_EQ(baseline_decoder_.is_literal_pool_head(inst_), actual_decoder_.is_literal_pool_head(inst_)); } // Mask to use if code bundle size is 16. static const uint32_t code_mask = 15; // Mask to use if data block is 16 bytes. static const uint32_t data16_mask = 0xFFFF; // Mask to use if data block is 24 bytes. static const uint32_t data24_mask = 0xFFFFFF; void ActualVsBaselineTester::CheckClearsBits() { // Note: We don't actually test all combinations. We just try a few. // Assuming code bundle size is 16, see if we are the same. EXPECT_EQ(baseline_decoder_.clears_bits(inst_, code_mask), actual_decoder_.clears_bits(inst_, code_mask)); // Assume data division size is 16 bytes. EXPECT_EQ(baseline_decoder_.clears_bits(inst_, data16_mask), actual_decoder_.clears_bits(inst_, data16_mask)); // Assume data division size is 24 bytes. EXPECT_EQ(baseline_decoder_.clears_bits(inst_, data24_mask), actual_decoder_.clears_bits(inst_, data24_mask)); } void ActualVsBaselineTester::CheckSetsZIfBitsClear() { // Note: We don't actually test all combinations of masks. We just // try a few. for (uint32_t i = 0; i < 15; ++i) { nacl_arm_dec::Register r(i); EXPECT_EQ(baseline_decoder_.sets_Z_if_bits_clear(inst_, r, data24_mask), actual_decoder_.sets_Z_if_bits_clear(inst_, r, data24_mask)); } } } // namespace nacl_arm_test
Fix a clang-discovered unused variable bug.
Fix a clang-discovered unused variable bug. This bug was introduced in https://codereview.chromium.org/12328043 It is minor, since the test itself is okay -- it just discards the computed values (since variables are unused) and recomputes them, using a POD-style structure equality comparison. [email protected] BUG= http://code.google.com/p/nativeclient/issues/detail?id=3111 TEST= existing validator tests Review URL: https://codereview.chromium.org/23621009 git-svn-id: 721b910a23eff8a86f00c8fd261a7587cddf18f8@12083 fcba33aa-ac0c-11dd-b9e7-8d5594d729c2
C++
bsd-3-clause
sbc100/native_client,sbc100/native_client,sbc100/native_client,sbc100/native_client,sbc100/native_client,sbc100/native_client
3eda4c9eacf4c1436bfb0a691d4e6a6390433f10
runtime/hipacc_cpu.hpp
runtime/hipacc_cpu.hpp
// // Copyright (c) 2014, Saarland University // 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. // #ifndef __HIPACC_CPU_HPP__ #define __HIPACC_CPU_HPP__ #include "hipacc_base.hpp" class HipaccContext : public HipaccContextBase { public: static HipaccContext &getInstance() { static HipaccContext instance; return instance; } }; // Allocate memory with alignment specified template<typename T> HipaccImage hipaccCreateMemory(T *host_mem, int width, int height, int alignment) { T *mem; HipaccContext &Ctx = HipaccContext::getInstance(); // alignment has to be a multiple of sizeof(T) alignment = (int)ceilf((float)alignment/sizeof(T)) * sizeof(T); // compute stride int stride = (int)ceilf((float)(width)/(alignment/sizeof(T))) * (alignment/sizeof(T)); mem = (T *)malloc(sizeof(T)*stride*height); HipaccImage img = HipaccImage(width, height, stride, alignment, sizeof(T), (void *)mem); Ctx.add_image(img); return img; } // Allocate memory without any alignment considerations template<typename T> HipaccImage hipaccCreateMemory(T *host_mem, int width, int height) { T *mem; HipaccContext &Ctx = HipaccContext::getInstance(); mem = (T *)malloc(sizeof(T)*width*height); HipaccImage img = HipaccImage(width, height, width, 0, sizeof(T), (void *)mem); Ctx.add_image(img); return img; } // Release memory void hipaccReleaseMemory(HipaccImage &img) { HipaccContext &Ctx = HipaccContext::getInstance(); free(img.mem); Ctx.del_image(img); } // Write to memory template<typename T> void hipaccWriteMemory(HipaccImage &img, T *host_mem) { int width = img.width; int height = img.height; int stride = img.stride; if (stride > width) { for (size_t i=0; i<height; ++i) { memcpy(&((T*)img.mem)[i*stride], &host_mem[i*width], sizeof(T)*width); } } else { memcpy(img.mem, host_mem, sizeof(T)*width*height); } } // Read from memory template<typename T> void hipaccReadMemory(T *host_mem, HipaccImage &img) { int width = img.width; int height = img.height; int stride = img.stride; if (stride > width) { for (size_t i=0; i<height; ++i) { memcpy(&host_mem[i*width], &((T*)img.mem)[i*stride], sizeof(T)*width); } } else { memcpy(host_mem, img.mem, sizeof(T)*width*height); } } // Copy from memory to memory void hipaccCopyMemory(HipaccImage &src, HipaccImage &dst) { int height = src.height; int stride = src.stride; memcpy(dst.mem, src.mem, src.pixel_size*stride*height); } // Copy from memory region to memory region void hipaccCopyMemoryRegion(HipaccAccessor src, HipaccAccessor dst) { for (size_t i=0; i<dst.height; ++i) { memcpy(&((uchar*)dst.img.mem)[dst.offset_x*dst.img.pixel_size + (dst.offset_y + i)*dst.img.stride*dst.img.pixel_size], &((uchar*)src.img.mem)[src.offset_x*src.img.pixel_size + (src.offset_y + i)*src.img.stride*src.img.pixel_size], src.width*src.img.pixel_size); } } #endif // __HIPACC_CPU_HPP__
// // Copyright (c) 2014, Saarland University // 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. // #ifndef __HIPACC_CPU_HPP__ #define __HIPACC_CPU_HPP__ #include <string.h> #include "hipacc_base.hpp" class HipaccContext : public HipaccContextBase { public: static HipaccContext &getInstance() { static HipaccContext instance; return instance; } }; // Allocate memory with alignment specified template<typename T> HipaccImage hipaccCreateMemory(T *host_mem, int width, int height, int alignment) { T *mem; HipaccContext &Ctx = HipaccContext::getInstance(); // alignment has to be a multiple of sizeof(T) alignment = (int)ceilf((float)alignment/sizeof(T)) * sizeof(T); // compute stride int stride = (int)ceilf((float)(width)/(alignment/sizeof(T))) * (alignment/sizeof(T)); mem = (T *)malloc(sizeof(T)*stride*height); HipaccImage img = HipaccImage(width, height, stride, alignment, sizeof(T), (void *)mem); Ctx.add_image(img); return img; } // Allocate memory without any alignment considerations template<typename T> HipaccImage hipaccCreateMemory(T *host_mem, int width, int height) { T *mem; HipaccContext &Ctx = HipaccContext::getInstance(); mem = (T *)malloc(sizeof(T)*width*height); HipaccImage img = HipaccImage(width, height, width, 0, sizeof(T), (void *)mem); Ctx.add_image(img); return img; } // Release memory void hipaccReleaseMemory(HipaccImage &img) { HipaccContext &Ctx = HipaccContext::getInstance(); free(img.mem); Ctx.del_image(img); } // Write to memory template<typename T> void hipaccWriteMemory(HipaccImage &img, T *host_mem) { int width = img.width; int height = img.height; int stride = img.stride; if (stride > width) { for (size_t i=0; i<height; ++i) { memcpy(&((T*)img.mem)[i*stride], &host_mem[i*width], sizeof(T)*width); } } else { memcpy(img.mem, host_mem, sizeof(T)*width*height); } } // Read from memory template<typename T> void hipaccReadMemory(T *host_mem, HipaccImage &img) { int width = img.width; int height = img.height; int stride = img.stride; if (stride > width) { for (size_t i=0; i<height; ++i) { memcpy(&host_mem[i*width], &((T*)img.mem)[i*stride], sizeof(T)*width); } } else { memcpy(host_mem, img.mem, sizeof(T)*width*height); } } // Copy from memory to memory void hipaccCopyMemory(HipaccImage &src, HipaccImage &dst) { int height = src.height; int stride = src.stride; memcpy(dst.mem, src.mem, src.pixel_size*stride*height); } // Copy from memory region to memory region void hipaccCopyMemoryRegion(HipaccAccessor src, HipaccAccessor dst) { for (size_t i=0; i<dst.height; ++i) { memcpy(&((uchar*)dst.img.mem)[dst.offset_x*dst.img.pixel_size + (dst.offset_y + i)*dst.img.stride*dst.img.pixel_size], &((uchar*)src.img.mem)[src.offset_x*src.img.pixel_size + (src.offset_y + i)*src.img.stride*src.img.pixel_size], src.width*src.img.pixel_size); } } #endif // __HIPACC_CPU_HPP__
Add missing header (GNU/Linux).
Add missing header (GNU/Linux).
C++
bsd-2-clause
hipacc/hipacc-vivado,hipacc/hipacc,hipacc/hipacc-vivado,hipacc/hipacc,hipacc/hipacc-vivado
5518e335bbaff2fa4ab3ff20a1ca60109a89eccf
libraries/USBDevice/USBSerial/USBSerial.cpp
libraries/USBDevice/USBSerial/USBSerial.cpp
/* Copyright (c) 2010-2011 mbed.org, MIT License * * 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 "stdint.h" #include "USBSerial.h" int USBSerial::_putc(int c) { if (!terminal_connected) return 0; send((uint8_t *)&c, 1); return 1; } int USBSerial::_getc() { uint8_t c = 0; while (buf.isEmpty()); buf.dequeue(&c); return c; } bool USBSerial::writeBlock(uint8_t * buf, uint16_t size) { if(size > MAX_PACKET_SIZE_EPBULK) { return false; } if(!send(buf, size)) { return false; } return true; } bool USBSerial::EP2_OUT_callback() { uint8_t c[65]; uint32_t size = 0; //we read the packet received and put it on the circular buffer readEP(c, &size); for (uint32_t i = 0; i < size; i++) { buf.queue(c[i]); } //call a potential handler rx.call(); // We reactivate the endpoint to receive next characters readStart(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK); return true; } uint8_t USBSerial::available() { return buf.available(); }
/* Copyright (c) 2010-2011 mbed.org, MIT License * * 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 "stdint.h" #include "USBSerial.h" int USBSerial::_putc(int c) { if (!terminal_connected) return 0; send((uint8_t *)&c, 1); return 1; } int USBSerial::_getc() { uint8_t c = 0; while (buf.isEmpty()); buf.dequeue(&c); return c; } bool USBSerial::writeBlock(uint8_t * buf, uint16_t size) { if(size > MAX_PACKET_SIZE_EPBULK) { return false; } if(!send(buf, size)) { return false; } return true; } bool USBSerial::EP2_OUT_callback() { uint8_t c[65]; uint32_t size = 0; //we read the packet received and put it on the circular buffer readEP(c, &size); for (uint32_t i = 0; i < size; i++) { buf.queue(c[i]); } //call a potential handler rx.call(); return true; } uint8_t USBSerial::available() { return buf.available(); }
Fix usb serial RX bug
Fix usb serial RX bug USBCDC::readEP already already called readStart, so we should not call it here. Signed-off-by: Paul Brook <[email protected]>
C++
apache-2.0
wodji/mbed,jpbrucker/mbed,tung7970/mbed-os,HeadsUpDisplayInc/mbed,rosterloh/mbed,alertby/mbed,sg-/mbed-drivers,mnlipp/mbed,tung7970/mbed-os-1,bulislaw/mbed-os,fpiot/mbed-ats,pradeep-gr/mbed-os5-onsemi,c1728p9/mbed-os,sam-geek/mbed,jrjang/mbed,j-greffe/mbed-os,andcor02/mbed-os,ban4jp/mbed,dbestm/mbed,Timmmm/mbed,nabilbendafi/mbed,pi19404/mbed,jrjang/mbed,ban4jp/mbed,masaohamanaka/mbed,nRFMesh/mbed-os,svogl/mbed-os,sam-geek/mbed,GustavWi/mbed,infinnovation/mbed-os,larks/mbed,fvincenzo/mbed-os,struempelix/mbed,Timmmm/mbed,netzimme/mbed-os,FranklyDev/mbed,netzimme/mbed-os,geky/mbed,jferreir/mbed,j-greffe/mbed-os,screamerbg/mbed,larks/mbed,Sweet-Peas/mbed,karsev/mbed-os,nRFMesh/mbed-os,bentwire/mbed,struempelix/mbed,iriark01/mbed-drivers,rgrover/mbed,cvtsi2sd/mbed-os,adamgreen/mbed,getopenmono/mbed,Archcady/mbed-os,mikaleppanen/mbed-os,nabilbendafi/mbed,kjbracey-arm/mbed,logost/mbed,mmorenobarm/mbed-os,mazimkhan/mbed-os,al177/mbed,al177/mbed,maximmbed/mbed,alertby/mbed,JasonHow44/mbed,andcor02/mbed-os,infinnovation/mbed-os,fvincenzo/mbed-os,jeremybrodt/mbed,K4zuki/mbed,mikaleppanen/mbed-os,pedromes/mbed,nabilbendafi/mbed,EmuxEvans/mbed,Tiryoh/mbed,adamgreen/mbed,pi19404/mbed,GustavWi/mbed,kpurusho/mbed,arostm/mbed-os,adamgreen/mbed,infinnovation/mbed-os,monkiineko/mbed-os,bulislaw/mbed-os,larks/mbed,Timmmm/mbed,bulislaw/mbed-os,bikeNomad/mbed,Tiryoh/mbed,arostm/mbed-os,autopulated/mbed,Archcady/mbed-os,CalSol/mbed,jamesadevine/mbed,struempelix/mbed,ARM-software/mbed-beetle,NitinBhaskar/mbed,theotherjimmy/mbed,kpurusho/mbed,Sweet-Peas/mbed,getopenmono/mbed,jeremybrodt/mbed,arostm/mbed-os,pbrook/mbed,adustm/mbed,karsev/mbed-os,HeadsUpDisplayInc/mbed,maximmbed/mbed,Willem23/mbed,hwfwgrp/mbed,mazimkhan/mbed-os,jrjang/mbed,adamgreen/mbed,getopenmono/mbed,GustavWi/mbed,jferreir/mbed,kl-cruz/mbed-os,K4zuki/mbed,YarivCol/mbed-os,j-greffe/mbed-os,nabilbendafi/mbed,fpiot/mbed-ats,Willem23/mbed,betzw/mbed-os,autopulated/mbed,alertby/mbed,c1728p9/mbed-os,infinnovation/mbed-os,RonEld/mbed,mnlipp/mbed,YarivCol/mbed-os,Archcady/mbed-os,masaohamanaka/mbed,mmorenobarm/mbed-os,ban4jp/mbed,karsev/mbed-os,catiedev/mbed-os,autopulated/mbed,monkiineko/mbed-os,radhika-raghavendran/mbed-os5.1-onsemi,brstew/MBED-BUILD,fvincenzo/mbed-os,betzw/mbed-os,CalSol/mbed,HeadsUpDisplayInc/mbed,dbestm/mbed,dbestm/mbed,mmorenobarm/mbed-os,brstew/MBED-BUILD,adamgreen/mbed,pbrook/mbed,jrjang/mbed,EmuxEvans/mbed,screamerbg/mbed,masaohamanaka/mbed,FranklyDev/mbed,andreaslarssonublox/mbed,jpbrucker/mbed,tung7970/mbed-os-1,dbestm/mbed,JasonHow44/mbed,Sweet-Peas/mbed,jferreir/mbed,bcostm/mbed-os,Willem23/mbed,geky/mbed,tung7970/mbed-os-1,pradeep-gr/mbed-os5-onsemi,JasonHow44/mbed,radhika-raghavendran/mbed-os5.1-onsemi,mikaleppanen/mbed-os,K4zuki/mbed,logost/mbed,getopenmono/mbed,brstew/MBED-BUILD,pbrook/mbed,svastm/mbed,YarivCol/mbed-os,dbestm/mbed,fahhem/mbed-os,screamerbg/mbed,infinnovation/mbed-os,jamesadevine/mbed,rosterloh/mbed,kjbracey-arm/mbed,rosterloh/mbed,pradeep-gr/mbed-os5-onsemi,mikaleppanen/mbed-os,fanghuaqi/mbed,mikaleppanen/mbed-os,bcostm/mbed-os,xcrespo/mbed,larks/mbed,ban4jp/mbed,xcrespo/mbed,autopulated/mbed,FranklyDev/mbed,ryankurte/mbed-os,HeadsUpDisplayInc/mbed,kl-cruz/mbed-os,wodji/mbed,radhika-raghavendran/mbed-os5.1-onsemi,bremoran/mbed-drivers,Marcomissyou/mbed,fanghuaqi/mbed,mazimkhan/mbed-os,mazimkhan/mbed-os,kpurusho/mbed,tung7970/mbed-os-1,mnlipp/mbed,kpurusho/mbed,svogl/mbed-os,screamerbg/mbed,NXPmicro/mbed,struempelix/mbed,svogl/mbed-os,c1728p9/mbed-os,fpiot/mbed-ats,pedromes/mbed,pedromes/mbed,Shengliang/mbed,cvtsi2sd/mbed-os,autopulated/mbed,naves-thiago/mbed-midi,Sweet-Peas/mbed,nRFMesh/mbed-os,al177/mbed,fahhem/mbed-os,pi19404/mbed,arostm/mbed-os,ban4jp/mbed,NXPmicro/mbed,Tiryoh/mbed,theotherjimmy/mbed,NitinBhaskar/mbed,radhika-raghavendran/mbed-os5.1-onsemi,j-greffe/mbed-os,Marcomissyou/mbed,jrjang/mbed,logost/mbed,jeremybrodt/mbed,andreaslarssonublox/mbed,rgrover/mbed,K4zuki/mbed,NXPmicro/mbed,larks/mbed,ryankurte/mbed-os,betzw/mbed-os,catiedev/mbed-os,pedromes/mbed,RonEld/mbed,fahhem/mbed-os,xcrespo/mbed,theotherjimmy/mbed,pi19404/mbed,bcostm/mbed-os,andreaslarssonublox/mbed,EmuxEvans/mbed,nRFMesh/mbed-os,sam-geek/mbed,sam-geek/mbed,hwfwgrp/mbed,adustm/mbed,HeadsUpDisplayInc/mbed,rosterloh/mbed,fvincenzo/mbed-os,fanghuaqi/mbed,larks/mbed,jamesadevine/mbed,theotherjimmy/mbed,CalSol/mbed,tung7970/mbed-os,fanghuaqi/mbed,karsev/mbed-os,rgrover/mbed,wodji/mbed,masaohamanaka/mbed,kjbracey-arm/mbed,Marcomissyou/mbed,al177/mbed,screamerbg/mbed,jrjang/mbed,arostm/mbed-os,Tiryoh/mbed,mnlipp/mbed,NXPmicro/mbed,logost/mbed,cvtsi2sd/mbed-os,geky/mbed,bcostm/mbed-os,Shengliang/mbed,mnlipp/mbed,monkiineko/mbed-os,pradeep-gr/mbed-os5-onsemi,arostm/mbed-os,radhika-raghavendran/mbed-os5.1-onsemi,0xc0170/mbed-drivers,brstew/MBED-BUILD,ban4jp/mbed,catiedev/mbed-os,xcrespo/mbed,mbedmicro/mbed,FranklyDev/mbed,DanKupiniak/mbed,tung7970/mbed-os,DanKupiniak/mbed,maximmbed/mbed,YarivCol/mbed-os,getopenmono/mbed,kl-cruz/mbed-os,netzimme/mbed-os,CalSol/mbed,cvtsi2sd/mbed-os,al177/mbed,getopenmono/mbed,NitinBhaskar/mbed,Shengliang/mbed,YarivCol/mbed-os,adustm/mbed,sg-/mbed-drivers,bentwire/mbed,mikaleppanen/mbed-os,mmorenobarm/mbed-os,hwfwgrp/mbed,adustm/mbed,jferreir/mbed,devanlai/mbed,jamesadevine/mbed,pradeep-gr/mbed-os5-onsemi,geky/mbed,mbedmicro/mbed,screamerbg/mbed,bcostm/mbed-os,logost/mbed,bikeNomad/mbed,autopulated/mbed,kpurusho/mbed,Archcady/mbed-os,nRFMesh/mbed-os,maximmbed/mbed,jpbrucker/mbed,betzw/mbed-os,andreaslarssonublox/mbed,rosterloh/mbed,EmuxEvans/mbed,naves-thiago/mbed-midi,Shengliang/mbed,tung7970/mbed-os-1,RonEld/mbed,jferreir/mbed,Marcomissyou/mbed,rgrover/mbed,bikeNomad/mbed,struempelix/mbed,Archcady/mbed-os,netzimme/mbed-os,bulislaw/mbed-os,Shengliang/mbed,HeadsUpDisplayInc/mbed,naves-thiago/mbed-midi,nRFMesh/mbed-os,alertby/mbed,svastm/mbed,adamgreen/mbed,naves-thiago/mbed-midi,karsev/mbed-os,jferreir/mbed,nvlsianpu/mbed,tung7970/mbed-os,bentwire/mbed,j-greffe/mbed-os,betzw/mbed-os,pbrook/mbed,ARM-software/mbed-beetle,fpiot/mbed-ats,GustavWi/mbed,NitinBhaskar/mbed,NXPmicro/mbed,svastm/mbed,netzimme/mbed-os,fahhem/mbed-os,masaohamanaka/mbed,kjbracey-arm/mbed,nvlsianpu/mbed,catiedev/mbed-os,FranklyDev/mbed,nvlsianpu/mbed,mnlipp/mbed,monkiineko/mbed-os,logost/mbed,svastm/mbed,Tiryoh/mbed,mazimkhan/mbed-os,j-greffe/mbed-os,0xc0170/mbed-drivers,ryankurte/mbed-os,xcrespo/mbed,nvlsianpu/mbed,mazimkhan/mbed-os,Marcomissyou/mbed,bulislaw/mbed-os,andreaslarssonublox/mbed,theotherjimmy/mbed,K4zuki/mbed,Timmmm/mbed,pedromes/mbed,struempelix/mbed,cvtsi2sd/mbed-os,DanKupiniak/mbed,YarivCol/mbed-os,alertby/mbed,jamesadevine/mbed,ryankurte/mbed-os,CalSol/mbed,Sweet-Peas/mbed,jpbrucker/mbed,fvincenzo/mbed-os,kl-cruz/mbed-os,pbrook/mbed,andcor02/mbed-os,radhika-raghavendran/mbed-os5.1-onsemi,sam-geek/mbed,RonEld/mbed,fpiot/mbed-ats,NXPmicro/mbed,NitinBhaskar/mbed,RonEld/mbed,svogl/mbed-os,wodji/mbed,EmuxEvans/mbed,ARM-software/mbed-beetle,JasonHow44/mbed,al177/mbed,bentwire/mbed,Timmmm/mbed,fpiot/mbed-ats,mbedmicro/mbed,pi19404/mbed,andcor02/mbed-os,catiedev/mbed-os,nvlsianpu/mbed,Tiryoh/mbed,hwfwgrp/mbed,infinnovation/mbed-os,kpurusho/mbed,monkiineko/mbed-os,hwfwgrp/mbed,adustm/mbed,kl-cruz/mbed-os,fahhem/mbed-os,naves-thiago/mbed-midi,DanKupiniak/mbed,svogl/mbed-os,fahhem/mbed-os,mmorenobarm/mbed-os,Willem23/mbed,JasonHow44/mbed,svogl/mbed-os,theotherjimmy/mbed,cvtsi2sd/mbed-os,c1728p9/mbed-os,andcor02/mbed-os,ryankurte/mbed-os,catiedev/mbed-os,nabilbendafi/mbed,devanlai/mbed,dbestm/mbed,Willem23/mbed,bikeNomad/mbed,Archcady/mbed-os,bikeNomad/mbed,masaohamanaka/mbed,xcrespo/mbed,GustavWi/mbed,jpbrucker/mbed,CalSol/mbed,devanlai/mbed,devanlai/mbed,fanghuaqi/mbed,mmorenobarm/mbed-os,maximmbed/mbed,K4zuki/mbed,adustm/mbed,Timmmm/mbed,pedromes/mbed,rosterloh/mbed,jpbrucker/mbed,netzimme/mbed-os,karsev/mbed-os,naves-thiago/mbed-midi,iriark01/mbed-drivers,betzw/mbed-os,Marcomissyou/mbed,andcor02/mbed-os,geky/mbed,JasonHow44/mbed,maximmbed/mbed,bentwire/mbed,ARM-software/mbed-beetle,tung7970/mbed-os,nabilbendafi/mbed,RonEld/mbed,pradeep-gr/mbed-os5-onsemi,Sweet-Peas/mbed,bentwire/mbed,brstew/MBED-BUILD,EmuxEvans/mbed,pi19404/mbed,monkiineko/mbed-os,bulislaw/mbed-os,hwfwgrp/mbed,svastm/mbed,nvlsianpu/mbed,bcostm/mbed-os,devanlai/mbed,bremoran/mbed-drivers,rgrover/mbed,mbedmicro/mbed,wodji/mbed,alertby/mbed,kl-cruz/mbed-os,brstew/MBED-BUILD,jeremybrodt/mbed,c1728p9/mbed-os,mbedmicro/mbed,wodji/mbed,Shengliang/mbed,pbrook/mbed,c1728p9/mbed-os,jeremybrodt/mbed,jamesadevine/mbed,devanlai/mbed,ryankurte/mbed-os
5a000baa138b5fae622be4be79afe694fa87d35a
src/AndroidClient.cpp
src/AndroidClient.cpp
#include <AndroidClient.h> #include <android/log.h> #include <vector> #include <memory> using namespace std; static jbyteArray convertToByteArray(JNIEnv * env, const std::string & s) { const jbyte * pNativeMessage = reinterpret_cast<const jbyte*>(s.c_str()); jbyteArray bytes = env->NewByteArray(s.size()); env->SetByteArrayRegion(bytes, 0, s.size(), pNativeMessage); return bytes; } static void logException(JNIEnv * env, const char * error) { jthrowable e = env->ExceptionOccurred(); env->ExceptionClear(); jclass clazz = env->GetObjectClass(e); jmethodID getMessage = env->GetMethodID(clazz, "getMessage", "()Ljava/lang/String;"); jstring message = (jstring)env->CallObjectMethod(e, getMessage); string m; if (message != NULL) { const char *mstr = env->GetStringUTFChars(message, NULL); m = mstr; env->ReleaseStringUTFChars(message, mstr); } env->DeleteLocalRef(message); env->DeleteLocalRef(clazz); env->DeleteLocalRef(e); __android_log_print(ANDROID_LOG_VERBOSE, "AndroidClient", "%s: %s", error, m.c_str()); } class AndroidClientCache { public: AndroidClientCache(JNIEnv * myEnv) { myEnv->GetJavaVM(&javaVM); cookieManagerClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("android/webkit/CookieManager")); httpClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/net/HttpURLConnection")); urlClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/net/URL")); urlConnectionClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/net/URLConnection")); inputStreamClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/io/InputStream")); frameworkClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("com/sometrik/framework/FrameWork")); outputStreamClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/io/OutputStream")); setReadTimeoutMethod = myEnv->GetMethodID(urlConnectionClass, "setReadTimeout", "(I)V"); getHeaderMethod = myEnv->GetMethodID(httpClass, "getHeaderField", "(Ljava/lang/String;)Ljava/lang/String;"); getHeaderMethodInt = myEnv->GetMethodID(httpClass, "getHeaderField", "(I)Ljava/lang/String;"); getHeaderKeyMethod = myEnv->GetMethodID(httpClass, "getHeaderFieldKey", "(I)Ljava/lang/String;"); readMethod = myEnv->GetMethodID(inputStreamClass, "read", "([B)I"); urlConstructor = myEnv->GetMethodID(urlClass, "<init>", "(Ljava/lang/String;)V"); openConnectionMethod = myEnv->GetMethodID(urlClass, "openConnection", "()Ljava/net/URLConnection;"); setUseCachesMethod = myEnv->GetMethodID(urlConnectionClass, "setUseCaches", "(Z)V"); disconnectConnectionMethod = myEnv->GetMethodID(httpClass, "disconnect", "()V"); getOutputStreamMethod = myEnv->GetMethodID(urlConnectionClass, "getOutputStream", "()Ljava/io/OutputStream;"); outputStreamWriteMethod = myEnv->GetMethodID(outputStreamClass, "write", "([B)V"); setChunkedStreamingModeMethod = myEnv->GetMethodID(httpClass, "setChunkedStreamingMode", "(I)V"); setFixedLengthStreamingModeMethod = myEnv->GetMethodID(httpClass, "setFixedLengthStreamingMode", "(I)V"); setRequestProperty = myEnv->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V"); setRequestMethod = myEnv->GetMethodID(httpClass, "setRequestMethod", "(Ljava/lang/String;)V"); setFollowMethod = myEnv->GetMethodID(httpClass, "setInstanceFollowRedirects", "(Z)V"); setDoInputMethod = myEnv->GetMethodID(httpClass, "setDoInput", "(Z)V"); setDoOutputMethod = myEnv->GetMethodID(httpClass, "setDoOutput", "(Z)V"); getResponseCodeMethod = myEnv->GetMethodID(httpClass, "getResponseCode", "()I"); getResponseMessageMethod = myEnv->GetMethodID(httpClass, "getResponseMessage", "()Ljava/lang/String;"); setRequestPropertyMethod = myEnv->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V"); clearCookiesMethod = myEnv->GetMethodID(cookieManagerClass, "removeAllCookie", "()V"); getInputStreamMethod = myEnv->GetMethodID(httpClass, "getInputStream", "()Ljava/io/InputStream;"); getErrorStreamMethod = myEnv->GetMethodID(httpClass, "getErrorStream", "()Ljava/io/InputStream;"); // handleThrowableMethod = myEnv->GetStaticMethodID(frameworkClass, "handleNativeException", "(Ljava/lang/Throwable;)V"); } ~AndroidClientCache() { JNIEnv * env = getEnv(); env->DeleteGlobalRef(cookieManagerClass); env->DeleteGlobalRef(httpClass); env->DeleteGlobalRef(urlClass); env->DeleteGlobalRef(inputStreamClass); env->DeleteGlobalRef(frameworkClass); env->DeleteGlobalRef(outputStreamClass); } JNIEnv * getEnv() { JNIEnv * env = 0; javaVM->GetEnv((void**)&env, JNI_VERSION_1_6); return env; } jclass cookieManagerClass; jmethodID clearCookiesMethod; jclass httpClass; jclass urlClass; jclass urlConnectionClass; jclass bufferedReaderClass; jclass inputStreamReaderClass; jclass inputStreamClass; jclass frameworkClass; jclass outputStreamClass; jmethodID urlConstructor; jmethodID openConnectionMethod; jmethodID getOutputStreamMethod; jmethodID outputStreamWriteMethod; jmethodID setReadTimeoutMethod; jmethodID setChunkedStreamingModeMethod; jmethodID setFixedLengthStreamingModeMethod; jmethodID setRequestProperty; jmethodID setRequestMethod; jmethodID setDoInputMethod; jmethodID setDoOutputMethod; jmethodID getResponseCodeMethod; jmethodID getResponseMessageMethod; jmethodID setRequestPropertyMethod; jmethodID outputStreamConstructor; jmethodID factoryDecodeMethod; jmethodID getInputStreamMethod; jmethodID getErrorStreamMethod; jmethodID bufferedReaderConstructor; jmethodID inputStreamReaderConstructor; jmethodID readLineMethod; jmethodID readerCloseMethod; jmethodID readMethod; jmethodID inputStreamCloseMethod; jmethodID setFollowMethod; jmethodID getHeaderMethod; jmethodID getHeaderMethodInt; jmethodID getHeaderKeyMethod; // jmethodID handleThrowableMethod; jmethodID setUseCachesMethod; jmethodID disconnectConnectionMethod; private: JavaVM * javaVM; JNIEnv * myEnv; }; class AndroidClient : public HTTPClient { public: AndroidClient(const std::shared_ptr<AndroidClientCache> & _cache, const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) : HTTPClient(_user_agent, _enable_cookies, _enable_keepalive), cache(_cache) { } void request(const HTTPRequest & req, const Authorization & auth, HTTPClientInterface & callback) { JNIEnv * env = cache->getEnv(); // __android_log_print(ANDROID_LOG_INFO, "AndroidClient", "Host = %s, ua = %s", req.getURI().c_str(), user_agent.c_str()); jstring juri = env->NewStringUTF(req.getURI().c_str()); jobject url = env->NewObject(cache->urlClass, cache->urlConstructor, juri); env->DeleteLocalRef(juri); jobject connection = env->CallObjectMethod(url, cache->openConnectionMethod); env->CallVoidMethod(connection, cache->setUseCachesMethod, JNI_FALSE); env->CallVoidMethod(connection, cache->setReadTimeoutMethod, req.getReadTimeout() * 1000); // env->CallVoidMethod(connection, cache->setConnectTimeoutMethod, req.getConnectTimeout() * 1000); env->DeleteLocalRef(url); //Authorization example // env->CallVoidMethod(connection, setRequestPropertyMethod, env->NewStringUTF("Authorization"), env->NewStringUTF("myUsername")); std::string auth_header = auth.createHeader(); env->CallVoidMethod(connection, cache->setFollowMethod, req.getFollowLocation() ? JNI_TRUE : JNI_FALSE); // Setting headers for request std::map<std::string, std::string> combined_headers; for (auto & hd : default_headers) { combined_headers[hd.first] = hd.second; } combined_headers["User-Agent"] = user_agent; if (req.getType() == HTTPRequest::POST && !req.getContentType().empty()) { combined_headers["Content-Type"] = req.getContentType(); } for (auto & hd : req.getHeaders()) { combined_headers[hd.first] = hd.second; } if (!auth_header.empty()) { // __android_log_print(ANDROID_LOG_INFO, "AndroidClient", "Auth: %s = %s", auth.getHeaderName(), auth_header.c_str()); combined_headers[auth.getHeaderName()] = auth_header; } for (auto & hd : combined_headers) { jstring firstHeader = env->NewStringUTF(hd.first.c_str()); jstring secondHeader = env->NewStringUTF(hd.second.c_str()); env->CallVoidMethod(connection, cache->setRequestPropertyMethod, firstHeader, secondHeader); env->DeleteLocalRef(firstHeader); env->DeleteLocalRef(secondHeader); } env->CallVoidMethod(connection, cache->setDoOutputMethod, req.getType() == HTTPRequest::POST); jstring jTypeString = env->NewStringUTF(req.getTypeString()); env->CallVoidMethod(connection, cache->setRequestMethod, jTypeString); env->DeleteLocalRef(jTypeString); bool connection_failed = false; if (req.getType() == HTTPRequest::POST) { env->CallVoidMethod(connection, cache->setFixedLengthStreamingModeMethod, req.getContent().size()); jobject outputStream = env->CallObjectMethod(connection, cache->getOutputStreamMethod); if (env->ExceptionCheck()) { logException(env, "Failed to open output stream"); connection_failed = true; } for (int i = 0; i < req.getContent().size() && !connection_failed; i += 4096) { auto a = convertToByteArray(env, req.getContent().substr(i, 4096)); env->CallVoidMethod(outputStream, cache->outputStreamWriteMethod, a); if (env->ExceptionCheck()) { logException(env, "Failed to write post data"); connection_failed = true; } env->DeleteLocalRef(a); } } int responseCode = 0; if (!connection_failed) { responseCode = env->CallIntMethod(connection, cache->getResponseCodeMethod); if (env->ExceptionCheck()) { logException(env, "Failed to get response code"); connection_failed = true; } } if (connection_failed) { callback.handleResultCode(0); } else { // __android_log_print(ANDROID_LOG_INFO, "AndroidClient", "http request responsecode = %i", responseCode); callback.handleResultCode(responseCode); jobject input = env->CallObjectMethod(connection, cache->getInputStreamMethod); if (env->ExceptionCheck()) { logException(env, "Failed to open input stream"); input = env->CallObjectMethod(connection, cache->getErrorStreamMethod); if (env->ExceptionCheck()) { logException(env, "Failed to open error stream"); input = 0; } } if (input != 0) { // Gather headers and values for (int i = 0;; i++) { jstring jheaderKey = (jstring) env->CallObjectMethod(connection, cache->getHeaderKeyMethod, i); if (jheaderKey != NULL) { jstring jheader = (jstring) env->CallObjectMethod(connection, cache->getHeaderMethodInt, i); if (jheader != NULL) { const char * headerKey = env->GetStringUTFChars(jheaderKey, 0); const char * header = env->GetStringUTFChars(jheader, 0); callback.handleHeader(headerKey, header); if (strcasecmp(headerKey, "Location") == 0) { callback.handleRedirectUrl(header); } env->ReleaseStringUTFChars(jheaderKey, headerKey); env->ReleaseStringUTFChars(jheader, header); } env->DeleteLocalRef(jheader); } env->DeleteLocalRef(jheaderKey); } // Gather content jbyteArray array = env->NewByteArray(4096); int g = 0; while ((g = env->CallIntMethod(input, cache->readMethod, array)) != -1) { if (env->ExceptionCheck()) { logException(env, "Failed to read stream"); break; } jbyte* content_array = env->GetByteArrayElements(array, NULL); bool r = callback.handleChunk(g, (char*) content_array); env->ReleaseByteArrayElements(array, content_array, JNI_ABORT); if (!r || !callback.onIdle()) { break; } } env->DeleteLocalRef(array); env->DeleteLocalRef(input); } env->CallVoidMethod(connection, cache->disconnectConnectionMethod); } callback.handleDisconnect(); env->DeleteLocalRef(connection); } void clearCookies() { // JNIEnv * env = cache->getJNIEnv(); // env->CallVoidMethod(cache->cookieManagerClass, cache->clearCookiesMethod); } private: std::shared_ptr<AndroidClientCache> cache; }; std::shared_ptr<AndroidClientCache> AndroidClientFactory::cache; void AndroidClientFactory::initialize(JNIEnv * env) { cache = make_shared<AndroidClientCache>(env); } std::unique_ptr<HTTPClient> AndroidClientFactory::createClient2(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) { return std::unique_ptr<AndroidClient>(new AndroidClient(cache, _user_agent, _enable_cookies, _enable_keepalive)); }
#include <AndroidClient.h> #include <android/log.h> #include <vector> #include <memory> using namespace std; static jbyteArray convertToByteArray(JNIEnv * env, const std::string & s) { const jbyte * pNativeMessage = reinterpret_cast<const jbyte*>(s.c_str()); jbyteArray bytes = env->NewByteArray(s.size()); env->SetByteArrayRegion(bytes, 0, s.size(), pNativeMessage); return bytes; } static void logException(JNIEnv * env, const char * error) { jthrowable e = env->ExceptionOccurred(); env->ExceptionClear(); jclass clazz = env->GetObjectClass(e); jmethodID getMessage = env->GetMethodID(clazz, "getMessage", "()Ljava/lang/String;"); jstring message = (jstring)env->CallObjectMethod(e, getMessage); string m; if (message != NULL) { const char *mstr = env->GetStringUTFChars(message, NULL); m = mstr; env->ReleaseStringUTFChars(message, mstr); } env->DeleteLocalRef(message); env->DeleteLocalRef(clazz); env->DeleteLocalRef(e); __android_log_print(ANDROID_LOG_INFO, "AndroidClient", "%s: %s", error, m.c_str()); } class AndroidClientCache { public: AndroidClientCache(JNIEnv * myEnv) { myEnv->GetJavaVM(&javaVM); cookieManagerClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("android/webkit/CookieManager")); httpClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/net/HttpURLConnection")); urlClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/net/URL")); urlConnectionClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/net/URLConnection")); inputStreamClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/io/InputStream")); frameworkClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("com/sometrik/framework/FrameWork")); outputStreamClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/io/OutputStream")); setReadTimeoutMethod = myEnv->GetMethodID(urlConnectionClass, "setReadTimeout", "(I)V"); getHeaderMethod = myEnv->GetMethodID(httpClass, "getHeaderField", "(Ljava/lang/String;)Ljava/lang/String;"); getHeaderMethodInt = myEnv->GetMethodID(httpClass, "getHeaderField", "(I)Ljava/lang/String;"); getHeaderKeyMethod = myEnv->GetMethodID(httpClass, "getHeaderFieldKey", "(I)Ljava/lang/String;"); readMethod = myEnv->GetMethodID(inputStreamClass, "read", "([B)I"); urlConstructor = myEnv->GetMethodID(urlClass, "<init>", "(Ljava/lang/String;)V"); openConnectionMethod = myEnv->GetMethodID(urlClass, "openConnection", "()Ljava/net/URLConnection;"); setUseCachesMethod = myEnv->GetMethodID(urlConnectionClass, "setUseCaches", "(Z)V"); disconnectConnectionMethod = myEnv->GetMethodID(httpClass, "disconnect", "()V"); getOutputStreamMethod = myEnv->GetMethodID(urlConnectionClass, "getOutputStream", "()Ljava/io/OutputStream;"); outputStreamWriteMethod = myEnv->GetMethodID(outputStreamClass, "write", "([B)V"); setChunkedStreamingModeMethod = myEnv->GetMethodID(httpClass, "setChunkedStreamingMode", "(I)V"); setFixedLengthStreamingModeMethod = myEnv->GetMethodID(httpClass, "setFixedLengthStreamingMode", "(I)V"); setRequestProperty = myEnv->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V"); setRequestMethod = myEnv->GetMethodID(httpClass, "setRequestMethod", "(Ljava/lang/String;)V"); setFollowMethod = myEnv->GetMethodID(httpClass, "setInstanceFollowRedirects", "(Z)V"); setDoInputMethod = myEnv->GetMethodID(httpClass, "setDoInput", "(Z)V"); setDoOutputMethod = myEnv->GetMethodID(httpClass, "setDoOutput", "(Z)V"); getResponseCodeMethod = myEnv->GetMethodID(httpClass, "getResponseCode", "()I"); getResponseMessageMethod = myEnv->GetMethodID(httpClass, "getResponseMessage", "()Ljava/lang/String;"); setRequestPropertyMethod = myEnv->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V"); clearCookiesMethod = myEnv->GetMethodID(cookieManagerClass, "removeAllCookie", "()V"); getInputStreamMethod = myEnv->GetMethodID(httpClass, "getInputStream", "()Ljava/io/InputStream;"); getErrorStreamMethod = myEnv->GetMethodID(httpClass, "getErrorStream", "()Ljava/io/InputStream;"); // handleThrowableMethod = myEnv->GetStaticMethodID(frameworkClass, "handleNativeException", "(Ljava/lang/Throwable;)V"); } ~AndroidClientCache() { JNIEnv * env = getEnv(); env->DeleteGlobalRef(cookieManagerClass); env->DeleteGlobalRef(httpClass); env->DeleteGlobalRef(urlClass); env->DeleteGlobalRef(inputStreamClass); env->DeleteGlobalRef(frameworkClass); env->DeleteGlobalRef(outputStreamClass); } JNIEnv * getEnv() { JNIEnv * env = 0; javaVM->GetEnv((void**)&env, JNI_VERSION_1_6); return env; } jclass cookieManagerClass; jmethodID clearCookiesMethod; jclass httpClass; jclass urlClass; jclass urlConnectionClass; jclass bufferedReaderClass; jclass inputStreamReaderClass; jclass inputStreamClass; jclass frameworkClass; jclass outputStreamClass; jmethodID urlConstructor; jmethodID openConnectionMethod; jmethodID getOutputStreamMethod; jmethodID outputStreamWriteMethod; jmethodID setReadTimeoutMethod; jmethodID setChunkedStreamingModeMethod; jmethodID setFixedLengthStreamingModeMethod; jmethodID setRequestProperty; jmethodID setRequestMethod; jmethodID setDoInputMethod; jmethodID setDoOutputMethod; jmethodID getResponseCodeMethod; jmethodID getResponseMessageMethod; jmethodID setRequestPropertyMethod; jmethodID outputStreamConstructor; jmethodID factoryDecodeMethod; jmethodID getInputStreamMethod; jmethodID getErrorStreamMethod; jmethodID bufferedReaderConstructor; jmethodID inputStreamReaderConstructor; jmethodID readLineMethod; jmethodID readerCloseMethod; jmethodID readMethod; jmethodID inputStreamCloseMethod; jmethodID setFollowMethod; jmethodID getHeaderMethod; jmethodID getHeaderMethodInt; jmethodID getHeaderKeyMethod; // jmethodID handleThrowableMethod; jmethodID setUseCachesMethod; jmethodID disconnectConnectionMethod; private: JavaVM * javaVM; JNIEnv * myEnv; }; class AndroidClient : public HTTPClient { public: AndroidClient(const std::shared_ptr<AndroidClientCache> & _cache, const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) : HTTPClient(_user_agent, _enable_cookies, _enable_keepalive), cache(_cache) { } void request(const HTTPRequest & req, const Authorization & auth, HTTPClientInterface & callback) { JNIEnv * env = cache->getEnv(); __android_log_print(ANDROID_LOG_INFO, "AndroidClient", "Host = %s, ua = %s", req.getURI().c_str(), user_agent.c_str()); jstring juri = env->NewStringUTF(req.getURI().c_str()); jobject url = env->NewObject(cache->urlClass, cache->urlConstructor, juri); env->DeleteLocalRef(juri); jobject connection = env->CallObjectMethod(url, cache->openConnectionMethod); env->CallVoidMethod(connection, cache->setUseCachesMethod, JNI_FALSE); env->CallVoidMethod(connection, cache->setReadTimeoutMethod, req.getReadTimeout() * 1000); // env->CallVoidMethod(connection, cache->setConnectTimeoutMethod, req.getConnectTimeout() * 1000); env->DeleteLocalRef(url); //Authorization example // env->CallVoidMethod(connection, setRequestPropertyMethod, env->NewStringUTF("Authorization"), env->NewStringUTF("myUsername")); std::string auth_header = auth.createHeader(); env->CallVoidMethod(connection, cache->setFollowMethod, req.getFollowLocation() ? JNI_TRUE : JNI_FALSE); // Setting headers for request std::map<std::string, std::string> combined_headers; for (auto & hd : default_headers) { combined_headers[hd.first] = hd.second; } combined_headers["User-Agent"] = user_agent; if (req.getType() == HTTPRequest::POST && !req.getContentType().empty()) { combined_headers["Content-Type"] = req.getContentType(); } for (auto & hd : req.getHeaders()) { combined_headers[hd.first] = hd.second; } if (!auth_header.empty()) { // __android_log_print(ANDROID_LOG_INFO, "AndroidClient", "Auth: %s = %s", auth.getHeaderName(), auth_header.c_str()); combined_headers[auth.getHeaderName()] = auth_header; } for (auto & hd : combined_headers) { jstring firstHeader = env->NewStringUTF(hd.first.c_str()); jstring secondHeader = env->NewStringUTF(hd.second.c_str()); env->CallVoidMethod(connection, cache->setRequestPropertyMethod, firstHeader, secondHeader); env->DeleteLocalRef(firstHeader); env->DeleteLocalRef(secondHeader); } env->CallVoidMethod(connection, cache->setDoOutputMethod, req.getType() == HTTPRequest::POST); jstring jTypeString = env->NewStringUTF(req.getTypeString()); env->CallVoidMethod(connection, cache->setRequestMethod, jTypeString); env->DeleteLocalRef(jTypeString); bool connection_failed = false; if (req.getType() == HTTPRequest::POST) { env->CallVoidMethod(connection, cache->setFixedLengthStreamingModeMethod, req.getContent().size()); jobject outputStream = env->CallObjectMethod(connection, cache->getOutputStreamMethod); if (env->ExceptionCheck()) { logException(env, "Failed to open output stream"); connection_failed = true; } for (int i = 0; i < req.getContent().size() && !connection_failed; i += 4096) { auto a = convertToByteArray(env, req.getContent().substr(i, 4096)); env->CallVoidMethod(outputStream, cache->outputStreamWriteMethod, a); if (env->ExceptionCheck()) { logException(env, "Failed to write post data"); connection_failed = true; } env->DeleteLocalRef(a); } } int responseCode = 0; if (!connection_failed) { responseCode = env->CallIntMethod(connection, cache->getResponseCodeMethod); if (env->ExceptionCheck()) { logException(env, "Failed to get response code"); connection_failed = true; } } if (connection_failed) { callback.handleResultCode(0); } else { // __android_log_print(ANDROID_LOG_INFO, "AndroidClient", "http request responsecode = %i", responseCode); callback.handleResultCode(responseCode); jobject input = env->CallObjectMethod(connection, cache->getInputStreamMethod); if (env->ExceptionCheck()) { logException(env, "Failed to open input stream"); input = env->CallObjectMethod(connection, cache->getErrorStreamMethod); if (env->ExceptionCheck()) { logException(env, "Failed to open error stream"); input = 0; } } if (input != 0) { // Gather headers and values for (int i = 0;; i++) { jstring jheaderKey = (jstring) env->CallObjectMethod(connection, cache->getHeaderKeyMethod, i); if (jheaderKey == NULL) { break; } else { jstring jheader = (jstring) env->CallObjectMethod(connection, cache->getHeaderMethodInt, i); if (jheader != NULL) { const char * headerKey = env->GetStringUTFChars(jheaderKey, 0); const char * header = env->GetStringUTFChars(jheader, 0); callback.handleHeader(headerKey, header); if (strcasecmp(headerKey, "Location") == 0) { callback.handleRedirectUrl(header); } env->ReleaseStringUTFChars(jheaderKey, headerKey); env->ReleaseStringUTFChars(jheader, header); env->DeleteLocalRef(jheader); } env->DeleteLocalRef(jheaderKey); } } // Gather content jbyteArray array = env->NewByteArray(4096); int g = 0; while ((g = env->CallIntMethod(input, cache->readMethod, array)) != -1) { if (env->ExceptionCheck()) { logException(env, "Failed to read stream"); break; } jbyte* content_array = env->GetByteArrayElements(array, NULL); bool r = callback.handleChunk(g, (char*) content_array); env->ReleaseByteArrayElements(array, content_array, JNI_ABORT); if (!r || !callback.onIdle()) { break; } } env->DeleteLocalRef(array); env->DeleteLocalRef(input); } env->CallVoidMethod(connection, cache->disconnectConnectionMethod); } callback.handleDisconnect(); env->DeleteLocalRef(connection); } void clearCookies() { // JNIEnv * env = cache->getJNIEnv(); // env->CallVoidMethod(cache->cookieManagerClass, cache->clearCookiesMethod); } private: std::shared_ptr<AndroidClientCache> cache; }; std::shared_ptr<AndroidClientCache> AndroidClientFactory::cache; void AndroidClientFactory::initialize(JNIEnv * env) { cache = make_shared<AndroidClientCache>(env); } std::unique_ptr<HTTPClient> AndroidClientFactory::createClient2(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) { return std::unique_ptr<AndroidClient>(new AndroidClient(cache, _user_agent, _enable_cookies, _enable_keepalive)); }
enable logging, fix infinite loop
enable logging, fix infinite loop
C++
mit
Sometrik/httpclient,Sometrik/httpclient
0bad6fdb1f64140e81d5bd61d40a8c037fe65e41
src/DactTreeScene.cpp
src/DactTreeScene.cpp
#include <algorithm> #include <QDebug> #include <QFontMetrics> #include <QGraphicsSceneHoverEvent> #include <QGraphicsView> #include <QPainter> #include <QSettings> extern "C" { #include <libxml/parser.h> #include <libxml/tree.h> } #include "DactTreeScene.hh" #include "Edge.hh" #include "SecEdge.hh" #include "TreeNode.hh" #include "PopupItem.hh" #include "XMLDeleters.hh" DactTreeScene::DactTreeScene(QObject *parent) : QGraphicsScene(parent), d_nodes() { connect(this, SIGNAL(selectionChanged()), this, SLOT(emitSelectionChange())); } DactTreeScene::~DactTreeScene() { disconnect(this, SIGNAL(selectionChanged())); if (rootNode()) freeNodes(); } void DactTreeScene::checkElementAndAssign(xmlNodePtr node, char const *nodeName, xmlNodePtr *variable) { if (node->type == XML_ELEMENT_NODE && nodeNameIs(node, nodeName)) { { if (*variable == 0) *variable = node; else qWarning() << "More than one '" << nodeName << "', only using first!"; } } } void DactTreeScene::emitSelectionChange() { emit selectionChanged(dynamic_cast<TreeNode*>(focusItem())); } void DactTreeScene::parseTree(QString const &xml) { // If there was a previous parse, clean up first. if (rootNode()) { removeItem(rootNode()); foreach (QGraphicsItem *edge, d_edges) { removeItem(edge); } freeNodes(); } parseXML(xml); // If parsing was successful enough to create a root node, // add it to the scene if (rootNode()) { rootNode()->layout(); foreach (QGraphicsItem *edge, d_edges) { addItem(edge); } addItem(rootNode()); } else { qWarning() << "No root node was found"; } } void DactTreeScene::parseXML(QString const &xml) { QByteArray xmlData(xml.toUtf8()); QScopedPointer<xmlDoc, XmlDocDeleter> doc( xmlReadMemory(xmlData.constData(), xmlData.size(), NULL, NULL, 0)); if (doc == 0) { qWarning() << "Could not parse tree!"; return; } xmlNode *treeRoot = xmlDocGetRootElement(doc.data()); if (treeRoot == NULL) { qWarning() << "Tree does not have a root?"; return; } xmlNodePtr treeRootNode = 0; xmlNodePtr secEdges = 0; for (xmlNodePtr child = treeRoot->children; child; child = child->next) { checkElementAndAssign(child, "node", &treeRootNode); checkElementAndAssign(child, "secedges", &secEdges); } if (treeRootNode == 0) { qWarning() << "Tree does not have a root?"; return; } processNode(treeRootNode); if (secEdges) processSecondaryEdges(secEdges); } TreeNode *DactTreeScene::processNode(xmlNodePtr xmlNode) { TreeNode *node = new TreeNode; node->setZValue(100.); d_nodes.append(node); for (xmlNodePtr child = xmlNode->children; child; child = child->next) { if (child->type == XML_ELEMENT_NODE && nodeNameIs(child, "node")) { TreeNode *childNode = processNode(child); node->appendChild(childNode); Edge *edge = new Edge(); edge->setParent(node); edge->setChild(childNode); d_edges.push_back(edge); } if (child->type == XML_ELEMENT_NODE && (nodeNameIs(child, "label") || nodeNameIs(child, "tooltip"))) { QScopedPointer<xmlBuffer, XmlBufferDeleter> buf(xmlBufferCreate()); for (xmlNodePtr contentNode = child->children; contentNode; contentNode = contentNode->next) { scrubNamespace(contentNode); xmlNodeDump(buf.data(), 0, contentNode, 0, 0); } xmlChar const *value = xmlBufferContent(buf.data()); if (nodeNameIs(child, "label")) node->setLabel(QString::fromUtf8(reinterpret_cast<char const *>(value)).trimmed()); else { node->setTooltip(QString::fromUtf8(reinterpret_cast<char const *>(value))); PopupItem *popupItem = new PopupItem(0, node->tooltip()); popupItem->setVisible(false); popupItem->setZValue(1.0); node->setPopupItem(popupItem); addItem(popupItem); } } } for (xmlAttrPtr attr = xmlNode->properties; attr; attr = attr->next) { QScopedPointer<xmlChar, XmlDeleter> value( xmlNodeGetContent(attr->children)); if (value == 0) continue; // Do we have an active node marker? if (xmlStrEqual(attr->name, reinterpret_cast<xmlChar const *>("active")) && xmlStrEqual(value.data(), reinterpret_cast<xmlChar const *>("1"))) node->setActive(true); else node->setAttribute( QString::fromUtf8(reinterpret_cast<char const *>(attr->name)), QString::fromUtf8(reinterpret_cast<char const *>(value.data()))); if (xmlStrEqual(attr->name, reinterpret_cast<xmlChar const *>("id"))) { QString nodeID = QString::fromUtf8(reinterpret_cast<char const *>(value.data())); d_idNodes[nodeID] = node; } } return node; } void DactTreeScene::processSecondaryEdges(xmlNodePtr node) { for (xmlNodePtr edge = node->children; edge; edge = edge->next) { if (!nodeNameIs(edge, "secedge")) continue; QScopedPointer<xmlChar, XmlDeleter> cat(xmlGetProp(edge, reinterpret_cast<xmlChar const *>("cat"))); QScopedPointer<xmlChar, XmlDeleter> from(xmlGetProp(edge, reinterpret_cast<xmlChar const *>("from"))); QScopedPointer<xmlChar, XmlDeleter> to(xmlGetProp(edge, reinterpret_cast<xmlChar const *>("to"))); QString qFrom = QString::fromUtf8(reinterpret_cast<char const *>(from.data())); QMap<QString, TreeNode *>::const_iterator fromIter = d_idNodes.find(qFrom); if (fromIter == d_idNodes.end()) { qWarning() << "Could not find from-node for secondary edge, skipping"; continue; } QString qTo = QString::fromUtf8(reinterpret_cast<char const *>(to.data())); QMap<QString, TreeNode *>::const_iterator toIter = d_idNodes.find(qTo); if (toIter == d_idNodes.end()) { qWarning() << "Could not find to-node for secondary edge, skipping"; continue; } SecEdge *secEdge = new SecEdge; secEdge->setZValue(50); secEdge->setFrom(fromIter.value()); secEdge->setTo(toIter.value()); secEdge->setLabel(QString::fromUtf8(reinterpret_cast<char const *>(cat.data()))); d_edges.push_back(secEdge); } } bool DactTreeScene::nodeNameIs(xmlNodePtr xmlNode, char const *name) { return xmlStrEqual(xmlNode->name, reinterpret_cast<xmlChar const *>(name)); } void DactTreeScene::scrubNamespace(xmlNodePtr xmlNode) { xmlSetNs(xmlNode, 0); for (xmlNodePtr child = xmlNode->children; child; child = child->next) scrubNamespace(child); } void DactTreeScene::freeNodes() { delete rootNode(); d_nodes.clear(); // because all have rootNode as parent/ancestor // they will have been deleted automatically. foreach (QGraphicsItem *edge, d_edges) { delete edge; } d_edges.clear(); } QList<TreeNode*> const &DactTreeScene::nodes() const { return d_nodes; } QList<TreeNode*> DactTreeScene::activeNodes() const { QList<TreeNode*> nodes; foreach (TreeNode* node, d_nodes) { if (node->isActive()) nodes.append(node); } return nodes; } TreeNode* DactTreeScene::rootNode() { if (d_nodes.size() > 0) return d_nodes[0]; else return 0; }
#include <algorithm> #include <QDebug> #include <QFontMetrics> #include <QGraphicsSceneHoverEvent> #include <QGraphicsView> #include <QPainter> #include <QSettings> extern "C" { #include <libxml/parser.h> #include <libxml/tree.h> } #include "DactTreeScene.hh" #include "Edge.hh" #include "SecEdge.hh" #include "TreeNode.hh" #include "PopupItem.hh" #include "XMLDeleters.hh" DactTreeScene::DactTreeScene(QObject *parent) : QGraphicsScene(parent), d_nodes() { connect(this, SIGNAL(selectionChanged()), this, SLOT(emitSelectionChange())); } DactTreeScene::~DactTreeScene() { disconnect(this, SIGNAL(selectionChanged())); if (rootNode()) freeNodes(); } void DactTreeScene::checkElementAndAssign(xmlNodePtr node, char const *nodeName, xmlNodePtr *variable) { if (node->type == XML_ELEMENT_NODE && nodeNameIs(node, nodeName)) { { if (*variable == 0) *variable = node; else qWarning() << "More than one '" << nodeName << "', only using first!"; } } } void DactTreeScene::emitSelectionChange() { emit selectionChanged(dynamic_cast<TreeNode*>(focusItem())); } void DactTreeScene::parseTree(QString const &xml) { // If there was a previous parse, clean up first. if (rootNode()) { removeItem(rootNode()); foreach (QGraphicsItem *edge, d_edges) { removeItem(edge); } freeNodes(); } parseXML(xml); // If parsing was successful enough to create a root node, // add it to the scene if (rootNode()) { rootNode()->layout(); foreach (QGraphicsItem *edge, d_edges) { addItem(edge); } addItem(rootNode()); } else { qWarning() << "No root node was found"; } } void DactTreeScene::parseXML(QString const &xml) { QByteArray xmlData(xml.toUtf8()); QScopedPointer<xmlDoc, XmlDocDeleter> doc( xmlReadMemory(xmlData.constData(), xmlData.size(), NULL, NULL, 0)); if (doc == 0) { qWarning() << "Could not parse tree!"; return; } xmlNode *treeRoot = xmlDocGetRootElement(doc.data()); if (treeRoot == NULL) { qWarning() << "Tree does not have a root?"; return; } xmlNodePtr treeRootNode = 0; xmlNodePtr secEdges = 0; for (xmlNodePtr child = treeRoot->children; child; child = child->next) { checkElementAndAssign(child, "node", &treeRootNode); checkElementAndAssign(child, "secedges", &secEdges); } if (treeRootNode == 0) { qWarning() << "Tree does not have a root?"; return; } processNode(treeRootNode); if (secEdges) processSecondaryEdges(secEdges); } TreeNode *DactTreeScene::processNode(xmlNodePtr xmlNode) { TreeNode *node = new TreeNode; node->setZValue(100.); d_nodes.append(node); for (xmlNodePtr child = xmlNode->children; child; child = child->next) { if (child->type == XML_ELEMENT_NODE && nodeNameIs(child, "node")) { TreeNode *childNode = processNode(child); node->appendChild(childNode); Edge *edge = new Edge(); edge->setParent(node); edge->setChild(childNode); d_edges.push_back(edge); } if (child->type == XML_ELEMENT_NODE && (nodeNameIs(child, "label") || nodeNameIs(child, "tooltip"))) { QScopedPointer<xmlBuffer, XmlBufferDeleter> buf(xmlBufferCreate()); for (xmlNodePtr contentNode = child->children; contentNode; contentNode = contentNode->next) { scrubNamespace(contentNode); xmlNodeDump(buf.data(), 0, contentNode, 0, 0); } xmlChar const *value = xmlBufferContent(buf.data()); if (nodeNameIs(child, "label")) node->setLabel(QString::fromUtf8(reinterpret_cast<char const *>(value)).trimmed()); else { node->setTooltip(QString::fromUtf8(reinterpret_cast<char const *>(value))); PopupItem *popupItem = new PopupItem(0, node->tooltip()); popupItem->setVisible(false); popupItem->setZValue(150.); node->setPopupItem(popupItem); addItem(popupItem); } } } for (xmlAttrPtr attr = xmlNode->properties; attr; attr = attr->next) { QScopedPointer<xmlChar, XmlDeleter> value( xmlNodeGetContent(attr->children)); if (value == 0) continue; // Do we have an active node marker? if (xmlStrEqual(attr->name, reinterpret_cast<xmlChar const *>("active")) && xmlStrEqual(value.data(), reinterpret_cast<xmlChar const *>("1"))) node->setActive(true); else node->setAttribute( QString::fromUtf8(reinterpret_cast<char const *>(attr->name)), QString::fromUtf8(reinterpret_cast<char const *>(value.data()))); if (xmlStrEqual(attr->name, reinterpret_cast<xmlChar const *>("id"))) { QString nodeID = QString::fromUtf8(reinterpret_cast<char const *>(value.data())); d_idNodes[nodeID] = node; } } return node; } void DactTreeScene::processSecondaryEdges(xmlNodePtr node) { for (xmlNodePtr edge = node->children; edge; edge = edge->next) { if (!nodeNameIs(edge, "secedge")) continue; QScopedPointer<xmlChar, XmlDeleter> cat(xmlGetProp(edge, reinterpret_cast<xmlChar const *>("cat"))); QScopedPointer<xmlChar, XmlDeleter> from(xmlGetProp(edge, reinterpret_cast<xmlChar const *>("from"))); QScopedPointer<xmlChar, XmlDeleter> to(xmlGetProp(edge, reinterpret_cast<xmlChar const *>("to"))); QString qFrom = QString::fromUtf8(reinterpret_cast<char const *>(from.data())); QMap<QString, TreeNode *>::const_iterator fromIter = d_idNodes.find(qFrom); if (fromIter == d_idNodes.end()) { qWarning() << "Could not find from-node for secondary edge, skipping"; continue; } QString qTo = QString::fromUtf8(reinterpret_cast<char const *>(to.data())); QMap<QString, TreeNode *>::const_iterator toIter = d_idNodes.find(qTo); if (toIter == d_idNodes.end()) { qWarning() << "Could not find to-node for secondary edge, skipping"; continue; } SecEdge *secEdge = new SecEdge; secEdge->setZValue(50.); secEdge->setFrom(fromIter.value()); secEdge->setTo(toIter.value()); secEdge->setLabel(QString::fromUtf8(reinterpret_cast<char const *>(cat.data()))); d_edges.push_back(secEdge); } } bool DactTreeScene::nodeNameIs(xmlNodePtr xmlNode, char const *name) { return xmlStrEqual(xmlNode->name, reinterpret_cast<xmlChar const *>(name)); } void DactTreeScene::scrubNamespace(xmlNodePtr xmlNode) { xmlSetNs(xmlNode, 0); for (xmlNodePtr child = xmlNode->children; child; child = child->next) scrubNamespace(child); } void DactTreeScene::freeNodes() { delete rootNode(); d_nodes.clear(); // because all have rootNode as parent/ancestor // they will have been deleted automatically. foreach (QGraphicsItem *edge, d_edges) { delete edge; } d_edges.clear(); } QList<TreeNode*> const &DactTreeScene::nodes() const { return d_nodes; } QList<TreeNode*> DactTreeScene::activeNodes() const { QList<TreeNode*> nodes; foreach (TreeNode* node, d_nodes) { if (node->isActive()) nodes.append(node); } return nodes; } TreeNode* DactTreeScene::rootNode() { if (d_nodes.size() > 0) return d_nodes[0]; else return 0; }
Fix z-value for popup items.
Fix z-value for popup items.
C++
lgpl-2.1
evdmade01/dact,evdmade01/dact,rug-compling/dact,evdmade01/dact,rug-compling/dact
87d82f42a31ae9b3b00ee731700b595fc1306836
src/DirectedGraph.cpp
src/DirectedGraph.cpp
#include "DirectedGraph.h" #include <cassert> #include <iostream> #include "RawStatistics.h" using namespace std; DirectedGraph::DirectedGraph(int _id) : Graph(1, _id) { } DirectedGraph::DirectedGraph(const DirectedGraph & other) : Graph(other) { } std::shared_ptr<Graph> DirectedGraph::createSimilar() const { std::shared_ptr<Graph> graph(new DirectedGraph(getId())); graph->setLocationGraphValid(false); graph->setTemporal(isTemporal()); graph->setPersonality(getPersonality()); graph->setHasTextures(hasTextures()); graph->setDoubleBufferedVBO(hasDoubleBufferedVBO()); graph->setLineWidth(getLineWidth()); graph->setNodeArray(nodes); return graph; } bool DirectedGraph::updateData(time_t start_time, time_t end_time, float start_sentiment, float end_sentiment, Graph & source_graph, RawStatistics & stats, bool is_first_level, Graph * base_graph) { if (!(end_time > start_time)) { cerr << "invalid time range for updateData: " << start_time << " - " << end_time << endl; return false; } auto & sid = source_graph.getNodeArray().getTable()["source"]; auto & soid = source_graph.getNodeArray().getTable()["id"]; auto & user_type = source_graph.getNodeArray().getTable()["type"]; auto & political_party = source_graph.getNodeArray().getTable()["party"]; auto & name_column = source_graph.getNodeArray().getTable()["name"]; auto & uname_column = source_graph.getNodeArray().getTable()["uname"]; auto begin = source_graph.begin_edges(); auto end = source_graph.end_edges(); auto it = begin; if (current_pos == -1) { clear(); edge_attributes.clear(); current_pos = 0; cerr << "restarting update, begin = " << begin.get() << ", cp = " << current_pos << ", end = " << end.get() << ", source = " << &source_graph << ", edges = " << source_graph.getEdgeCount() << endl; } else { cerr << "continuing update, begin = " << begin.get() << ", cp = " << current_pos << ", end = " << end.get() << ", source = " << &source_graph << ", edges = " << source_graph.getEdgeCount() << endl; for (int i = 0; i < current_pos; i++) ++it; } auto & nodes = getNodeArray(); unsigned int skipped_count = 0; bool is_changed = false; unsigned int num_edges_processed = 0; for ( ; it != end; ++it, current_pos++) { num_edges_processed++; time_t t = 0; float se = 0; short lang = 0; long long app_id = -1, filter_id = -1; bool is_first = false; assert(it->face != -1); if (it->face != -1) { auto & fd = source_graph.getFaceAttributes(it->face); t = fd.timestamp; se = fd.sentiment; lang = fd.lang; app_id = fd.app_id; filter_id = fd.filter_id; is_first = fd.first_edge == current_pos; } if (it->tail < 0 || it->head < 0 || it->tail >= nodes.size() || it->head >= nodes.size()) { cerr << "invalid values: tail = " << it->tail << ", head = " << it->head << ", t = " << t << ", count = " << nodes.size() << ", n = " << num_edges_processed << endl; assert(0); } if ((!start_time || t >= start_time) && (!end_time || t < end_time) && se >= start_sentiment && se <= end_sentiment) { if (t < min_time || min_time == 0) min_time = t; if (t > max_time) max_time = t; pair<int, int> np(it->tail, it->head); short first_user_sid = sid.getInt(np.first); short target_user_sid = sid.getInt(np.second); long long first_user_soid = soid.getInt64(np.first); long long target_user_soid = soid.getInt64(np.second); auto & td1 = base_graph->getNodeTertiaryData(np.first); auto & td2 = base_graph->getNodeTertiaryData(np.second); if (!is_first_level) { if (td1.indegree < getMinSignificance()) { skipped_count++; continue; } if (td2.indegree < getMinSignificance()) { skipped_count++; continue; } } is_changed = true; auto & target_nd_old = nodes.getNodeData(np.second); NodeType target_type = target_nd_old.type; if (is_first_level && is_first) { stats.addActivity(t, first_user_sid, first_user_soid, lang, app_id, filter_id, PoliticalParty(political_party.getInt(np.first))); } if (is_first_level && !seen_nodes.count(np.second)) { seen_nodes.insert(np.second); if (target_type == NODE_HASHTAG) { stats.addHashtag(name_column.getText(np.second)); num_hashtags++; } else if (target_type == NODE_URL) { stats.addLink(name_column.getText(np.second), uname_column.getText(np.second)); num_links++; } else { UserType ut = UserType(user_type.getInt(np.second)); if (ut != UNKNOWN_TYPE) stats.addUserType(ut); // stats.addPoliticalParty(PoliticalParty(political_party.getInt(np.first))); } } if (target_type != NODE_URL && target_type != NODE_HASHTAG) { if (is_first_level && target_type == NODE_ANY) { stats.addReceivedActivity(t, target_user_sid, target_user_soid, app_id, filter_id); } assert(end_time > start_time); long long coverage = 0; int time_pos = 63LL * (t - start_time) / (end_time - start_time); assert(time_pos >= 0 && time_pos < 64); coverage |= 1 << time_pos; unordered_map<int, unordered_map<int, int> >::iterator it1; unordered_map<int, int>::iterator it2; if ((it1 = seen_edges.find(np.first)) != seen_edges.end() && (it2 = it1->second.find(np.second)) != it1->second.end()) { #if 0 updateOutdegree(np.first, 1.0f); updateIndegree(np.second, 1.0f); updateNodeSize(np.first); updateNodeSize(np.second); #endif auto & ed = getEdgeAttributes(it2->second); ed.coverage |= coverage; float new_weight = 0; for (int i = 0; i < 64; i++) { if (ed.coverage & (1 << i)) new_weight += 1.0f; } new_weight /= 64.0f; updateEdgeWeight(it2->second, new_weight - ed.weight); } else { if (td1.indegree == 0 && td1.outdegree == 0) { bool has_zero = zerodegree_nodes.count(np.first) != 0; if (np.first == np.second && !has_zero) { int z = nodes.getZeroDegreeNode(); cerr << "DEBUG: adding node " << np.first << " to zero degree node (id = " << z << ")\n"; addChild(z, np.first); zerodegree_nodes.insert(np.first); } else if (np.first != np.second && has_zero) { cerr << "DEBUG: removing node " << np.first << " from zero degree node (A)\n"; removeChild(np.first); zerodegree_nodes.erase(np.first); } } if (td2.indegree == 0 && td2.outdegree == 0 && np.first != np.second && zerodegree_nodes.count(np.second) != 0) { cerr << "DEBUG: removing node " << np.second << " from zero degree node (B)\n"; removeChild(np.second); zerodegree_nodes.erase(np.second); } seen_edges[np.first][np.second] = addEdge(np.first, np.second, -1, 1.0f / 64.0f, 0, coverage); } } } } cerr << "updated graph data, nodes = " << nodes.size() << ", edges = " << getEdgeCount() << ", min_sig = " << getMinSignificance() << ", skipped = " << skipped_count << ", first = " << is_first_level << endl; if (is_first_level) { stats.setTimeRange(min_time, max_time); stats.setNumRawNodes(nodes.size()); stats.setNumRawEdges(source_graph.getEdgeCount()); // stats.setNumPosts(num_posts); // stats.setNumActiveUsers(num_active_users); } return is_changed; } #if 0 struct component_s { component_s() { } unsigned int size = 0; }; Graph * DirectedGraph::simplify() const { vector<component_s> components; map<int, int> nodes_to_component; for (int v = 0; v < getNodeCount(); v++) { int found_component = -1; int edge = getNodeFirstEdge(v); while (edge != -1) { int succ = getEdgeTargetNode(edge); auto it = nodes_to_component.find(succ); if (it != nodes_to_component.end()) { found_component = it->second; break; } edge = getNextNodeEdge(edge); } if (found_component == -1) { found_component = components.size(); components.push_back(component_s()); } nodes_to_component[v] = found_component; } unsigned int singles_count = 0, pairs_count = 0; for (auto c : components) { if (c.size == 1) { singles_count++; } else if (c.size == 2) { pairs_count++; } } DirectedGraph * new_graph = new DirectedGraph(); int singles_node = -1, pairs_node = -1; if (singles_count) { singles_node = new_graph->addNode(); } if (pairs_count) { pairs_node = new_graph->addNode(); } for (int v = 0; v < getNodeCount(); v++) { int component_id = nodes_to_component[v]; auto & c = components[component_id]; if (c.size == 1 || c.size == 2) { } else { } } return new_graph; } #endif
#include "DirectedGraph.h" #include <cassert> #include <iostream> #include "RawStatistics.h" using namespace std; DirectedGraph::DirectedGraph(int _id) : Graph(1, _id) { } DirectedGraph::DirectedGraph(const DirectedGraph & other) : Graph(other) { } std::shared_ptr<Graph> DirectedGraph::createSimilar() const { std::shared_ptr<Graph> graph(new DirectedGraph(getId())); graph->setLocationGraphValid(false); graph->setTemporal(isTemporal()); graph->setPersonality(getPersonality()); graph->setHasTemporalCoverage(hasTemporalCoverage()); graph->setHasTextures(hasTextures()); graph->setDoubleBufferedVBO(hasDoubleBufferedVBO()); graph->setLineWidth(getLineWidth()); graph->setNodeArray(nodes); return graph; } bool DirectedGraph::updateData(time_t start_time, time_t end_time, float start_sentiment, float end_sentiment, Graph & source_graph, RawStatistics & stats, bool is_first_level, Graph * base_graph) { if (!(end_time > start_time)) { cerr << "invalid time range for updateData: " << start_time << " - " << end_time << endl; return false; } auto & sid = source_graph.getNodeArray().getTable()["source"]; auto & soid = source_graph.getNodeArray().getTable()["id"]; auto & user_type = source_graph.getNodeArray().getTable()["type"]; auto & political_party = source_graph.getNodeArray().getTable()["party"]; auto & name_column = source_graph.getNodeArray().getTable()["name"]; auto & uname_column = source_graph.getNodeArray().getTable()["uname"]; auto begin = source_graph.begin_edges(); auto end = source_graph.end_edges(); auto it = begin; if (current_pos == -1) { clear(); edge_attributes.clear(); current_pos = 0; cerr << "restarting update, begin = " << begin.get() << ", cp = " << current_pos << ", end = " << end.get() << ", source = " << &source_graph << ", edges = " << source_graph.getEdgeCount() << endl; } else { cerr << "continuing update, begin = " << begin.get() << ", cp = " << current_pos << ", end = " << end.get() << ", source = " << &source_graph << ", edges = " << source_graph.getEdgeCount() << endl; for (int i = 0; i < current_pos; i++) ++it; } auto & nodes = getNodeArray(); unsigned int skipped_count = 0; bool is_changed = false; unsigned int num_edges_processed = 0; for ( ; it != end; ++it, current_pos++) { num_edges_processed++; time_t t = 0; float se = 0; short lang = 0; long long app_id = -1, filter_id = -1; bool is_first = false; assert(it->face != -1); if (it->face != -1) { auto & fd = source_graph.getFaceAttributes(it->face); t = fd.timestamp; se = fd.sentiment; lang = fd.lang; app_id = fd.app_id; filter_id = fd.filter_id; is_first = fd.first_edge == current_pos; } if (it->tail < 0 || it->head < 0 || it->tail >= nodes.size() || it->head >= nodes.size()) { cerr << "invalid values: tail = " << it->tail << ", head = " << it->head << ", t = " << t << ", count = " << nodes.size() << ", n = " << num_edges_processed << endl; assert(0); } if ((!start_time || t >= start_time) && (!end_time || t < end_time) && se >= start_sentiment && se <= end_sentiment) { if (t < min_time || min_time == 0) min_time = t; if (t > max_time) max_time = t; pair<int, int> np(it->tail, it->head); short first_user_sid = sid.getInt(np.first); short target_user_sid = sid.getInt(np.second); long long first_user_soid = soid.getInt64(np.first); long long target_user_soid = soid.getInt64(np.second); auto & td1 = base_graph->getNodeTertiaryData(np.first); auto & td2 = base_graph->getNodeTertiaryData(np.second); if (!is_first_level) { if (td1.indegree < getMinSignificance()) { skipped_count++; continue; } if (td2.indegree < getMinSignificance()) { skipped_count++; continue; } } is_changed = true; auto & target_nd_old = nodes.getNodeData(np.second); NodeType target_type = target_nd_old.type; if (is_first_level && is_first) { stats.addActivity(t, first_user_sid, first_user_soid, lang, app_id, filter_id, PoliticalParty(political_party.getInt(np.first))); } if (is_first_level && !seen_nodes.count(np.second)) { seen_nodes.insert(np.second); if (target_type == NODE_HASHTAG) { stats.addHashtag(name_column.getText(np.second)); num_hashtags++; } else if (target_type == NODE_URL) { stats.addLink(name_column.getText(np.second), uname_column.getText(np.second)); num_links++; } else { UserType ut = UserType(user_type.getInt(np.second)); if (ut != UNKNOWN_TYPE) stats.addUserType(ut); // stats.addPoliticalParty(PoliticalParty(political_party.getInt(np.first))); } } if (target_type != NODE_URL && target_type != NODE_HASHTAG) { if (is_first_level && target_type == NODE_ANY) { stats.addReceivedActivity(t, target_user_sid, target_user_soid, app_id, filter_id); } assert(end_time > start_time); long long coverage = 0; int time_pos = 63LL * (t - start_time) / (end_time - start_time); assert(time_pos >= 0 && time_pos < 64); coverage |= 1 << time_pos; unordered_map<int, unordered_map<int, int> >::iterator it1; unordered_map<int, int>::iterator it2; if ((it1 = seen_edges.find(np.first)) != seen_edges.end() && (it2 = it1->second.find(np.second)) != it1->second.end()) { #if 0 updateOutdegree(np.first, 1.0f); updateIndegree(np.second, 1.0f); updateNodeSize(np.first); updateNodeSize(np.second); #endif if (hasTemporalCoverage()) { auto & ed = getEdgeAttributes(it2->second); ed.coverage |= coverage; float new_weight = 0; for (int i = 0; i < 64; i++) { if (ed.coverage & (1 << i)) new_weight += 1.0f; } new_weight /= 64.0f; updateEdgeWeight(it2->second, new_weight - ed.weight); } } else { if (td1.indegree == 0 && td1.outdegree == 0) { bool has_zero = zerodegree_nodes.count(np.first) != 0; if (np.first == np.second && !has_zero) { int z = nodes.getZeroDegreeNode(); cerr << "DEBUG: adding node " << np.first << " to zero degree node (id = " << z << ")\n"; addChild(z, np.first); zerodegree_nodes.insert(np.first); } else if (np.first != np.second && has_zero) { cerr << "DEBUG: removing node " << np.first << " from zero degree node (A)\n"; removeChild(np.first); zerodegree_nodes.erase(np.first); } } if (td2.indegree == 0 && td2.outdegree == 0 && np.first != np.second && zerodegree_nodes.count(np.second) != 0) { cerr << "DEBUG: removing node " << np.second << " from zero degree node (B)\n"; removeChild(np.second); zerodegree_nodes.erase(np.second); } seen_edges[np.first][np.second] = addEdge(np.first, np.second, -1, 1.0f / 64.0f, 0, hasTemporalCoverage() ? coverage : 1.0f); } } } } cerr << "updated graph data, nodes = " << nodes.size() << ", edges = " << getEdgeCount() << ", min_sig = " << getMinSignificance() << ", skipped = " << skipped_count << ", first = " << is_first_level << endl; if (is_first_level) { stats.setTimeRange(min_time, max_time); stats.setNumRawNodes(nodes.size()); stats.setNumRawEdges(source_graph.getEdgeCount()); // stats.setNumPosts(num_posts); // stats.setNumActiveUsers(num_active_users); } return is_changed; } #if 0 struct component_s { component_s() { } unsigned int size = 0; }; Graph * DirectedGraph::simplify() const { vector<component_s> components; map<int, int> nodes_to_component; for (int v = 0; v < getNodeCount(); v++) { int found_component = -1; int edge = getNodeFirstEdge(v); while (edge != -1) { int succ = getEdgeTargetNode(edge); auto it = nodes_to_component.find(succ); if (it != nodes_to_component.end()) { found_component = it->second; break; } edge = getNextNodeEdge(edge); } if (found_component == -1) { found_component = components.size(); components.push_back(component_s()); } nodes_to_component[v] = found_component; } unsigned int singles_count = 0, pairs_count = 0; for (auto c : components) { if (c.size == 1) { singles_count++; } else if (c.size == 2) { pairs_count++; } } DirectedGraph * new_graph = new DirectedGraph(); int singles_node = -1, pairs_node = -1; if (singles_count) { singles_node = new_graph->addNode(); } if (pairs_count) { pairs_node = new_graph->addNode(); } for (int v = 0; v < getNodeCount(); v++) { int component_id = nodes_to_component[v]; auto & c = components[component_id]; if (c.size == 1 || c.size == 2) { } else { } } return new_graph; } #endif
update temporal coverage and coverage based weight, only if temporal coverage is enabled
update temporal coverage and coverage based weight, only if temporal coverage is enabled
C++
mit
Sometrik/graphlib,Sometrik/graphlib
31f563e495026e94c4e09ad45dd3febc88370b4e
libqimessaging/qimessaging/details/genericvalue.hxx
libqimessaging/qimessaging/details/genericvalue.hxx
#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QIMESSAGING_DETAILS_GENERICVALUE_HXX_ #define _QI_MESSAGING_VALUE_HXX_ #include <boost/type_traits/remove_const.hpp> #include <qimessaging/typeint.hpp> namespace qi { class ValueClone { public: void* clone(void* src) { return new GenericValue(((GenericValue*)src)->clone()); } void destroy(void* ptr) { ((GenericValue*)ptr)->destroy(); delete (GenericValue*)ptr; } }; class ValueValue { public: bool toValue(const void* ptr, qi::detail::DynamicValue& val) { GenericValue* m = (GenericValue*)ptr; return m->type->toValue(m->value, val); } void* fromValue(const qi::detail::DynamicValue& val) { GenericValue v = ::qi::toValue(val); return new GenericValue(v.clone()); } }; template<> class TypeImpl<GenericValue>: public DefaultTypeImpl< GenericValue, TypeDefaultAccess<GenericValue>, ValueClone, ValueValue, TypeDefaultSerialize<TypeDefaultAccess<GenericValue> > > {}; namespace detail { template<typename T> struct TypeCopy { void operator()(T &dst, const T &src) { dst = src; } }; template<int I> struct TypeCopy<char[I] > { void operator() (char* dst, const char* src) { memcpy(dst, src, I); } }; } template<typename T> GenericValue toValue(const T& v) { GenericValue res; res.type = typeOf<typename boost::remove_const<T>::type>(); res.value = res.type->initializeStorage(const_cast<void*>((const void*)&v)); return res; } inline GenericValue GenericValue::clone() const { GenericValue res; res.type = type; res.value = type?res.type->clone(value):0; return res; } template<typename T> std::pair<const T*, bool> GenericValue::to() const { Type* targetType = typeOf<T>(); if (type->info() == targetType->info()) return std::make_pair((const T*)type->ptrFromStorage((void**)&value), false); else { std::pair<GenericValue, bool> mv = convert(targetType); // NOTE: delete theResult.first will not do, destroy must be called, return std::make_pair((const T*)mv.first.type->ptrFromStorage(&mv.first.value), mv.second); } } inline AutoGenericValue::AutoGenericValue(const AutoGenericValue& b) { value = b.value; type = b.type; } template<typename T> AutoGenericValue::AutoGenericValue(const T& ptr) { *(GenericValue*)this = toValue(ptr); } inline AutoGenericValue::AutoGenericValue() { value = type = 0; } inline std::string GenericValue::signature() const { if (!type) return ""; else return type->signature(); } inline void GenericValue::destroy() { if (type && value) type->destroy(value); } inline void GenericValue::serialize(ODataStream& os) const { if (type) type->serialize(os, value); } inline GenericValue::GenericValue() : value(0) , type(0) { } inline Type::Kind GenericValue::kind() const { if (!type) return Type::Void; else return type->kind(); } // Kind -> handler Type (TypeInt, TypeList...) accessor class KindNotConvertible; template<Type::Kind T> struct TypeOfKind { typedef KindNotConvertible type; }; #define TYPE_OF_KIND(k, t) template<> struct TypeOfKind<k> { typedef t type;} TYPE_OF_KIND(Type::Int, TypeInt); TYPE_OF_KIND(Type::Float, TypeFloat); //TYPE_OF_KIND(Type::String, TypeString); #undef TYPE_OF_KIND // Type -> Kind accessor namespace detail { struct Nothing {}; template<Type::Kind k> struct MakeKind { static const Type::Kind value = k; }; template<typename C, typename T, typename F> struct IfElse { }; template<typename T, typename F> struct IfElse<boost::true_type, T, F> { typedef T type; }; template<typename T, typename F> struct IfElse<boost::false_type, T, F> { typedef F type; }; } #define IF(cond, type) \ public detail::IfElse<cond, typename detail::MakeKind<type>, detail::Nothing>::type template<typename T> struct KindOfType : IF(typename boost::is_integral<T>::type, Type::Int) , IF(typename boost::is_floating_point<T>::type, Type::Float) { }; #undef IF template<typename T, Type::Kind k> inline T GenericValue::as() const { if (kind() != k) { qiLogWarning("qi.GenericValue") << "as: type " << kind() <<" not convertible to kind " << k; return T(); } return dynamic_cast<const typename TypeOfKind<k>::type*>(type)->get(value); } template<typename T> inline T GenericValue::as() const { return as<T, KindOfType<T>::value>(); } inline int64_t GenericValue::asInt() const { return as<int64_t, Type::Int>(); } inline float GenericValue::asFloat() const { return as<float, Type::Float>(); } inline double GenericValue::asDouble() const { return as<double, Type::Float>(); } inline std::string GenericValue::asString() const { return ""; // as<std::string, Type::String>(); } namespace detail { /** This class can be used to convert the return value of an arbitrary function * into a GenericValue. It handles functions returning void. * * Usage: * ValueCopy val; * val(), functionCall(arg); * * in val(), parenthesis are useful to avoid compiler warning "val not used" when handling void. */ class GenericValueCopy: public GenericValue { public: template<typename T> void operator,(const T& any); GenericValueCopy &operator()() { return *this; } }; template<typename T> void GenericValueCopy::operator,(const T& any) { *(GenericValue*)this = toValue(any); *(GenericValue*)this = clone(); } } } #endif // _QIMESSAGING_DETAILS_GENERICVALUE_HXX_
#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QIMESSAGING_DETAILS_GENERICVALUE_HXX_ #define _QIMESSAGING_DETAILS_GENERICVALUE_HXX_ #include <boost/type_traits/remove_const.hpp> #include <qimessaging/typeint.hpp> namespace qi { class ValueClone { public: void* clone(void* src) { return new GenericValue(((GenericValue*)src)->clone()); } void destroy(void* ptr) { ((GenericValue*)ptr)->destroy(); delete (GenericValue*)ptr; } }; class ValueValue { public: bool toValue(const void* ptr, qi::detail::DynamicValue& val) { GenericValue* m = (GenericValue*)ptr; return m->type->toValue(m->value, val); } void* fromValue(const qi::detail::DynamicValue& val) { GenericValue v = ::qi::toValue(val); return new GenericValue(v.clone()); } }; template<> class TypeImpl<GenericValue>: public DefaultTypeImpl< GenericValue, TypeDefaultAccess<GenericValue>, ValueClone, ValueValue, TypeDefaultSerialize<TypeDefaultAccess<GenericValue> > > {}; namespace detail { template<typename T> struct TypeCopy { void operator()(T &dst, const T &src) { dst = src; } }; template<int I> struct TypeCopy<char[I] > { void operator() (char* dst, const char* src) { memcpy(dst, src, I); } }; } template<typename T> GenericValue toValue(const T& v) { GenericValue res; res.type = typeOf<typename boost::remove_const<T>::type>(); res.value = res.type->initializeStorage(const_cast<void*>((const void*)&v)); return res; } inline GenericValue GenericValue::clone() const { GenericValue res; res.type = type; res.value = type?res.type->clone(value):0; return res; } template<typename T> std::pair<const T*, bool> GenericValue::to() const { Type* targetType = typeOf<T>(); if (type->info() == targetType->info()) return std::make_pair((const T*)type->ptrFromStorage((void**)&value), false); else { std::pair<GenericValue, bool> mv = convert(targetType); // NOTE: delete theResult.first will not do, destroy must be called, return std::make_pair((const T*)mv.first.type->ptrFromStorage(&mv.first.value), mv.second); } } inline AutoGenericValue::AutoGenericValue(const AutoGenericValue& b) { value = b.value; type = b.type; } template<typename T> AutoGenericValue::AutoGenericValue(const T& ptr) { *(GenericValue*)this = toValue(ptr); } inline AutoGenericValue::AutoGenericValue() { value = type = 0; } inline std::string GenericValue::signature() const { if (!type) return ""; else return type->signature(); } inline void GenericValue::destroy() { if (type && value) type->destroy(value); } inline void GenericValue::serialize(ODataStream& os) const { if (type) type->serialize(os, value); } inline GenericValue::GenericValue() : value(0) , type(0) { } inline Type::Kind GenericValue::kind() const { if (!type) return Type::Void; else return type->kind(); } // Kind -> handler Type (TypeInt, TypeList...) accessor class KindNotConvertible; template<Type::Kind T> struct TypeOfKind { typedef KindNotConvertible type; }; #define TYPE_OF_KIND(k, t) template<> struct TypeOfKind<k> { typedef t type;} TYPE_OF_KIND(Type::Int, TypeInt); TYPE_OF_KIND(Type::Float, TypeFloat); //TYPE_OF_KIND(Type::String, TypeString); #undef TYPE_OF_KIND // Type -> Kind accessor namespace detail { struct Nothing {}; template<Type::Kind k> struct MakeKind { static const Type::Kind value = k; }; template<typename C, typename T, typename F> struct IfElse { }; template<typename T, typename F> struct IfElse<boost::true_type, T, F> { typedef T type; }; template<typename T, typename F> struct IfElse<boost::false_type, T, F> { typedef F type; }; } #define IF(cond, type) \ public detail::IfElse<cond, typename detail::MakeKind<type>, detail::Nothing>::type template<typename T> struct KindOfType : IF(typename boost::is_integral<T>::type, Type::Int) , IF(typename boost::is_floating_point<T>::type, Type::Float) { }; #undef IF template<typename T, Type::Kind k> inline T GenericValue::as() const { if (kind() != k) { qiLogWarning("qi.GenericValue") << "as: type " << kind() <<" not convertible to kind " << k; return T(); } return dynamic_cast<const typename TypeOfKind<k>::type*>(type)->get(value); } template<typename T> inline T GenericValue::as() const { return as<T, KindOfType<T>::value>(); } inline int64_t GenericValue::asInt() const { return as<int64_t, Type::Int>(); } inline float GenericValue::asFloat() const { return as<float, Type::Float>(); } inline double GenericValue::asDouble() const { return as<double, Type::Float>(); } inline std::string GenericValue::asString() const { return ""; // as<std::string, Type::String>(); } namespace detail { /** This class can be used to convert the return value of an arbitrary function * into a GenericValue. It handles functions returning void. * * Usage: * ValueCopy val; * val(), functionCall(arg); * * in val(), parenthesis are useful to avoid compiler warning "val not used" when handling void. */ class GenericValueCopy: public GenericValue { public: template<typename T> void operator,(const T& any); GenericValueCopy &operator()() { return *this; } }; template<typename T> void GenericValueCopy::operator,(const T& any) { *(GenericValue*)this = toValue(any); *(GenericValue*)this = clone(); } } } #endif // _QIMESSAGING_DETAILS_GENERICVALUE_HXX_
fix double-include guard
genericvalue.hxx: fix double-include guard Change-Id: I32fa1b5962a92ee6b85448974316685bdb685a88
C++
bsd-3-clause
vbarbaresi/libqi,aldebaran/libqi-java,bsautron/libqi,aldebaran/libqi,aldebaran/libqi-java,aldebaran/libqi,aldebaran/libqi,aldebaran/libqi-java
2f955a3da73953a46cedea703f409e8463ded9a8
modules/desktop_capture/window_capturer_unittest.cc
modules/desktop_capture/window_capturer_unittest.cc
/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/desktop_capture/window_capturer.h" #include "gtest/gtest.h" #include "webrtc/modules/desktop_capture/desktop_frame.h" #include "webrtc/modules/desktop_capture/desktop_region.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" namespace webrtc { class WindowCapturerTest : public testing::Test, public DesktopCapturer::Callback { public: void SetUp() OVERRIDE { capturer_.reset(WindowCapturer::Create()); } void TearDown() OVERRIDE { } // DesktopCapturer::Callback interface virtual SharedMemory* CreateSharedMemory(size_t size) OVERRIDE { return NULL; } virtual void OnCaptureCompleted(DesktopFrame* frame) OVERRIDE { frame_.reset(frame); } protected: scoped_ptr<WindowCapturer> capturer_; scoped_ptr<DesktopFrame> frame_; }; // Verify that we can enumerate windows. TEST_F(WindowCapturerTest, Enumerate) { WindowCapturer::WindowList windows; EXPECT_TRUE(capturer_->GetWindowList(&windows)); // Assume that there is at least one window. EXPECT_GT(windows.size(), 0U); // Verify that window titles are set. for (WindowCapturer::WindowList::iterator it = windows.begin(); it != windows.end(); ++it) { EXPECT_FALSE(it->title.empty()); } } // Verify we can capture a window. // // TODO(sergeyu): Currently this test just looks at the windows that already // exist. Ideally it should create a test window and capture from it, but there // is no easy cross-platform way to create new windows (potentially we could // have a python script showing Tk dialog, but launching code will differ // between platforms). TEST_F(WindowCapturerTest, Capture) { WindowCapturer::WindowList windows; capturer_->Start(this); EXPECT_TRUE(capturer_->GetWindowList(&windows)); // Verify that we can select and capture each window. for (WindowCapturer::WindowList::iterator it = windows.begin(); it != windows.end(); ++it) { frame_.reset(); if (capturer_->SelectWindow(it->id)) { capturer_->Capture(DesktopRegion()); } // If we failed to capture a window make sure it no longer exists. if (!frame_.get()) { WindowCapturer::WindowList new_list; EXPECT_TRUE(capturer_->GetWindowList(&new_list)); for (WindowCapturer::WindowList::iterator new_list_it = windows.begin(); new_list_it != windows.end(); ++new_list_it) { EXPECT_FALSE(it->id == new_list_it->id); } continue; } EXPECT_GT(frame_->size().width(), 0); EXPECT_GT(frame_->size().height(), 0); } } } // namespace webrtc
/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/desktop_capture/window_capturer.h" #include "gtest/gtest.h" #include "webrtc/modules/desktop_capture/desktop_frame.h" #include "webrtc/modules/desktop_capture/desktop_region.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" namespace webrtc { class WindowCapturerTest : public testing::Test, public DesktopCapturer::Callback { public: void SetUp() OVERRIDE { capturer_.reset(WindowCapturer::Create()); } void TearDown() OVERRIDE { } // DesktopCapturer::Callback interface virtual SharedMemory* CreateSharedMemory(size_t size) OVERRIDE { return NULL; } virtual void OnCaptureCompleted(DesktopFrame* frame) OVERRIDE { frame_.reset(frame); } protected: scoped_ptr<WindowCapturer> capturer_; scoped_ptr<DesktopFrame> frame_; }; #if defined(WEBRTC_WIN) // Verify that we can enumerate windows. TEST_F(WindowCapturerTest, Enumerate) { WindowCapturer::WindowList windows; EXPECT_TRUE(capturer_->GetWindowList(&windows)); // Assume that there is at least one window. EXPECT_GT(windows.size(), 0U); // Verify that window titles are set. for (WindowCapturer::WindowList::iterator it = windows.begin(); it != windows.end(); ++it) { EXPECT_FALSE(it->title.empty()); } } // Verify we can capture a window. // // TODO(sergeyu): Currently this test just looks at the windows that already // exist. Ideally it should create a test window and capture from it, but there // is no easy cross-platform way to create new windows (potentially we could // have a python script showing Tk dialog, but launching code will differ // between platforms). TEST_F(WindowCapturerTest, Capture) { WindowCapturer::WindowList windows; capturer_->Start(this); EXPECT_TRUE(capturer_->GetWindowList(&windows)); // Verify that we can select and capture each window. for (WindowCapturer::WindowList::iterator it = windows.begin(); it != windows.end(); ++it) { frame_.reset(); if (capturer_->SelectWindow(it->id)) { capturer_->Capture(DesktopRegion()); } // If we failed to capture a window make sure it no longer exists. if (!frame_.get()) { WindowCapturer::WindowList new_list; EXPECT_TRUE(capturer_->GetWindowList(&new_list)); for (WindowCapturer::WindowList::iterator new_list_it = windows.begin(); new_list_it != windows.end(); ++new_list_it) { EXPECT_FALSE(it->id == new_list_it->id); } continue; } EXPECT_GT(frame_->size().width(), 0); EXPECT_GT(frame_->size().height(), 0); } } #endif // defined(WEBRTC_WIN) } // namespace webrtc
Disable WindowCapturer tests on OSX and Linux
Disable WindowCapturer tests on OSX and Linux [email protected] Review URL: https://webrtc-codereview.appspot.com/1533004 Cr-Mirrored-From: https://chromium.googlesource.com/external/webrtc Cr-Mirrored-Commit: 6ec25073e3b3c68731c24bf60ab65c02d263cdee
C++
bsd-3-clause
sippet/webrtc,sippet/webrtc,sippet/webrtc,sippet/webrtc,sippet/webrtc,sippet/webrtc
93b8211690cdfae288e3fb400e7f4765ac7d49f2
trunk/extension/src/svn.cpp
trunk/extension/src/svn.cpp
/******************************************************************************\ * File: svn.cpp * Purpose: Implementation of wxExSVN class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/config.h> #include <wx/extension/svn.h> #include <wx/extension/configdlg.h> #include <wx/extension/defs.h> #include <wx/extension/log.h> #include <wx/extension/stc.h> #include <wx/extension/util.h> wxExSVN* wxExSVN::m_Self = NULL; #if wxUSE_GUI wxExSTCEntryDialog* wxExSVN::m_STCEntryDialog = NULL; #endif wxString wxExSVN::m_UsageKey; wxExSVN::wxExSVN() : m_Type(SVN_NONE) , m_FullPath(wxEmptyString) { Initialize(); } wxExSVN::wxExSVN(int command_id, const wxString& fullpath) : m_Type(GetType(command_id)) , m_FullPath(fullpath) { Initialize(); } wxExSVN::wxExSVN(wxExSVNType type, const wxString& fullpath) : m_Type(type) , m_FullPath(fullpath) { Initialize(); } #if wxUSE_GUI int wxExSVN::ConfigDialog( wxWindow* parent, const wxString& title) const { std::vector<wxExConfigItem> v; v.push_back(wxExConfigItem()); // a spacer v.push_back(wxExConfigItem(m_UsageKey, CONFIG_CHECKBOX)); v.push_back(wxExConfigItem(_("Comparator"), CONFIG_FILEPICKERCTRL)); return wxExConfigDialog(parent, v, title).ShowModal(); } #endif bool wxExSVN::DirExists(const wxFileName& filename) const { wxFileName path(filename); path.AppendDir(".svn"); return path.DirExists(); } wxStandardID wxExSVN::Execute() { wxASSERT(m_Type != SVN_NONE); const wxString cwd = wxGetCwd(); wxString file; if (m_FullPath.empty()) { if (!wxSetWorkingDirectory(wxExConfigFirstOf(_("Base folder")))) { m_Output = _("Cannot set working directory"); return wxID_ABORT; } if (m_Type == SVN_ADD) { file = wxExConfigFirstOf(_("Path")); } } else { file = " \"" + m_FullPath + "\""; } wxString comment; if (m_Type == SVN_COMMIT) { comment = " -m \"" + wxExConfigFirstOf(_("Revision comment")) + "\""; } wxString flags; wxString subcommand; if (UseSubcommand()) { subcommand = wxConfigBase::Get()->Read(_("Subcommand")); if (!subcommand.empty()) { subcommand = " " + subcommand; } } if (UseFlags()) { flags = wxConfigBase::Get()->Read(_("Flags")); if (!flags.empty()) { flags = " " + flags; } } m_CommandWithFlags = m_Command + flags; const wxString commandline = "svn " + m_Command + subcommand + flags + comment + file; wxArrayString output; wxArrayString errors; m_Output.clear(); if (wxExecute( commandline, output, errors) == -1) { if (m_Output.empty()) { m_Output = "Could not execute: " + commandline; } m_ReturnCode = wxID_ABORT; return m_ReturnCode; } wxExLog::Get()->Log(commandline); if (m_FullPath.empty()) { wxSetWorkingDirectory(cwd); } // First output the errors. for (size_t i = 0; i < errors.GetCount(); i++) { m_Output += errors[i] + "\n"; } // Then the normal output, will be empty if there are errors. for (size_t j = 0; j < output.GetCount(); j++) { m_Output += output[j] + "\n"; } return wxID_OK; } #if wxUSE_GUI wxStandardID wxExSVN::Execute(wxWindow* parent) { wxASSERT(parent != NULL); // Key SVN is already used, so use other name. const wxString svn_flags_name = wxString::Format("svnflags/name%d", m_Type); std::vector<wxExConfigItem> v; if (m_Type == SVN_COMMIT) { v.push_back(wxExConfigItem( _("Revision comment"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } if (m_FullPath.empty() && m_Type != SVN_HELP) { v.push_back(wxExConfigItem( _("Base folder"), CONFIG_COMBOBOXDIR, wxEmptyString, true)); // required if (m_Type == SVN_ADD) { v.push_back(wxExConfigItem( _("Path"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } } if (UseFlags()) { wxConfigBase::Get()->Write( _("Flags"), wxConfigBase::Get()->Read(svn_flags_name)); v.push_back(wxExConfigItem(_("Flags"))); } if (UseSubcommand()) { v.push_back(wxExConfigItem(_("Subcommand"))); } m_ReturnCode = (wxStandardID)wxExConfigDialog(parent, v, m_Caption).ShowModal(); if (m_ReturnCode == wxID_CANCEL) { return m_ReturnCode; } if (UseFlags()) { wxConfigBase::Get()->Write(svn_flags_name, wxConfigBase::Get()->Read(svn_flags_name)); } return Execute(); } #endif #if wxUSE_GUI wxStandardID wxExSVN::ExecuteAndShowOutput(wxWindow* parent) { // We must have a parent. wxASSERT(parent != NULL); // If an error occurred, already shown by wxExecute itself. if (Execute(parent) == wxID_OK) { ShowOutput(parent); } return m_ReturnCode; } #endif wxExSVN* wxExSVN::Get(bool createOnDemand) { if (m_Self == NULL && createOnDemand) { m_Self = new wxExSVN; if (!wxConfigBase::Get()->Exists(m_UsageKey)) { if (!wxConfigBase::Get()->Write(m_UsageKey, true)) { wxFAIL; } } } return m_Self; } wxExSVNType wxExSVN::GetType(int command_id) const { switch (command_id) { case ID_EDIT_SVN_ADD: return SVN_ADD; break; case ID_EDIT_SVN_BLAME: return SVN_BLAME; break; case ID_EDIT_SVN_CAT: return SVN_CAT; break; case ID_EDIT_SVN_COMMIT: return SVN_COMMIT; break; case ID_EDIT_SVN_DIFF: return SVN_DIFF; break; case ID_EDIT_SVN_HELP: return SVN_HELP; break; case ID_EDIT_SVN_INFO: return SVN_INFO; break; case ID_EDIT_SVN_LOG: return SVN_LOG; break; case ID_EDIT_SVN_PROPLIST: return SVN_PROPLIST; break; case ID_EDIT_SVN_PROPSET: return SVN_PROPSET; break; case ID_EDIT_SVN_REVERT: return SVN_REVERT; break; case ID_EDIT_SVN_STAT: return SVN_STAT; break; case ID_EDIT_SVN_UPDATE: return SVN_UPDATE; break; default: wxFAIL; return SVN_NONE; break; } } void wxExSVN::Initialize() { switch (m_Type) { case SVN_NONE: m_Caption = ""; break; case SVN_ADD: m_Caption = "SVN Add"; break; case SVN_BLAME: m_Caption = "SVN Blame"; break; case SVN_CAT: m_Caption = "SVN Cat"; break; case SVN_COMMIT: m_Caption = "SVN Commit"; break; case SVN_DIFF: m_Caption = "SVN Diff"; break; case SVN_HELP: m_Caption = "SVN Help"; break; case SVN_INFO: m_Caption = "SVN Info"; break; case SVN_LOG: m_Caption = "SVN Log"; break; case SVN_LS: m_Caption = "SVN Ls"; break; case SVN_PROPLIST: m_Caption = "SVN Proplist"; break; case SVN_PROPSET: m_Caption = "SVN Propset"; break; case SVN_REVERT: m_Caption = "SVN Revert"; break; case SVN_STAT: m_Caption = "SVN Stat"; break; case SVN_UPDATE: m_Caption = "SVN Update"; break; default: wxFAIL; break; } m_Command = m_Caption.AfterFirst(' ').Lower(); // Currently no flags, as no command was executed. m_CommandWithFlags = m_Command; m_Output.clear(); m_ReturnCode = wxID_NONE; m_UsageKey = _("Use SVN"); } wxExSVN* wxExSVN::Set(wxExSVN* svn) { wxExSVN* old = m_Self; m_Self = svn; return old; } #if wxUSE_GUI void wxExSVN::ShowOutput(wxWindow* parent) const { switch (m_ReturnCode) { case wxID_CANCEL: break; case wxID_ABORT: wxMessageBox(m_Output); break; case wxID_OK: { wxString caption = m_Caption; if (m_Type != SVN_HELP) { caption += " " + (!m_FullPath.empty() ? wxFileName(m_FullPath).GetFullName(): wxExConfigFirstOf(_("Base folder"))); } // Create a dialog for contents. if (m_STCEntryDialog == NULL) { m_STCEntryDialog = new wxExSTCEntryDialog( parent, caption, m_Output, wxEmptyString, wxOK, wxID_ANY, wxDefaultPosition, wxSize(575, 250)); } else { m_STCEntryDialog->SetText(m_Output); m_STCEntryDialog->SetTitle(caption); // Reset a previous lexer. if (!m_STCEntryDialog->GetLexer().empty()) { m_STCEntryDialog->SetLexer(wxEmptyString); } } // Add a lexer if we specified a path, asked for cat or blame // and there is a lexer. if ( !m_FullPath.empty() && (m_Type == SVN_CAT || m_Type == SVN_BLAME)) { const wxExFileName fn(m_FullPath); if (!fn.GetLexer().GetScintillaLexer().empty()) { m_STCEntryDialog->SetLexer(fn.GetLexer().GetScintillaLexer()); } } m_STCEntryDialog->Show(); } break; default: wxFAIL; break; } } #endif bool wxExSVN::Use() const { return wxConfigBase::Get()->ReadBool(m_UsageKey, true); } bool wxExSVN::UseFlags() const { return m_Type != SVN_UPDATE && m_Type != SVN_HELP; } bool wxExSVN::UseSubcommand() const { return m_Type == SVN_HELP; }
/******************************************************************************\ * File: svn.cpp * Purpose: Implementation of wxExSVN class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/config.h> #include <wx/extension/svn.h> #include <wx/extension/configdlg.h> #include <wx/extension/defs.h> #include <wx/extension/log.h> #include <wx/extension/stc.h> #include <wx/extension/util.h> wxExSVN* wxExSVN::m_Self = NULL; #if wxUSE_GUI wxExSTCEntryDialog* wxExSVN::m_STCEntryDialog = NULL; #endif wxString wxExSVN::m_UsageKey; wxExSVN::wxExSVN() : m_Type(SVN_NONE) , m_FullPath(wxEmptyString) { Initialize(); } wxExSVN::wxExSVN(int command_id, const wxString& fullpath) : m_Type(GetType(command_id)) , m_FullPath(fullpath) { Initialize(); } wxExSVN::wxExSVN(wxExSVNType type, const wxString& fullpath) : m_Type(type) , m_FullPath(fullpath) { Initialize(); } #if wxUSE_GUI int wxExSVN::ConfigDialog( wxWindow* parent, const wxString& title) const { std::vector<wxExConfigItem> v; v.push_back(wxExConfigItem()); // a spacer v.push_back(wxExConfigItem(m_UsageKey, CONFIG_CHECKBOX)); v.push_back(wxExConfigItem(_("Comparator"), CONFIG_FILEPICKERCTRL)); return wxExConfigDialog(parent, v, title).ShowModal(); } #endif bool wxExSVN::DirExists(const wxFileName& filename) const { wxFileName path(filename); path.AppendDir(".svn"); return path.DirExists(); } wxStandardID wxExSVN::Execute() { wxASSERT(m_Type != SVN_NONE); const wxString cwd = wxGetCwd(); wxString file; if (m_FullPath.empty()) { if (!wxSetWorkingDirectory(wxExConfigFirstOf(_("Base folder")))) { m_Output = _("Cannot set working directory"); m_ReturnCode = wxID_ABORT; return m_ReturnCode; } if (m_Type == SVN_ADD) { file = wxExConfigFirstOf(_("Path")); } } else { file = " \"" + m_FullPath + "\""; } wxString comment; if (m_Type == SVN_COMMIT) { comment = " -m \"" + wxExConfigFirstOf(_("Revision comment")) + "\""; } wxString flags; wxString subcommand; if (UseSubcommand()) { subcommand = wxConfigBase::Get()->Read(_("Subcommand")); if (!subcommand.empty()) { subcommand = " " + subcommand; } } if (UseFlags()) { flags = wxConfigBase::Get()->Read(_("Flags")); if (!flags.empty()) { flags = " " + flags; } } m_CommandWithFlags = m_Command + flags; const wxString commandline = "svn " + m_Command + subcommand + flags + comment + file; wxArrayString output; wxArrayString errors; m_Output.clear(); if (wxExecute( commandline, output, errors) == -1) { if (m_Output.empty()) { m_Output = "Could not execute: " + commandline; } m_ReturnCode = wxID_ABORT; return m_ReturnCode; } wxExLog::Get()->Log(commandline); if (m_FullPath.empty()) { wxSetWorkingDirectory(cwd); } // First output the errors. for (size_t i = 0; i < errors.GetCount(); i++) { m_Output += errors[i] + "\n"; } // Then the normal output, will be empty if there are errors. for (size_t j = 0; j < output.GetCount(); j++) { m_Output += output[j] + "\n"; } m_ReturnCode = wxID_OK; return m_ReturnCode; } #if wxUSE_GUI wxStandardID wxExSVN::Execute(wxWindow* parent) { wxASSERT(parent != NULL); // Key SVN is already used, so use other name. const wxString svn_flags_name = wxString::Format("svnflags/name%d", m_Type); std::vector<wxExConfigItem> v; if (m_Type == SVN_COMMIT) { v.push_back(wxExConfigItem( _("Revision comment"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } if (m_FullPath.empty() && m_Type != SVN_HELP) { v.push_back(wxExConfigItem( _("Base folder"), CONFIG_COMBOBOXDIR, wxEmptyString, true)); // required if (m_Type == SVN_ADD) { v.push_back(wxExConfigItem( _("Path"), CONFIG_COMBOBOX, wxEmptyString, true)); // required } } if (UseFlags()) { wxConfigBase::Get()->Write( _("Flags"), wxConfigBase::Get()->Read(svn_flags_name)); v.push_back(wxExConfigItem(_("Flags"))); } if (UseSubcommand()) { v.push_back(wxExConfigItem(_("Subcommand"))); } m_ReturnCode = (wxStandardID)wxExConfigDialog(parent, v, m_Caption).ShowModal(); if (m_ReturnCode == wxID_CANCEL) { return m_ReturnCode; } if (UseFlags()) { wxConfigBase::Get()->Write(svn_flags_name, wxConfigBase::Get()->Read(svn_flags_name)); } return Execute(); } #endif #if wxUSE_GUI wxStandardID wxExSVN::ExecuteAndShowOutput(wxWindow* parent) { // We must have a parent. wxASSERT(parent != NULL); // If an error occurred, already shown by wxExecute itself. if (Execute(parent) == wxID_OK) { ShowOutput(parent); } return m_ReturnCode; } #endif wxExSVN* wxExSVN::Get(bool createOnDemand) { if (m_Self == NULL && createOnDemand) { m_Self = new wxExSVN; if (!wxConfigBase::Get()->Exists(m_UsageKey)) { if (!wxConfigBase::Get()->Write(m_UsageKey, true)) { wxFAIL; } } } return m_Self; } wxExSVNType wxExSVN::GetType(int command_id) const { switch (command_id) { case ID_EDIT_SVN_ADD: return SVN_ADD; break; case ID_EDIT_SVN_BLAME: return SVN_BLAME; break; case ID_EDIT_SVN_CAT: return SVN_CAT; break; case ID_EDIT_SVN_COMMIT: return SVN_COMMIT; break; case ID_EDIT_SVN_DIFF: return SVN_DIFF; break; case ID_EDIT_SVN_HELP: return SVN_HELP; break; case ID_EDIT_SVN_INFO: return SVN_INFO; break; case ID_EDIT_SVN_LOG: return SVN_LOG; break; case ID_EDIT_SVN_PROPLIST: return SVN_PROPLIST; break; case ID_EDIT_SVN_PROPSET: return SVN_PROPSET; break; case ID_EDIT_SVN_REVERT: return SVN_REVERT; break; case ID_EDIT_SVN_STAT: return SVN_STAT; break; case ID_EDIT_SVN_UPDATE: return SVN_UPDATE; break; default: wxFAIL; return SVN_NONE; break; } } void wxExSVN::Initialize() { switch (m_Type) { case SVN_NONE: m_Caption = ""; break; case SVN_ADD: m_Caption = "SVN Add"; break; case SVN_BLAME: m_Caption = "SVN Blame"; break; case SVN_CAT: m_Caption = "SVN Cat"; break; case SVN_COMMIT: m_Caption = "SVN Commit"; break; case SVN_DIFF: m_Caption = "SVN Diff"; break; case SVN_HELP: m_Caption = "SVN Help"; break; case SVN_INFO: m_Caption = "SVN Info"; break; case SVN_LOG: m_Caption = "SVN Log"; break; case SVN_LS: m_Caption = "SVN Ls"; break; case SVN_PROPLIST: m_Caption = "SVN Proplist"; break; case SVN_PROPSET: m_Caption = "SVN Propset"; break; case SVN_REVERT: m_Caption = "SVN Revert"; break; case SVN_STAT: m_Caption = "SVN Stat"; break; case SVN_UPDATE: m_Caption = "SVN Update"; break; default: wxFAIL; break; } m_Command = m_Caption.AfterFirst(' ').Lower(); // Currently no flags, as no command was executed. m_CommandWithFlags = m_Command; m_Output.clear(); m_ReturnCode = wxID_NONE; m_UsageKey = _("Use SVN"); } wxExSVN* wxExSVN::Set(wxExSVN* svn) { wxExSVN* old = m_Self; m_Self = svn; return old; } #if wxUSE_GUI void wxExSVN::ShowOutput(wxWindow* parent) const { switch (m_ReturnCode) { case wxID_CANCEL: break; case wxID_ABORT: wxMessageBox(m_Output); break; case wxID_OK: { wxString caption = m_Caption; if (m_Type != SVN_HELP) { caption += " " + (!m_FullPath.empty() ? wxFileName(m_FullPath).GetFullName(): wxExConfigFirstOf(_("Base folder"))); } // Create a dialog for contents. if (m_STCEntryDialog == NULL) { m_STCEntryDialog = new wxExSTCEntryDialog( parent, caption, m_Output, wxEmptyString, wxOK, wxID_ANY, wxDefaultPosition, wxSize(575, 250)); } else { m_STCEntryDialog->SetText(m_Output); m_STCEntryDialog->SetTitle(caption); // Reset a previous lexer. if (!m_STCEntryDialog->GetLexer().empty()) { m_STCEntryDialog->SetLexer(wxEmptyString); } } // Add a lexer if we specified a path, asked for cat or blame // and there is a lexer. if ( !m_FullPath.empty() && (m_Type == SVN_CAT || m_Type == SVN_BLAME)) { const wxExFileName fn(m_FullPath); if (!fn.GetLexer().GetScintillaLexer().empty()) { m_STCEntryDialog->SetLexer(fn.GetLexer().GetScintillaLexer()); } } m_STCEntryDialog->Show(); } break; default: wxFAIL; break; } } #endif bool wxExSVN::Use() const { return wxConfigBase::Get()->ReadBool(m_UsageKey, true); } bool wxExSVN::UseFlags() const { return m_Type != SVN_UPDATE && m_Type != SVN_HELP; } bool wxExSVN::UseSubcommand() const { return m_Type == SVN_HELP; }
fix for return code
fix for return code git-svn-id: e171abefef93db0a74257c7d87d5b6400fe00c1f@2114 f22100f3-aa73-48fe-a4fb-fd497bb32605
C++
mit
antonvw/wxExtension,antonvw/wxExtension,antonvw/wxExtension
5c00b4af61bb6abff2fb28ddd904808623a7db23
tools/gold/gold-plugin.cpp
tools/gold/gold-plugin.cpp
//===-- gold-plugin.cpp - Plugin to gold for Link Time Optimization ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is a gold plugin for LLVM. It provides an LLVM implementation of the // interface described in http://gcc.gnu.org/wiki/whopr/driver . // //===----------------------------------------------------------------------===// #include "llvm/Config/config.h" #include "plugin-api.h" #include "llvm-c/lto.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Errno.h" #include "llvm/System/Path.h" #include "llvm/System/Program.h" #include <cerrno> #include <cstdlib> #include <cstring> #include <fstream> #include <list> #include <vector> using namespace llvm; namespace { ld_plugin_status discard_message(int level, const char *format, ...) { // Die loudly. Recent versions of Gold pass ld_plugin_message as the first // callback in the transfer vector. This should never be called. abort(); } ld_plugin_add_symbols add_symbols = NULL; ld_plugin_get_symbols get_symbols = NULL; ld_plugin_add_input_file add_input_file = NULL; ld_plugin_message message = discard_message; int api_version = 0; int gold_version = 0; bool generate_api_file = false; const char *as_path = NULL; struct claimed_file { lto_module_t M; void *handle; std::vector<ld_plugin_symbol> syms; }; lto_codegen_model output_type = LTO_CODEGEN_PIC_MODEL_STATIC; std::list<claimed_file> Modules; std::vector<sys::Path> Cleanup; } ld_plugin_status claim_file_hook(const ld_plugin_input_file *file, int *claimed); ld_plugin_status all_symbols_read_hook(void); ld_plugin_status cleanup_hook(void); extern "C" ld_plugin_status onload(ld_plugin_tv *tv); ld_plugin_status onload(ld_plugin_tv *tv) { // We're given a pointer to the first transfer vector. We read through them // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values // contain pointers to functions that we need to call to register our own // hooks. The others are addresses of functions we can use to call into gold // for services. bool registeredClaimFile = false; bool registeredAllSymbolsRead = false; bool registeredCleanup = false; for (; tv->tv_tag != LDPT_NULL; ++tv) { switch (tv->tv_tag) { case LDPT_API_VERSION: api_version = tv->tv_u.tv_val; break; case LDPT_GOLD_VERSION: // major * 100 + minor gold_version = tv->tv_u.tv_val; break; case LDPT_LINKER_OUTPUT: switch (tv->tv_u.tv_val) { case LDPO_REL: // .o case LDPO_DYN: // .so output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC; break; case LDPO_EXEC: // .exe output_type = LTO_CODEGEN_PIC_MODEL_STATIC; break; default: (*message)(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val); return LDPS_ERR; } // TODO: add an option to disable PIC. //output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC; break; case LDPT_OPTION: if (strcmp("generate-api-file", tv->tv_u.tv_string) == 0) { generate_api_file = true; } else if (strncmp("as=", tv->tv_u.tv_string, 3) == 0) { if (as_path) { (*message)(LDPL_WARNING, "Path to as specified twice. " "Discarding %s", tv->tv_u.tv_string); } else { as_path = strdup(tv->tv_u.tv_string + 3); } } else { (*message)(LDPL_WARNING, "Ignoring flag %s", tv->tv_u.tv_string); } break; case LDPT_REGISTER_CLAIM_FILE_HOOK: { ld_plugin_register_claim_file callback; callback = tv->tv_u.tv_register_claim_file; if ((*callback)(claim_file_hook) != LDPS_OK) return LDPS_ERR; registeredClaimFile = true; } break; case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: { ld_plugin_register_all_symbols_read callback; callback = tv->tv_u.tv_register_all_symbols_read; if ((*callback)(all_symbols_read_hook) != LDPS_OK) return LDPS_ERR; registeredAllSymbolsRead = true; } break; case LDPT_REGISTER_CLEANUP_HOOK: { ld_plugin_register_cleanup callback; callback = tv->tv_u.tv_register_cleanup; if ((*callback)(cleanup_hook) != LDPS_OK) return LDPS_ERR; registeredCleanup = true; } break; case LDPT_ADD_SYMBOLS: add_symbols = tv->tv_u.tv_add_symbols; break; case LDPT_GET_SYMBOLS: get_symbols = tv->tv_u.tv_get_symbols; break; case LDPT_ADD_INPUT_FILE: add_input_file = tv->tv_u.tv_add_input_file; break; case LDPT_MESSAGE: message = tv->tv_u.tv_message; break; default: break; } } if (!registeredClaimFile) { (*message)(LDPL_ERROR, "register_claim_file not passed to LLVMgold."); return LDPS_ERR; } if (!add_symbols) { (*message)(LDPL_ERROR, "add_symbols not passed to LLVMgold."); return LDPS_ERR; } return LDPS_OK; } /// claim_file_hook - called by gold to see whether this file is one that /// our plugin can handle. We'll try to open it and register all the symbols /// with add_symbol if possible. ld_plugin_status claim_file_hook(const ld_plugin_input_file *file, int *claimed) { void *buf = NULL; if (file->offset) { // Gold has found what might be IR part-way inside of a file, such as // an .a archive. if (lseek(file->fd, file->offset, SEEK_SET) == -1) { (*message)(LDPL_ERROR, "Failed to seek to archive member of %s at offset %d: %s\n", file->name, file->offset, sys::StrError(errno).c_str()); return LDPS_ERR; } buf = malloc(file->filesize); if (!buf) { (*message)(LDPL_ERROR, "Failed to allocate buffer for archive member of size: %d\n", file->filesize); return LDPS_ERR; } if (read(file->fd, buf, file->filesize) != file->filesize) { (*message)(LDPL_ERROR, "Failed to read archive member of %s at offset %d: %s\n", file->name, file->offset, sys::StrError(errno).c_str()); free(buf); return LDPS_ERR; } if (!lto_module_is_object_file_in_memory(buf, file->filesize)) { free(buf); return LDPS_OK; } } else if (!lto_module_is_object_file(file->name)) return LDPS_OK; *claimed = 1; Modules.resize(Modules.size() + 1); claimed_file &cf = Modules.back(); cf.M = buf ? lto_module_create_from_memory(buf, file->filesize) : lto_module_create(file->name); free(buf); if (!cf.M) { (*message)(LDPL_ERROR, "Failed to create LLVM module: %s", lto_get_error_message()); return LDPS_ERR; } cf.handle = file->handle; unsigned sym_count = lto_module_get_num_symbols(cf.M); cf.syms.reserve(sym_count); for (unsigned i = 0; i != sym_count; ++i) { lto_symbol_attributes attrs = lto_module_get_symbol_attribute(cf.M, i); if ((attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL) continue; cf.syms.push_back(ld_plugin_symbol()); ld_plugin_symbol &sym = cf.syms.back(); sym.name = const_cast<char *>(lto_module_get_symbol_name(cf.M, i)); sym.version = NULL; int scope = attrs & LTO_SYMBOL_SCOPE_MASK; switch (scope) { case LTO_SYMBOL_SCOPE_HIDDEN: sym.visibility = LDPV_HIDDEN; break; case LTO_SYMBOL_SCOPE_PROTECTED: sym.visibility = LDPV_PROTECTED; break; case 0: // extern case LTO_SYMBOL_SCOPE_DEFAULT: sym.visibility = LDPV_DEFAULT; break; default: (*message)(LDPL_ERROR, "Unknown scope attribute: %d", scope); return LDPS_ERR; } int definition = attrs & LTO_SYMBOL_DEFINITION_MASK; switch (definition) { case LTO_SYMBOL_DEFINITION_REGULAR: sym.def = LDPK_DEF; break; case LTO_SYMBOL_DEFINITION_UNDEFINED: sym.def = LDPK_UNDEF; break; case LTO_SYMBOL_DEFINITION_TENTATIVE: sym.def = LDPK_COMMON; break; case LTO_SYMBOL_DEFINITION_WEAK: sym.def = LDPK_WEAKDEF; break; case LTO_SYMBOL_DEFINITION_WEAKUNDEF: sym.def = LDPK_WEAKUNDEF; break; default: (*message)(LDPL_ERROR, "Unknown definition attribute: %d", definition); return LDPS_ERR; } // LLVM never emits COMDAT. sym.size = 0; sym.comdat_key = NULL; sym.resolution = LDPR_UNKNOWN; } cf.syms.reserve(cf.syms.size()); if (!cf.syms.empty()) { if ((*add_symbols)(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) { (*message)(LDPL_ERROR, "Unable to add symbols!"); return LDPS_ERR; } } return LDPS_OK; } /// all_symbols_read_hook - gold informs us that all symbols have been read. /// At this point, we use get_symbols to see if any of our definitions have /// been overridden by a native object file. Then, perform optimization and /// codegen. ld_plugin_status all_symbols_read_hook(void) { lto_code_gen_t cg = lto_codegen_create(); for (std::list<claimed_file>::iterator I = Modules.begin(), E = Modules.end(); I != E; ++I) lto_codegen_add_module(cg, I->M); std::ofstream api_file; if (generate_api_file) { api_file.open("apifile.txt", std::ofstream::out | std::ofstream::trunc); if (!api_file.is_open()) { (*message)(LDPL_FATAL, "Unable to open apifile.txt for writing."); abort(); } } // If we don't preserve any symbols, libLTO will assume that all symbols are // needed. Keep all symbols unless we're producing a final executable. if (output_type == LTO_CODEGEN_PIC_MODEL_STATIC) { bool anySymbolsPreserved = false; for (std::list<claimed_file>::iterator I = Modules.begin(), E = Modules.end(); I != E; ++I) { (*get_symbols)(I->handle, I->syms.size(), &I->syms[0]); for (unsigned i = 0, e = I->syms.size(); i != e; i++) { if (I->syms[i].resolution == LDPR_PREVAILING_DEF || (I->syms[i].def == LDPK_COMMON && I->syms[i].resolution == LDPR_RESOLVED_IR)) { lto_codegen_add_must_preserve_symbol(cg, I->syms[i].name); anySymbolsPreserved = true; if (generate_api_file) api_file << I->syms[i].name << "\n"; } } } if (generate_api_file) api_file.close(); if (!anySymbolsPreserved) { // This entire file is unnecessary! lto_codegen_dispose(cg); return LDPS_OK; } } lto_codegen_set_pic_model(cg, output_type); lto_codegen_set_debug_model(cg, LTO_DEBUG_MODEL_DWARF); if (as_path) { sys::Path p = sys::Program::FindProgramByName(as_path); lto_codegen_set_assembler_path(cg, p.c_str()); } size_t bufsize = 0; const char *buffer = static_cast<const char *>(lto_codegen_compile(cg, &bufsize)); std::string ErrMsg; sys::Path uniqueObjPath("/tmp/llvmgold.o"); if (uniqueObjPath.createTemporaryFileOnDisk(true, &ErrMsg)) { (*message)(LDPL_ERROR, "%s", ErrMsg.c_str()); return LDPS_ERR; } raw_fd_ostream *objFile = new raw_fd_ostream(uniqueObjPath.c_str(), ErrMsg, raw_fd_ostream::F_Binary); if (!ErrMsg.empty()) { delete objFile; (*message)(LDPL_ERROR, "%s", ErrMsg.c_str()); return LDPS_ERR; } objFile->write(buffer, bufsize); objFile->close(); lto_codegen_dispose(cg); if ((*add_input_file)(const_cast<char*>(uniqueObjPath.c_str())) != LDPS_OK) { (*message)(LDPL_ERROR, "Unable to add .o file to the link."); (*message)(LDPL_ERROR, "File left behind in: %s", uniqueObjPath.c_str()); return LDPS_ERR; } Cleanup.push_back(uniqueObjPath); return LDPS_OK; } ld_plugin_status cleanup_hook(void) { std::string ErrMsg; for (int i = 0, e = Cleanup.size(); i != e; ++i) if (Cleanup[i].eraseFromDisk(false, &ErrMsg)) (*message)(LDPL_ERROR, "Failed to delete '%s': %s", Cleanup[i].c_str(), ErrMsg.c_str()); return LDPS_OK; }
//===-- gold-plugin.cpp - Plugin to gold for Link Time Optimization ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is a gold plugin for LLVM. It provides an LLVM implementation of the // interface described in http://gcc.gnu.org/wiki/whopr/driver . // //===----------------------------------------------------------------------===// #include "llvm/Config/config.h" #include "plugin-api.h" #include "llvm-c/lto.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Errno.h" #include "llvm/System/Path.h" #include "llvm/System/Program.h" #include <cerrno> #include <cstdlib> #include <cstring> #include <fstream> #include <list> #include <vector> using namespace llvm; namespace { ld_plugin_status discard_message(int level, const char *format, ...) { // Die loudly. Recent versions of Gold pass ld_plugin_message as the first // callback in the transfer vector. This should never be called. abort(); } ld_plugin_add_symbols add_symbols = NULL; ld_plugin_get_symbols get_symbols = NULL; ld_plugin_add_input_file add_input_file = NULL; ld_plugin_message message = discard_message; int api_version = 0; int gold_version = 0; struct claimed_file { lto_module_t M; void *handle; std::vector<ld_plugin_symbol> syms; }; lto_codegen_model output_type = LTO_CODEGEN_PIC_MODEL_STATIC; std::list<claimed_file> Modules; std::vector<sys::Path> Cleanup; } namespace options { bool generate_api_file = false; const char *as_path = NULL; // Additional options to pass into the code generator. // Note: This array will contain all plugin options which are not claimed // as plugin exclusive to pass to the code generator. // For example, "generate-api-file" and "as"options are for the plugin // use only and will not be passed. std::vector<std::string> extra; void process_plugin_option(const char* opt) { if (opt == NULL) return; if (strcmp("generate-api-file", opt) == 0) { generate_api_file = true; } else if (strncmp("as=", opt, 3) == 0) { if (as_path) { (*message)(LDPL_WARNING, "Path to as specified twice. " "Discarding %s", opt); } else { as_path = strdup(opt + 3); } } else { // Save this option to pass to the code generator. extra.push_back(std::string(opt)); } } } ld_plugin_status claim_file_hook(const ld_plugin_input_file *file, int *claimed); ld_plugin_status all_symbols_read_hook(void); ld_plugin_status cleanup_hook(void); extern "C" ld_plugin_status onload(ld_plugin_tv *tv); ld_plugin_status onload(ld_plugin_tv *tv) { // We're given a pointer to the first transfer vector. We read through them // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values // contain pointers to functions that we need to call to register our own // hooks. The others are addresses of functions we can use to call into gold // for services. bool registeredClaimFile = false; bool registeredAllSymbolsRead = false; bool registeredCleanup = false; for (; tv->tv_tag != LDPT_NULL; ++tv) { switch (tv->tv_tag) { case LDPT_API_VERSION: api_version = tv->tv_u.tv_val; break; case LDPT_GOLD_VERSION: // major * 100 + minor gold_version = tv->tv_u.tv_val; break; case LDPT_LINKER_OUTPUT: switch (tv->tv_u.tv_val) { case LDPO_REL: // .o case LDPO_DYN: // .so output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC; break; case LDPO_EXEC: // .exe output_type = LTO_CODEGEN_PIC_MODEL_STATIC; break; default: (*message)(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val); return LDPS_ERR; } // TODO: add an option to disable PIC. //output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC; break; case LDPT_OPTION: options::process_plugin_option(tv->tv_u.tv_string); break; case LDPT_REGISTER_CLAIM_FILE_HOOK: { ld_plugin_register_claim_file callback; callback = tv->tv_u.tv_register_claim_file; if ((*callback)(claim_file_hook) != LDPS_OK) return LDPS_ERR; registeredClaimFile = true; } break; case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: { ld_plugin_register_all_symbols_read callback; callback = tv->tv_u.tv_register_all_symbols_read; if ((*callback)(all_symbols_read_hook) != LDPS_OK) return LDPS_ERR; registeredAllSymbolsRead = true; } break; case LDPT_REGISTER_CLEANUP_HOOK: { ld_plugin_register_cleanup callback; callback = tv->tv_u.tv_register_cleanup; if ((*callback)(cleanup_hook) != LDPS_OK) return LDPS_ERR; registeredCleanup = true; } break; case LDPT_ADD_SYMBOLS: add_symbols = tv->tv_u.tv_add_symbols; break; case LDPT_GET_SYMBOLS: get_symbols = tv->tv_u.tv_get_symbols; break; case LDPT_ADD_INPUT_FILE: add_input_file = tv->tv_u.tv_add_input_file; break; case LDPT_MESSAGE: message = tv->tv_u.tv_message; break; default: break; } } if (!registeredClaimFile) { (*message)(LDPL_ERROR, "register_claim_file not passed to LLVMgold."); return LDPS_ERR; } if (!add_symbols) { (*message)(LDPL_ERROR, "add_symbols not passed to LLVMgold."); return LDPS_ERR; } return LDPS_OK; } /// claim_file_hook - called by gold to see whether this file is one that /// our plugin can handle. We'll try to open it and register all the symbols /// with add_symbol if possible. ld_plugin_status claim_file_hook(const ld_plugin_input_file *file, int *claimed) { void *buf = NULL; if (file->offset) { // Gold has found what might be IR part-way inside of a file, such as // an .a archive. if (lseek(file->fd, file->offset, SEEK_SET) == -1) { (*message)(LDPL_ERROR, "Failed to seek to archive member of %s at offset %d: %s\n", file->name, file->offset, sys::StrError(errno).c_str()); return LDPS_ERR; } buf = malloc(file->filesize); if (!buf) { (*message)(LDPL_ERROR, "Failed to allocate buffer for archive member of size: %d\n", file->filesize); return LDPS_ERR; } if (read(file->fd, buf, file->filesize) != file->filesize) { (*message)(LDPL_ERROR, "Failed to read archive member of %s at offset %d: %s\n", file->name, file->offset, sys::StrError(errno).c_str()); free(buf); return LDPS_ERR; } if (!lto_module_is_object_file_in_memory(buf, file->filesize)) { free(buf); return LDPS_OK; } } else if (!lto_module_is_object_file(file->name)) return LDPS_OK; *claimed = 1; Modules.resize(Modules.size() + 1); claimed_file &cf = Modules.back(); cf.M = buf ? lto_module_create_from_memory(buf, file->filesize) : lto_module_create(file->name); free(buf); if (!cf.M) { (*message)(LDPL_ERROR, "Failed to create LLVM module: %s", lto_get_error_message()); return LDPS_ERR; } cf.handle = file->handle; unsigned sym_count = lto_module_get_num_symbols(cf.M); cf.syms.reserve(sym_count); for (unsigned i = 0; i != sym_count; ++i) { lto_symbol_attributes attrs = lto_module_get_symbol_attribute(cf.M, i); if ((attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL) continue; cf.syms.push_back(ld_plugin_symbol()); ld_plugin_symbol &sym = cf.syms.back(); sym.name = const_cast<char *>(lto_module_get_symbol_name(cf.M, i)); sym.version = NULL; int scope = attrs & LTO_SYMBOL_SCOPE_MASK; switch (scope) { case LTO_SYMBOL_SCOPE_HIDDEN: sym.visibility = LDPV_HIDDEN; break; case LTO_SYMBOL_SCOPE_PROTECTED: sym.visibility = LDPV_PROTECTED; break; case 0: // extern case LTO_SYMBOL_SCOPE_DEFAULT: sym.visibility = LDPV_DEFAULT; break; default: (*message)(LDPL_ERROR, "Unknown scope attribute: %d", scope); return LDPS_ERR; } int definition = attrs & LTO_SYMBOL_DEFINITION_MASK; switch (definition) { case LTO_SYMBOL_DEFINITION_REGULAR: sym.def = LDPK_DEF; break; case LTO_SYMBOL_DEFINITION_UNDEFINED: sym.def = LDPK_UNDEF; break; case LTO_SYMBOL_DEFINITION_TENTATIVE: sym.def = LDPK_COMMON; break; case LTO_SYMBOL_DEFINITION_WEAK: sym.def = LDPK_WEAKDEF; break; case LTO_SYMBOL_DEFINITION_WEAKUNDEF: sym.def = LDPK_WEAKUNDEF; break; default: (*message)(LDPL_ERROR, "Unknown definition attribute: %d", definition); return LDPS_ERR; } // LLVM never emits COMDAT. sym.size = 0; sym.comdat_key = NULL; sym.resolution = LDPR_UNKNOWN; } cf.syms.reserve(cf.syms.size()); if (!cf.syms.empty()) { if ((*add_symbols)(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) { (*message)(LDPL_ERROR, "Unable to add symbols!"); return LDPS_ERR; } } return LDPS_OK; } /// all_symbols_read_hook - gold informs us that all symbols have been read. /// At this point, we use get_symbols to see if any of our definitions have /// been overridden by a native object file. Then, perform optimization and /// codegen. ld_plugin_status all_symbols_read_hook(void) { lto_code_gen_t cg = lto_codegen_create(); for (std::list<claimed_file>::iterator I = Modules.begin(), E = Modules.end(); I != E; ++I) lto_codegen_add_module(cg, I->M); std::ofstream api_file; if (options::generate_api_file) { api_file.open("apifile.txt", std::ofstream::out | std::ofstream::trunc); if (!api_file.is_open()) { (*message)(LDPL_FATAL, "Unable to open apifile.txt for writing."); abort(); } } // If we don't preserve any symbols, libLTO will assume that all symbols are // needed. Keep all symbols unless we're producing a final executable. if (output_type == LTO_CODEGEN_PIC_MODEL_STATIC) { bool anySymbolsPreserved = false; for (std::list<claimed_file>::iterator I = Modules.begin(), E = Modules.end(); I != E; ++I) { (*get_symbols)(I->handle, I->syms.size(), &I->syms[0]); for (unsigned i = 0, e = I->syms.size(); i != e; i++) { if (I->syms[i].resolution == LDPR_PREVAILING_DEF || (I->syms[i].def == LDPK_COMMON && I->syms[i].resolution == LDPR_RESOLVED_IR)) { lto_codegen_add_must_preserve_symbol(cg, I->syms[i].name); anySymbolsPreserved = true; if (options::generate_api_file) api_file << I->syms[i].name << "\n"; } } } if (options::generate_api_file) api_file.close(); if (!anySymbolsPreserved) { // This entire file is unnecessary! lto_codegen_dispose(cg); return LDPS_OK; } } lto_codegen_set_pic_model(cg, output_type); lto_codegen_set_debug_model(cg, LTO_DEBUG_MODEL_DWARF); if (options::as_path) { sys::Path p = sys::Program::FindProgramByName(options::as_path); lto_codegen_set_assembler_path(cg, p.c_str()); } // Pass through extra options to the code generator. if (!options::extra.empty()) { for (std::vector<std::string>::iterator it = options::extra.begin(); it != options::extra.end(); ++it) { lto_codegen_debug_options(cg, (*it).c_str()); } } size_t bufsize = 0; const char *buffer = static_cast<const char *>(lto_codegen_compile(cg, &bufsize)); std::string ErrMsg; sys::Path uniqueObjPath("/tmp/llvmgold.o"); if (uniqueObjPath.createTemporaryFileOnDisk(true, &ErrMsg)) { (*message)(LDPL_ERROR, "%s", ErrMsg.c_str()); return LDPS_ERR; } raw_fd_ostream *objFile = new raw_fd_ostream(uniqueObjPath.c_str(), ErrMsg, raw_fd_ostream::F_Binary); if (!ErrMsg.empty()) { delete objFile; (*message)(LDPL_ERROR, "%s", ErrMsg.c_str()); return LDPS_ERR; } objFile->write(buffer, bufsize); objFile->close(); lto_codegen_dispose(cg); if ((*add_input_file)(const_cast<char*>(uniqueObjPath.c_str())) != LDPS_OK) { (*message)(LDPL_ERROR, "Unable to add .o file to the link."); (*message)(LDPL_ERROR, "File left behind in: %s", uniqueObjPath.c_str()); return LDPS_ERR; } Cleanup.push_back(uniqueObjPath); return LDPS_OK; } ld_plugin_status cleanup_hook(void) { std::string ErrMsg; for (int i = 0, e = Cleanup.size(); i != e; ++i) if (Cleanup[i].eraseFromDisk(false, &ErrMsg)) (*message)(LDPL_ERROR, "Failed to delete '%s': %s", Cleanup[i].c_str(), ErrMsg.c_str()); return LDPS_OK; }
Fix to pass options from Gold plugin to LTO codegen
Fix to pass options from Gold plugin to LTO codegen git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@85419 91177308-0d34-0410-b5e6-96231b3b80d8
C++
bsd-2-clause
chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,dslab-epfl/asap,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap
ca4286295f7db200724cb488a04ad15441a8ba99
tools/gold/gold-plugin.cpp
tools/gold/gold-plugin.cpp
//===-- gold-plugin.cpp - Plugin to gold for Link Time Optimization ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is a gold plugin for LLVM. It provides an LLVM implementation of the // interface described in http://gcc.gnu.org/wiki/whopr/driver . // //===----------------------------------------------------------------------===// #include "plugin-api.h" #include "llvm-c/lto.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Path.h" #include <cerrno> #include <cstdlib> #include <cstring> #include <list> #include <vector> using namespace llvm; namespace { ld_plugin_status discard_message(int level, const char *format, ...) { // Die loudly. Recent versions of Gold pass ld_plugin_message as the first // callback in the transfer vector. This should never be called. abort(); } ld_plugin_add_symbols add_symbols = NULL; ld_plugin_get_symbols get_symbols = NULL; ld_plugin_add_input_file add_input_file = NULL; ld_plugin_message message = discard_message; int api_version = 0; int gold_version = 0; struct claimed_file { lto_module_t M; void *handle; std::vector<ld_plugin_symbol> syms; }; lto_codegen_model output_type = LTO_CODEGEN_PIC_MODEL_STATIC; std::list<claimed_file> Modules; std::vector<sys::Path> Cleanup; } ld_plugin_status claim_file_hook(const ld_plugin_input_file *file, int *claimed); ld_plugin_status all_symbols_read_hook(void); ld_plugin_status cleanup_hook(void); extern "C" ld_plugin_status onload(ld_plugin_tv *tv); ld_plugin_status onload(ld_plugin_tv *tv) { // We're given a pointer to the first transfer vector. We read through them // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values // contain pointers to functions that we need to call to register our own // hooks. The others are addresses of functions we can use to call into gold // for services. bool registeredClaimFile = false; bool registeredAllSymbolsRead = false; bool registeredCleanup = false; for (; tv->tv_tag != LDPT_NULL; ++tv) { switch (tv->tv_tag) { case LDPT_API_VERSION: api_version = tv->tv_u.tv_val; break; case LDPT_GOLD_VERSION: // major * 100 + minor gold_version = tv->tv_u.tv_val; break; case LDPT_LINKER_OUTPUT: switch (tv->tv_u.tv_val) { case LDPO_REL: // .o case LDPO_DYN: // .so output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC; break; case LDPO_EXEC: // .exe output_type = LTO_CODEGEN_PIC_MODEL_STATIC; break; default: (*message)(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val); return LDPS_ERR; } // TODO: add an option to disable PIC. //output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC; break; case LDPT_OPTION: (*message)(LDPL_WARNING, "Ignoring flag %s", tv->tv_u.tv_string); break; case LDPT_REGISTER_CLAIM_FILE_HOOK: { ld_plugin_register_claim_file callback; callback = tv->tv_u.tv_register_claim_file; if ((*callback)(claim_file_hook) != LDPS_OK) return LDPS_ERR; registeredClaimFile = true; } break; case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: { ld_plugin_register_all_symbols_read callback; callback = tv->tv_u.tv_register_all_symbols_read; if ((*callback)(all_symbols_read_hook) != LDPS_OK) return LDPS_ERR; registeredAllSymbolsRead = true; } break; case LDPT_REGISTER_CLEANUP_HOOK: { ld_plugin_register_cleanup callback; callback = tv->tv_u.tv_register_cleanup; if ((*callback)(cleanup_hook) != LDPS_OK) return LDPS_ERR; registeredCleanup = true; } break; case LDPT_ADD_SYMBOLS: add_symbols = tv->tv_u.tv_add_symbols; break; case LDPT_GET_SYMBOLS: get_symbols = tv->tv_u.tv_get_symbols; break; case LDPT_ADD_INPUT_FILE: add_input_file = tv->tv_u.tv_add_input_file; break; case LDPT_MESSAGE: message = tv->tv_u.tv_message; break; default: break; } } if (!registeredClaimFile) { (*message)(LDPL_ERROR, "register_claim_file not passed to LLVMgold."); return LDPS_ERR; } if (!add_symbols) { (*message)(LDPL_ERROR, "add_symbols not passed to LLVMgold."); return LDPS_ERR; } return LDPS_OK; } /// claim_file_hook - called by gold to see whether this file is one that /// our plugin can handle. We'll try to open it and register all the symbols /// with add_symbol if possible. ld_plugin_status claim_file_hook(const ld_plugin_input_file *file, int *claimed) { void *buf = NULL; if (file->offset) { // Gold has found what might be IR part-way inside of a file, such as // an .a archive. if (lseek(file->fd, file->offset, SEEK_SET) == -1) { (*message)(LDPL_ERROR, "Failed to seek to archive member of %s at offset %d: %s\n", file->name, file->offset, strerror(errno)); return LDPS_ERR; } buf = malloc(file->filesize); if (!buf) { (*message)(LDPL_ERROR, "Failed to allocate buffer for archive member of size: %d\n", file->filesize); return LDPS_ERR; } if (read(file->fd, buf, file->filesize) != file->filesize) { (*message)(LDPL_ERROR, "Failed to read archive member of %s at offset %d: %s\n", file->name, file->offset, strerror(errno)); free(buf); return LDPS_ERR; } if (!lto_module_is_object_file_in_memory(buf, file->filesize)) { free(buf); return LDPS_OK; } } else if (!lto_module_is_object_file(file->name)) return LDPS_OK; *claimed = 1; Modules.resize(Modules.size() + 1); claimed_file &cf = Modules.back(); cf.M = buf ? lto_module_create_from_memory(buf, file->filesize) : lto_module_create(file->name); free(buf); if (!cf.M) { (*message)(LDPL_ERROR, "Failed to create LLVM module: %s", lto_get_error_message()); return LDPS_ERR; } cf.handle = file->handle; unsigned sym_count = lto_module_get_num_symbols(cf.M); cf.syms.reserve(sym_count); for (unsigned i = 0; i != sym_count; ++i) { lto_symbol_attributes attrs = lto_module_get_symbol_attribute(cf.M, i); if ((attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL) continue; cf.syms.push_back(ld_plugin_symbol()); ld_plugin_symbol &sym = cf.syms.back(); sym.name = const_cast<char *>(lto_module_get_symbol_name(cf.M, i)); sym.version = NULL; int scope = attrs & LTO_SYMBOL_SCOPE_MASK; switch (scope) { case LTO_SYMBOL_SCOPE_HIDDEN: sym.visibility = LDPV_HIDDEN; break; case LTO_SYMBOL_SCOPE_PROTECTED: sym.visibility = LDPV_PROTECTED; break; case 0: // extern case LTO_SYMBOL_SCOPE_DEFAULT: sym.visibility = LDPV_DEFAULT; break; default: (*message)(LDPL_ERROR, "Unknown scope attribute: %d", scope); return LDPS_ERR; } int definition = attrs & LTO_SYMBOL_DEFINITION_MASK; switch (definition) { case LTO_SYMBOL_DEFINITION_REGULAR: sym.def = LDPK_DEF; break; case LTO_SYMBOL_DEFINITION_UNDEFINED: sym.def = LDPK_UNDEF; break; case LTO_SYMBOL_DEFINITION_TENTATIVE: sym.def = LDPK_COMMON; break; case LTO_SYMBOL_DEFINITION_WEAK: sym.def = LDPK_WEAKDEF; break; default: (*message)(LDPL_ERROR, "Unknown definition attribute: %d", definition); return LDPS_ERR; } // LLVM never emits COMDAT. sym.size = 0; sym.comdat_key = NULL; sym.resolution = LDPR_UNKNOWN; } cf.syms.reserve(cf.syms.size()); if (!cf.syms.empty()) { if ((*add_symbols)(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) { (*message)(LDPL_ERROR, "Unable to add symbols!"); return LDPS_ERR; } } return LDPS_OK; } /// all_symbols_read_hook - gold informs us that all symbols have been read. /// At this point, we use get_symbols to see if any of our definitions have /// been overridden by a native object file. Then, perform optimization and /// codegen. ld_plugin_status all_symbols_read_hook(void) { lto_code_gen_t cg = lto_codegen_create(); for (std::list<claimed_file>::iterator I = Modules.begin(), E = Modules.end(); I != E; ++I) lto_codegen_add_module(cg, I->M); // If we don't preserve any symbols, libLTO will assume that all symbols are // needed. Keep all symbols unless we're producing a final executable. if (output_type == LTO_CODEGEN_PIC_MODEL_STATIC) { bool anySymbolsPreserved = false; for (std::list<claimed_file>::iterator I = Modules.begin(), E = Modules.end(); I != E; ++I) { (*get_symbols)(I->handle, I->syms.size(), &I->syms[0]); for (unsigned i = 0, e = I->syms.size(); i != e; i++) { if (I->syms[i].resolution == LDPR_PREVAILING_DEF || (I->syms[i].def == LDPK_COMMON && I->syms[i].resolution == LDPR_RESOLVED_IR)) { lto_codegen_add_must_preserve_symbol(cg, I->syms[i].name); anySymbolsPreserved = true; } } } if (!anySymbolsPreserved) { // This entire file is unnecessary! lto_codegen_dispose(cg); return LDPS_OK; } } lto_codegen_set_pic_model(cg, output_type); lto_codegen_set_debug_model(cg, LTO_DEBUG_MODEL_DWARF); size_t bufsize = 0; const char *buffer = static_cast<const char *>(lto_codegen_compile(cg, &bufsize)); std::string ErrMsg; sys::Path uniqueObjPath("/tmp/llvmgold.o"); if (uniqueObjPath.createTemporaryFileOnDisk(true, &ErrMsg)) { (*message)(LDPL_ERROR, "%s", ErrMsg.c_str()); return LDPS_ERR; } raw_fd_ostream *objFile = new raw_fd_ostream(uniqueObjPath.c_str(), true, ErrMsg); if (!ErrMsg.empty()) { delete objFile; (*message)(LDPL_ERROR, "%s", ErrMsg.c_str()); return LDPS_ERR; } objFile->write(buffer, bufsize); objFile->close(); lto_codegen_dispose(cg); if ((*add_input_file)(const_cast<char*>(uniqueObjPath.c_str())) != LDPS_OK) { (*message)(LDPL_ERROR, "Unable to add .o file to the link."); (*message)(LDPL_ERROR, "File left behind in: %s", uniqueObjPath.c_str()); return LDPS_ERR; } Cleanup.push_back(uniqueObjPath); return LDPS_OK; } ld_plugin_status cleanup_hook(void) { std::string ErrMsg; for (int i = 0, e = Cleanup.size(); i != e; ++i) if (Cleanup[i].eraseFromDisk(false, &ErrMsg)) (*message)(LDPL_ERROR, "Failed to delete '%s': %s", Cleanup[i].c_str(), ErrMsg.c_str()); return LDPS_OK; }
//===-- gold-plugin.cpp - Plugin to gold for Link Time Optimization ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is a gold plugin for LLVM. It provides an LLVM implementation of the // interface described in http://gcc.gnu.org/wiki/whopr/driver . // //===----------------------------------------------------------------------===// #include "plugin-api.h" #include "llvm-c/lto.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Path.h" #include <cerrno> #include <cstdlib> #include <cstring> #include <fstream> #include <list> #include <vector> using namespace llvm; namespace { ld_plugin_status discard_message(int level, const char *format, ...) { // Die loudly. Recent versions of Gold pass ld_plugin_message as the first // callback in the transfer vector. This should never be called. abort(); } ld_plugin_add_symbols add_symbols = NULL; ld_plugin_get_symbols get_symbols = NULL; ld_plugin_add_input_file add_input_file = NULL; ld_plugin_message message = discard_message; int api_version = 0; int gold_version = 0; bool generate_api_file = false; struct claimed_file { lto_module_t M; void *handle; std::vector<ld_plugin_symbol> syms; }; lto_codegen_model output_type = LTO_CODEGEN_PIC_MODEL_STATIC; std::list<claimed_file> Modules; std::vector<sys::Path> Cleanup; } ld_plugin_status claim_file_hook(const ld_plugin_input_file *file, int *claimed); ld_plugin_status all_symbols_read_hook(void); ld_plugin_status cleanup_hook(void); extern "C" ld_plugin_status onload(ld_plugin_tv *tv); ld_plugin_status onload(ld_plugin_tv *tv) { // We're given a pointer to the first transfer vector. We read through them // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values // contain pointers to functions that we need to call to register our own // hooks. The others are addresses of functions we can use to call into gold // for services. bool registeredClaimFile = false; bool registeredAllSymbolsRead = false; bool registeredCleanup = false; for (; tv->tv_tag != LDPT_NULL; ++tv) { switch (tv->tv_tag) { case LDPT_API_VERSION: api_version = tv->tv_u.tv_val; break; case LDPT_GOLD_VERSION: // major * 100 + minor gold_version = tv->tv_u.tv_val; break; case LDPT_LINKER_OUTPUT: switch (tv->tv_u.tv_val) { case LDPO_REL: // .o case LDPO_DYN: // .so output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC; break; case LDPO_EXEC: // .exe output_type = LTO_CODEGEN_PIC_MODEL_STATIC; break; default: (*message)(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val); return LDPS_ERR; } // TODO: add an option to disable PIC. //output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC; break; case LDPT_OPTION: if (strcmp("generate-api-file", tv->tv_u.tv_string) == 0) { generate_api_file = true; } else { (*message)(LDPL_WARNING, "Ignoring flag %s", tv->tv_u.tv_string); } break; case LDPT_REGISTER_CLAIM_FILE_HOOK: { ld_plugin_register_claim_file callback; callback = tv->tv_u.tv_register_claim_file; if ((*callback)(claim_file_hook) != LDPS_OK) return LDPS_ERR; registeredClaimFile = true; } break; case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: { ld_plugin_register_all_symbols_read callback; callback = tv->tv_u.tv_register_all_symbols_read; if ((*callback)(all_symbols_read_hook) != LDPS_OK) return LDPS_ERR; registeredAllSymbolsRead = true; } break; case LDPT_REGISTER_CLEANUP_HOOK: { ld_plugin_register_cleanup callback; callback = tv->tv_u.tv_register_cleanup; if ((*callback)(cleanup_hook) != LDPS_OK) return LDPS_ERR; registeredCleanup = true; } break; case LDPT_ADD_SYMBOLS: add_symbols = tv->tv_u.tv_add_symbols; break; case LDPT_GET_SYMBOLS: get_symbols = tv->tv_u.tv_get_symbols; break; case LDPT_ADD_INPUT_FILE: add_input_file = tv->tv_u.tv_add_input_file; break; case LDPT_MESSAGE: message = tv->tv_u.tv_message; break; default: break; } } if (!registeredClaimFile) { (*message)(LDPL_ERROR, "register_claim_file not passed to LLVMgold."); return LDPS_ERR; } if (!add_symbols) { (*message)(LDPL_ERROR, "add_symbols not passed to LLVMgold."); return LDPS_ERR; } return LDPS_OK; } /// claim_file_hook - called by gold to see whether this file is one that /// our plugin can handle. We'll try to open it and register all the symbols /// with add_symbol if possible. ld_plugin_status claim_file_hook(const ld_plugin_input_file *file, int *claimed) { void *buf = NULL; if (file->offset) { // Gold has found what might be IR part-way inside of a file, such as // an .a archive. if (lseek(file->fd, file->offset, SEEK_SET) == -1) { (*message)(LDPL_ERROR, "Failed to seek to archive member of %s at offset %d: %s\n", file->name, file->offset, strerror(errno)); return LDPS_ERR; } buf = malloc(file->filesize); if (!buf) { (*message)(LDPL_ERROR, "Failed to allocate buffer for archive member of size: %d\n", file->filesize); return LDPS_ERR; } if (read(file->fd, buf, file->filesize) != file->filesize) { (*message)(LDPL_ERROR, "Failed to read archive member of %s at offset %d: %s\n", file->name, file->offset, strerror(errno)); free(buf); return LDPS_ERR; } if (!lto_module_is_object_file_in_memory(buf, file->filesize)) { free(buf); return LDPS_OK; } } else if (!lto_module_is_object_file(file->name)) return LDPS_OK; *claimed = 1; Modules.resize(Modules.size() + 1); claimed_file &cf = Modules.back(); cf.M = buf ? lto_module_create_from_memory(buf, file->filesize) : lto_module_create(file->name); free(buf); if (!cf.M) { (*message)(LDPL_ERROR, "Failed to create LLVM module: %s", lto_get_error_message()); return LDPS_ERR; } cf.handle = file->handle; unsigned sym_count = lto_module_get_num_symbols(cf.M); cf.syms.reserve(sym_count); for (unsigned i = 0; i != sym_count; ++i) { lto_symbol_attributes attrs = lto_module_get_symbol_attribute(cf.M, i); if ((attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL) continue; cf.syms.push_back(ld_plugin_symbol()); ld_plugin_symbol &sym = cf.syms.back(); sym.name = const_cast<char *>(lto_module_get_symbol_name(cf.M, i)); sym.version = NULL; int scope = attrs & LTO_SYMBOL_SCOPE_MASK; switch (scope) { case LTO_SYMBOL_SCOPE_HIDDEN: sym.visibility = LDPV_HIDDEN; break; case LTO_SYMBOL_SCOPE_PROTECTED: sym.visibility = LDPV_PROTECTED; break; case 0: // extern case LTO_SYMBOL_SCOPE_DEFAULT: sym.visibility = LDPV_DEFAULT; break; default: (*message)(LDPL_ERROR, "Unknown scope attribute: %d", scope); return LDPS_ERR; } int definition = attrs & LTO_SYMBOL_DEFINITION_MASK; switch (definition) { case LTO_SYMBOL_DEFINITION_REGULAR: sym.def = LDPK_DEF; break; case LTO_SYMBOL_DEFINITION_UNDEFINED: sym.def = LDPK_UNDEF; break; case LTO_SYMBOL_DEFINITION_TENTATIVE: sym.def = LDPK_COMMON; break; case LTO_SYMBOL_DEFINITION_WEAK: sym.def = LDPK_WEAKDEF; break; default: (*message)(LDPL_ERROR, "Unknown definition attribute: %d", definition); return LDPS_ERR; } // LLVM never emits COMDAT. sym.size = 0; sym.comdat_key = NULL; sym.resolution = LDPR_UNKNOWN; } cf.syms.reserve(cf.syms.size()); if (!cf.syms.empty()) { if ((*add_symbols)(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) { (*message)(LDPL_ERROR, "Unable to add symbols!"); return LDPS_ERR; } } return LDPS_OK; } /// all_symbols_read_hook - gold informs us that all symbols have been read. /// At this point, we use get_symbols to see if any of our definitions have /// been overridden by a native object file. Then, perform optimization and /// codegen. ld_plugin_status all_symbols_read_hook(void) { lto_code_gen_t cg = lto_codegen_create(); for (std::list<claimed_file>::iterator I = Modules.begin(), E = Modules.end(); I != E; ++I) lto_codegen_add_module(cg, I->M); std::ofstream api_file; if (generate_api_file) { api_file.open("apifile.txt", std::ofstream::out | std::ofstream::trunc); if (!api_file.is_open()) { (*message)(LDPL_FATAL, "Unable to open apifile.txt for writing."); abort(); } } // If we don't preserve any symbols, libLTO will assume that all symbols are // needed. Keep all symbols unless we're producing a final executable. if (output_type == LTO_CODEGEN_PIC_MODEL_STATIC) { bool anySymbolsPreserved = false; for (std::list<claimed_file>::iterator I = Modules.begin(), E = Modules.end(); I != E; ++I) { (*get_symbols)(I->handle, I->syms.size(), &I->syms[0]); for (unsigned i = 0, e = I->syms.size(); i != e; i++) { if (I->syms[i].resolution == LDPR_PREVAILING_DEF || (I->syms[i].def == LDPK_COMMON && I->syms[i].resolution == LDPR_RESOLVED_IR)) { lto_codegen_add_must_preserve_symbol(cg, I->syms[i].name); anySymbolsPreserved = true; if (generate_api_file) api_file << I->syms[i].name << "\n"; } } } if (generate_api_file) api_file.close(); if (!anySymbolsPreserved) { // This entire file is unnecessary! lto_codegen_dispose(cg); return LDPS_OK; } } lto_codegen_set_pic_model(cg, output_type); lto_codegen_set_debug_model(cg, LTO_DEBUG_MODEL_DWARF); size_t bufsize = 0; const char *buffer = static_cast<const char *>(lto_codegen_compile(cg, &bufsize)); std::string ErrMsg; sys::Path uniqueObjPath("/tmp/llvmgold.o"); if (uniqueObjPath.createTemporaryFileOnDisk(true, &ErrMsg)) { (*message)(LDPL_ERROR, "%s", ErrMsg.c_str()); return LDPS_ERR; } raw_fd_ostream *objFile = new raw_fd_ostream(uniqueObjPath.c_str(), true, ErrMsg); if (!ErrMsg.empty()) { delete objFile; (*message)(LDPL_ERROR, "%s", ErrMsg.c_str()); return LDPS_ERR; } objFile->write(buffer, bufsize); objFile->close(); lto_codegen_dispose(cg); if ((*add_input_file)(const_cast<char*>(uniqueObjPath.c_str())) != LDPS_OK) { (*message)(LDPL_ERROR, "Unable to add .o file to the link."); (*message)(LDPL_ERROR, "File left behind in: %s", uniqueObjPath.c_str()); return LDPS_ERR; } Cleanup.push_back(uniqueObjPath); return LDPS_OK; } ld_plugin_status cleanup_hook(void) { std::string ErrMsg; for (int i = 0, e = Cleanup.size(); i != e; ++i) if (Cleanup[i].eraseFromDisk(false, &ErrMsg)) (*message)(LDPL_ERROR, "Failed to delete '%s': %s", Cleanup[i].c_str(), ErrMsg.c_str()); return LDPS_OK; }
Add an option to the gold plugin to make it emit a file with the public api list that can in turn be passed to -internalize pass through -internalize-public-api-file.
Add an option to the gold plugin to make it emit a file with the public api list that can in turn be passed to -internalize pass through -internalize-public-api-file. Pass gold -plugin-opt=generate-api-file to produce "apifile.txt" in the current directory. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@65295 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,chubbymaggie/asap,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,dslab-epfl/asap,llvm-mirror/llvm,chubbymaggie/asap,chubbymaggie/asap,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm
9c49ac15c14a1040752e310aec6826c17ac29830
extensions/browser/api/hid/hid_device_manager.cc
extensions/browser/api/hid/hid_device_manager.cc
// Copyright 2014 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 "extensions/browser/api/hid/hid_device_manager.h" #include <limits> #include <vector> #include "base/lazy_instance.h" #include "device/core/device_client.h" #include "device/hid/hid_device_filter.h" #include "device/hid/hid_service.h" #include "extensions/browser/api/extensions_api_client.h" #include "extensions/common/permissions/permissions_data.h" #include "extensions/common/permissions/usb_device_permission.h" using device::HidDeviceFilter; using device::HidService; using device::HidUsageAndPage; namespace extensions { HidDeviceManager::HidDeviceManager(content::BrowserContext* context) : next_resource_id_(0) { } HidDeviceManager::~HidDeviceManager() {} // static BrowserContextKeyedAPIFactory<HidDeviceManager>* HidDeviceManager::GetFactoryInstance() { static base::LazyInstance<BrowserContextKeyedAPIFactory<HidDeviceManager> > factory = LAZY_INSTANCE_INITIALIZER; return &factory.Get(); } scoped_ptr<base::ListValue> HidDeviceManager::GetApiDevices( const Extension* extension, const std::vector<HidDeviceFilter>& filters) { UpdateDevices(); HidService* hid_service = device::DeviceClient::Get()->GetHidService(); DCHECK(hid_service); base::ListValue* api_devices = new base::ListValue(); for (ResourceIdToDeviceIdMap::const_iterator device_iter = device_ids_.begin(); device_iter != device_ids_.end(); ++device_iter) { int resource_id = device_iter->first; device::HidDeviceId device_id = device_iter->second; device::HidDeviceInfo device_info; if (hid_service->GetDeviceInfo(device_id, &device_info)) { if (!filters.empty() && !HidDeviceFilter::MatchesAny(device_info, filters)) { continue; } if (!HasPermission(extension, device_info)) { continue; } core_api::hid::HidDeviceInfo api_device_info; api_device_info.device_id = resource_id; api_device_info.vendor_id = device_info.vendor_id; api_device_info.product_id = device_info.product_id; api_device_info.max_input_report_size = device_info.max_input_report_size; api_device_info.max_output_report_size = device_info.max_output_report_size; api_device_info.max_feature_report_size = device_info.max_feature_report_size; for (std::vector<device::HidCollectionInfo>::const_iterator collections_iter = device_info.collections.begin(); collections_iter != device_info.collections.end(); ++collections_iter) { const device::HidCollectionInfo& collection = *collections_iter; // Don't expose sensitive data. if (collection.usage.IsProtected()) { continue; } core_api::hid::HidCollectionInfo* api_collection = new core_api::hid::HidCollectionInfo(); api_collection->usage_page = collection.usage.usage_page; api_collection->usage = collection.usage.usage; api_collection->report_ids.resize(collection.report_ids.size()); std::copy(collection.report_ids.begin(), collection.report_ids.end(), api_collection->report_ids.begin()); api_device_info.collections.push_back(make_linked_ptr(api_collection)); } // Expose devices with which user can communicate. if (api_device_info.collections.size() > 0) { api_devices->Append(api_device_info.ToValue().release()); } } } return scoped_ptr<base::ListValue>(api_devices); } bool HidDeviceManager::GetDeviceInfo(int resource_id, device::HidDeviceInfo* device_info) { UpdateDevices(); HidService* hid_service = device::DeviceClient::Get()->GetHidService(); DCHECK(hid_service); ResourceIdToDeviceIdMap::const_iterator device_iter = device_ids_.find(resource_id); if (device_iter == device_ids_.end()) return false; return hid_service->GetDeviceInfo(device_iter->second, device_info); } bool HidDeviceManager::HasPermission(const Extension* extension, const device::HidDeviceInfo& device_info) { UsbDevicePermission::CheckParam usbParam( device_info.vendor_id, device_info.product_id, UsbDevicePermissionData::UNSPECIFIED_INTERFACE); if (extension->permissions_data()->CheckAPIPermissionWithParam( APIPermission::kUsbDevice, &usbParam)) { return true; } if (extension->permissions_data()->HasAPIPermission( APIPermission::kU2fDevices)) { HidDeviceFilter u2f_filter; u2f_filter.SetUsagePage(0xF1D0); if (u2f_filter.Matches(device_info)) { return true; } } return false; } void HidDeviceManager::UpdateDevices() { DCHECK(thread_checker_.CalledOnValidThread()); HidService* hid_service = device::DeviceClient::Get()->GetHidService(); DCHECK(hid_service); std::vector<device::HidDeviceInfo> devices; hid_service->GetDevices(&devices); // Build an updated bidi mapping between resource ID and underlying device ID. DeviceIdToResourceIdMap new_resource_ids; ResourceIdToDeviceIdMap new_device_ids; for (std::vector<device::HidDeviceInfo>::const_iterator iter = devices.begin(); iter != devices.end(); ++iter) { const device::HidDeviceInfo& device_info = *iter; DeviceIdToResourceIdMap::iterator resource_iter = resource_ids_.find(device_info.device_id); int new_id; if (resource_iter != resource_ids_.end()) { new_id = resource_iter->second; } else { DCHECK_LT(next_resource_id_, std::numeric_limits<int>::max()); new_id = next_resource_id_++; } new_resource_ids[device_info.device_id] = new_id; new_device_ids[new_id] = device_info.device_id; } device_ids_.swap(new_device_ids); resource_ids_.swap(new_resource_ids); } } // namespace extensions
// Copyright 2014 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 "extensions/browser/api/hid/hid_device_manager.h" #include <limits> #include <vector> #include "base/lazy_instance.h" #include "device/core/device_client.h" #include "device/hid/hid_device_filter.h" #include "device/hid/hid_service.h" #include "extensions/browser/api/extensions_api_client.h" #include "extensions/common/permissions/permissions_data.h" #include "extensions/common/permissions/usb_device_permission.h" using device::HidDeviceFilter; using device::HidService; using device::HidUsageAndPage; namespace extensions { HidDeviceManager::HidDeviceManager(content::BrowserContext* context) : next_resource_id_(0) { } HidDeviceManager::~HidDeviceManager() {} // static BrowserContextKeyedAPIFactory<HidDeviceManager>* HidDeviceManager::GetFactoryInstance() { static base::LazyInstance<BrowserContextKeyedAPIFactory<HidDeviceManager> > factory = LAZY_INSTANCE_INITIALIZER; return &factory.Get(); } scoped_ptr<base::ListValue> HidDeviceManager::GetApiDevices( const Extension* extension, const std::vector<HidDeviceFilter>& filters) { UpdateDevices(); HidService* hid_service = device::DeviceClient::Get()->GetHidService(); DCHECK(hid_service); base::ListValue* api_devices = new base::ListValue(); for (ResourceIdToDeviceIdMap::const_iterator device_iter = device_ids_.begin(); device_iter != device_ids_.end(); ++device_iter) { int resource_id = device_iter->first; device::HidDeviceId device_id = device_iter->second; device::HidDeviceInfo device_info; if (hid_service->GetDeviceInfo(device_id, &device_info)) { if (!filters.empty() && !HidDeviceFilter::MatchesAny(device_info, filters)) { continue; } if (!HasPermission(extension, device_info)) { continue; } core_api::hid::HidDeviceInfo api_device_info; api_device_info.device_id = resource_id; api_device_info.vendor_id = device_info.vendor_id; api_device_info.product_id = device_info.product_id; api_device_info.max_input_report_size = device_info.max_input_report_size; api_device_info.max_output_report_size = device_info.max_output_report_size; api_device_info.max_feature_report_size = device_info.max_feature_report_size; for (std::vector<device::HidCollectionInfo>::const_iterator collections_iter = device_info.collections.begin(); collections_iter != device_info.collections.end(); ++collections_iter) { const device::HidCollectionInfo& collection = *collections_iter; // Don't expose sensitive data. if (collection.usage.IsProtected()) { continue; } core_api::hid::HidCollectionInfo* api_collection = new core_api::hid::HidCollectionInfo(); api_collection->usage_page = collection.usage.usage_page; api_collection->usage = collection.usage.usage; api_collection->report_ids.resize(collection.report_ids.size()); std::copy(collection.report_ids.begin(), collection.report_ids.end(), api_collection->report_ids.begin()); api_device_info.collections.push_back(make_linked_ptr(api_collection)); } // Expose devices with which user can communicate. if (api_device_info.collections.size() > 0) { api_devices->Append(api_device_info.ToValue().release()); } } } return scoped_ptr<base::ListValue>(api_devices); } bool HidDeviceManager::GetDeviceInfo(int resource_id, device::HidDeviceInfo* device_info) { UpdateDevices(); HidService* hid_service = device::DeviceClient::Get()->GetHidService(); DCHECK(hid_service); ResourceIdToDeviceIdMap::const_iterator device_iter = device_ids_.find(resource_id); if (device_iter == device_ids_.end()) return false; return hid_service->GetDeviceInfo(device_iter->second, device_info); } bool HidDeviceManager::HasPermission(const Extension* extension, const device::HidDeviceInfo& device_info) { UsbDevicePermission::CheckParam usbParam( device_info.vendor_id, device_info.product_id, UsbDevicePermissionData::UNSPECIFIED_INTERFACE); if (extension->permissions_data()->CheckAPIPermissionWithParam( APIPermission::kUsbDevice, &usbParam)) { return true; } if (extension->permissions_data()->HasAPIPermission( APIPermission::kU2fDevices)) { HidDeviceFilter u2f_filter; u2f_filter.SetUsagePage(0xF1D0); if (u2f_filter.Matches(device_info)) { return true; } } return false; } void HidDeviceManager::UpdateDevices() { thread_checker_.CalledOnValidThread(); HidService* hid_service = device::DeviceClient::Get()->GetHidService(); DCHECK(hid_service); std::vector<device::HidDeviceInfo> devices; hid_service->GetDevices(&devices); // Build an updated bidi mapping between resource ID and underlying device ID. DeviceIdToResourceIdMap new_resource_ids; ResourceIdToDeviceIdMap new_device_ids; for (std::vector<device::HidDeviceInfo>::const_iterator iter = devices.begin(); iter != devices.end(); ++iter) { const device::HidDeviceInfo& device_info = *iter; DeviceIdToResourceIdMap::iterator resource_iter = resource_ids_.find(device_info.device_id); int new_id; if (resource_iter != resource_ids_.end()) { new_id = resource_iter->second; } else { DCHECK_LT(next_resource_id_, std::numeric_limits<int>::max()); new_id = next_resource_id_++; } new_resource_ids[device_info.device_id] = new_id; new_device_ids[new_id] = device_info.device_id; } device_ids_.swap(new_device_ids); resource_ids_.swap(new_resource_ids); } } // namespace extensions
Revert "extensions: Explicitly ignore result of CalledOnValidThread()."
Revert "extensions: Explicitly ignore result of CalledOnValidThread()." This reverts commit 7fb8b9950da0f1156d07e18dca5151f3f1457e2b. BUG=417939 [email protected] Review URL: https://codereview.chromium.org/609633002 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#296845}
C++
bsd-3-clause
axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,ltilve/chromium,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,M4sse/chromium.src,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,ltilve/chromium,ltilve/chromium,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,dednal/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,ltilve/chromium,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,M4sse/chromium.src,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,Jonekee/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,markYoungH/chromium.src,ltilve/chromium,markYoungH/chromium.src,axinging/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,dednal/chromium.src,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,Chilledheart/chromium,fujunwei/chromium-crosswalk,Just-D/chromium-1,markYoungH/chromium.src,Jonekee/chromium.src,Chilledheart/chromium,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,fujunwei/chromium-crosswalk,dednal/chromium.src,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,markYoungH/chromium.src,dednal/chromium.src,ltilve/chromium,Jonekee/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk,M4sse/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,jaruba/chromium.src,fujunwei/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,ltilve/chromium,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,Chilledheart/chromium,axinging/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk
4b15a2b5308b66065068b87b4fae104c6dde4768
dune/gdt/operators/elliptic-swipdg.hh
dune/gdt/operators/elliptic-swipdg.hh
// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATORS_ELLIPTIC_SWIPDG_HH #define DUNE_GDT_OPERATORS_ELLIPTIC_SWIPDG_HH #include <type_traits> #include <dune/stuff/la/container/interfaces.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/stuff/common/memory.hh> #include <dune/stuff/grid/boundaryinfo.hh> #include <dune/gdt/spaces/interface.hh> #include <dune/gdt/localevaluation/elliptic.hh> #include <dune/gdt/localevaluation/swipdg.hh> #include <dune/gdt/localoperator/codim0.hh> #include <dune/gdt/localoperator/codim1.hh> #include <dune/gdt/assembler/local/codim0.hh> #include <dune/gdt/assembler/local/codim1.hh> #include <dune/gdt/assembler/system.hh> #include "base.hh" namespace Dune { namespace GDT { namespace Operators { // forwards template< class DiffusionFactorType , class MatrixImp , class SourceSpaceImp , class RangeSpaceImp = SourceSpaceImp , class GridViewImp = typename SourceSpaceImp::GridViewType , class DiffusionTensorType = void > class EllipticSWIPDG; namespace internal { template< class DiffusionFactorType , class MatrixImp , class SourceSpaceImp , class RangeSpaceImp , class GridViewImp , class DiffusionTensorType = void > class EllipticSWIPDGTraits { static_assert(std::is_base_of< Stuff::Tags::LocalizableFunction, DiffusionFactorType >::value, "DiffusionFactorType has to be derived from Stuff::LocalizableFunctionInterface!"); static_assert(std::is_base_of< Stuff::Tags::LocalizableFunction, DiffusionTensorType >::value, "DiffusionTensorType has to be derived from Stuff::LocalizableFunctionInterface!"); static_assert(std::is_base_of < Stuff::LA::MatrixInterface< typename MatrixImp::Traits, typename MatrixImp::Traits::ScalarType >, MatrixImp >::value, "MatrixImp has to be derived from Stuff::LA::MatrixInterface!"); static_assert(std::is_base_of< SpaceInterface< typename SourceSpaceImp::Traits >, SourceSpaceImp >::value, "SourceSpaceImp has to be derived from SpaceInterface!"); static_assert(std::is_base_of< SpaceInterface< typename RangeSpaceImp::Traits >, RangeSpaceImp >::value, "RangeSpaceImp has to be derived from SpaceInterface!"); public: typedef EllipticSWIPDG< DiffusionFactorType, MatrixImp, SourceSpaceImp , RangeSpaceImp, GridViewImp, DiffusionTensorType > derived_type; typedef MatrixImp MatrixType; typedef SourceSpaceImp SourceSpaceType; typedef RangeSpaceImp RangeSpaceType; typedef GridViewImp GridViewType; }; // class EllipticSWIPDGTraits template< class DiffusionType , class MatrixImp , class SourceSpaceImp , class RangeSpaceImp , class GridViewImp > class EllipticSWIPDGTraits< DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp, void > { static_assert(std::is_base_of< Stuff::Tags::LocalizableFunction, DiffusionType >::value, "DiffusionType has to be derived from Stuff::LocalizableFunctionInterface!"); static_assert(std::is_base_of < Stuff::LA::MatrixInterface< typename MatrixImp::Traits, typename MatrixImp::Traits::ScalarType >, MatrixImp >::value, "MatrixImp has to be derived from Stuff::LA::MatrixInterface!"); static_assert(std::is_base_of< SpaceInterface< typename SourceSpaceImp::Traits >, SourceSpaceImp >::value, "SourceSpaceImp has to be derived from SpaceInterface!"); static_assert(std::is_base_of< SpaceInterface< typename RangeSpaceImp::Traits >, RangeSpaceImp >::value, "RangeSpaceImp has to be derived from SpaceInterface!"); public: typedef EllipticSWIPDG< DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp, void > derived_type; typedef MatrixImp MatrixType; typedef SourceSpaceImp SourceSpaceType; typedef RangeSpaceImp RangeSpaceType; typedef GridViewImp GridViewType; }; // class EllipticSWIPDGTraits } // namespace internal template< class DiffusionType, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp, class GridViewImp > class EllipticSWIPDG< DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp, void > : Stuff::Common::StorageProvider< MatrixImp > , public Operators::MatrixBased< internal::EllipticSWIPDGTraits< DiffusionType, MatrixImp, SourceSpaceImp , RangeSpaceImp, GridViewImp, void > > , public SystemAssembler< RangeSpaceImp, GridViewImp, SourceSpaceImp > { typedef Stuff::Common::StorageProvider< MatrixImp > StorageProvider; typedef SystemAssembler< RangeSpaceImp, GridViewImp, SourceSpaceImp > AssemblerBaseType; typedef Operators::MatrixBased< internal::EllipticSWIPDGTraits< DiffusionType, MatrixImp , SourceSpaceImp, RangeSpaceImp , GridViewImp, void > > OperatorBaseType; typedef LocalOperator::Codim0Integral< LocalEvaluation::Elliptic< DiffusionType > > VolumeOperatorType; typedef LocalAssembler::Codim0Matrix< VolumeOperatorType > VolumeAssemblerType; typedef LocalOperator::Codim1CouplingIntegral< LocalEvaluation::SWIPDG::Inner< DiffusionType > > CouplingOperatorType; typedef LocalAssembler::Codim1CouplingMatrix< CouplingOperatorType > CouplingAssemblerType; typedef LocalOperator::Codim1BoundaryIntegral< LocalEvaluation::SWIPDG::BoundaryLHS< DiffusionType > > DirichletBoundaryOperatorType; typedef LocalAssembler::Codim1BoundaryMatrix< DirichletBoundaryOperatorType > DirichletBoundaryAssemblerType; typedef typename MatrixImp::ScalarType ScalarType; public: typedef internal::EllipticSWIPDGTraits< DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp, void > Traits; typedef typename Traits::MatrixType MatrixType; typedef typename Traits::SourceSpaceType SourceSpaceType; typedef typename Traits::RangeSpaceType RangeSpaceType; typedef typename Traits::GridViewType GridViewType; typedef Stuff::Grid::BoundaryInfoInterface< typename GridViewType::Intersection > BoundaryInfoType; using OperatorBaseType::pattern; static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space, const SourceSpaceType& source_space, const GridViewType& grid_view) { return range_space.compute_face_and_volume_pattern(grid_view, source_space); } EllipticSWIPDG(const DiffusionType& diffusion, const BoundaryInfoType& boundary_info, MatrixType& matrix, const SourceSpaceType& source_space, const RangeSpaceType& range_space, const GridViewType& grid_view, const ScalarType beta = LocalEvaluation::SWIPDG::internal::default_beta(GridViewType::dimension)) : StorageProvider(matrix) , OperatorBaseType(this->storage_access(), source_space, range_space, grid_view) , AssemblerBaseType(range_space, grid_view, source_space) , diffusion_(diffusion) , boundary_info_(boundary_info) , volume_operator_(diffusion_) , volume_assembler_(volume_operator_) , coupling_operator_(diffusion_, beta) , coupling_assembler_(coupling_operator_) , dirichlet_boundary_operator_(diffusion_, beta) , dirichlet_boundary_assembler_(dirichlet_boundary_operator_) { setup(); } EllipticSWIPDG(const DiffusionType& diffusion, const BoundaryInfoType& boundary_info, const SourceSpaceType& source_space, const RangeSpaceType& range_space, const GridViewType& grid_view, const ScalarType beta = LocalEvaluation::SWIPDG::internal::default_beta(GridViewType::dimension)) : StorageProvider(new MatrixType(range_space.mapper().size(), source_space.mapper().size(), pattern(range_space, source_space, grid_view))) , OperatorBaseType(this->storage_access(), source_space, range_space, grid_view) , AssemblerBaseType(range_space, grid_view, source_space) , diffusion_(diffusion) , boundary_info_(boundary_info) , volume_operator_(diffusion_) , volume_assembler_(volume_operator_) , coupling_operator_(diffusion_, beta) , coupling_assembler_(coupling_operator_) , dirichlet_boundary_operator_(diffusion_, beta) , dirichlet_boundary_assembler_(dirichlet_boundary_operator_) { setup(); } EllipticSWIPDG(const DiffusionType& diffusion, const BoundaryInfoType& boundary_info, MatrixType& matrix, const SourceSpaceType& source_space, const RangeSpaceType& range_space, const ScalarType beta = LocalEvaluation::SWIPDG::internal::default_beta(GridViewType::dimension)) : StorageProvider(matrix) , OperatorBaseType(this->storage_access(), source_space, range_space) , AssemblerBaseType(range_space, source_space) , diffusion_(diffusion) , boundary_info_(boundary_info) , volume_operator_(diffusion_) , volume_assembler_(volume_operator_) , coupling_operator_(diffusion_, beta) , coupling_assembler_(coupling_operator_) , dirichlet_boundary_operator_(diffusion_, beta) , dirichlet_boundary_assembler_(dirichlet_boundary_operator_) { setup(); } EllipticSWIPDG(const DiffusionType& diffusion, const BoundaryInfoType& boundary_info, const SourceSpaceType& source_space, const RangeSpaceType& range_space, const ScalarType beta = LocalEvaluation::SWIPDG::internal::default_beta(GridViewType::dimension)) : StorageProvider(new MatrixType(range_space.mapper().size(), source_space.mapper().size(), pattern(range_space, source_space))) , OperatorBaseType(this->storage_access(), source_space, range_space) , AssemblerBaseType(range_space, source_space) , diffusion_(diffusion) , boundary_info_(boundary_info) , volume_operator_(diffusion_) , volume_assembler_(volume_operator_) , coupling_operator_(diffusion_, beta) , coupling_assembler_(coupling_operator_) , dirichlet_boundary_operator_(diffusion_, beta) , dirichlet_boundary_assembler_(dirichlet_boundary_operator_) { setup(); } EllipticSWIPDG(const DiffusionType& diffusion, const BoundaryInfoType& boundary_info, MatrixType& matrix, const SourceSpaceType& source_space, const ScalarType beta = LocalEvaluation::SWIPDG::internal::default_beta(GridViewType::dimension)) : StorageProvider(matrix) , OperatorBaseType(this->storage_access(), source_space) , AssemblerBaseType(source_space) , diffusion_(diffusion) , boundary_info_(boundary_info) , volume_operator_(diffusion_) , volume_assembler_(volume_operator_) , coupling_operator_(diffusion_, beta) , coupling_assembler_(coupling_operator_) , dirichlet_boundary_operator_(diffusion_, beta) , dirichlet_boundary_assembler_(dirichlet_boundary_operator_) { setup(); } EllipticSWIPDG(const DiffusionType& diffusion, const BoundaryInfoType& boundary_info, const SourceSpaceType& source_space, const ScalarType beta = LocalEvaluation::SWIPDG::internal::default_beta(GridViewType::dimension)) : StorageProvider(new MatrixType(source_space.mapper().size(), source_space.mapper().size(), pattern(source_space))) , OperatorBaseType(this->storage_access(), source_space) , AssemblerBaseType(source_space) , diffusion_(diffusion) , boundary_info_(boundary_info) , volume_operator_(diffusion_) , volume_assembler_(volume_operator_) , coupling_operator_(diffusion_, beta) , coupling_assembler_(coupling_operator_) , dirichlet_boundary_operator_(diffusion_, beta) , dirichlet_boundary_assembler_(dirichlet_boundary_operator_) { setup(); } virtual ~EllipticSWIPDG() {} virtual void assemble() override final { AssemblerBaseType::assemble(); } private: void setup() { this->add(volume_assembler_, this->matrix()); this->add(coupling_assembler_, this->matrix(), new Stuff::Grid::ApplyOn::InnerIntersectionsPrimally< GridViewType >()); this->add(dirichlet_boundary_assembler_, this->matrix(), new Stuff::Grid::ApplyOn::DirichletIntersections< GridViewType >(boundary_info_)); } // ... setup(...) const DiffusionType& diffusion_; const BoundaryInfoType& boundary_info_; const VolumeOperatorType volume_operator_; const VolumeAssemblerType volume_assembler_; const CouplingOperatorType coupling_operator_; const CouplingAssemblerType coupling_assembler_; const DirichletBoundaryOperatorType dirichlet_boundary_operator_; const DirichletBoundaryAssemblerType dirichlet_boundary_assembler_; }; // class EllipticSWIPDG template< class DF, class M, class S > std::unique_ptr< EllipticSWIPDG< DF, M, S, S, typename S::GridViewType > > make_elliptic_swipdg(const DF& diffusion_factor, const Stuff::Grid::BoundaryInfoInterface< typename S::GridViewType::Intersection >& boundary_info, const M& /*matrix*/, const S& space) { return Stuff::Common::make_unique< EllipticSWIPDG< DF, M, S, S, typename S::GridViewType > >(diffusion_factor, boundary_info, space); } // ... make_elliptic_swipdg(...) template< class DF, class M, class S > std::unique_ptr< EllipticSWIPDG< DF, M, S, S, typename S::GridViewType > > make_elliptic_swipdg(const DF& diffusion_factor, const Stuff::Grid::BoundaryInfoInterface< typename S::GridViewType::Intersection >& boundary_info, M& matrix, const S& space) { return Stuff::Common::make_unique< EllipticSWIPDG< DF, M, S, S, typename S::GridViewType > >(diffusion_factor, boundary_info, matrix, space); } // ... make_elliptic_swipdg(...) } // namespace Operators } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_ELLIPTIC_SWIPDG_HH
// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATORS_ELLIPTIC_SWIPDG_HH #define DUNE_GDT_OPERATORS_ELLIPTIC_SWIPDG_HH #include <type_traits> #include <dune/stuff/la/container/interfaces.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/stuff/common/memory.hh> #include <dune/stuff/grid/boundaryinfo.hh> #include <dune/gdt/spaces/interface.hh> #include <dune/gdt/localevaluation/elliptic.hh> #include <dune/gdt/localevaluation/swipdg.hh> #include <dune/gdt/localoperator/codim0.hh> #include <dune/gdt/localoperator/codim1.hh> #include <dune/gdt/assembler/local/codim0.hh> #include <dune/gdt/assembler/local/codim1.hh> #include <dune/gdt/assembler/system.hh> #include "base.hh" namespace Dune { namespace GDT { namespace Operators { // forwards template< class DiffusionFactorType , class MatrixImp , class SourceSpaceImp , class RangeSpaceImp = SourceSpaceImp , class GridViewImp = typename SourceSpaceImp::GridViewType , class DiffusionTensorType = void > class EllipticSWIPDG; namespace internal { template< class DiffusionFactorType , class MatrixImp , class SourceSpaceImp , class RangeSpaceImp , class GridViewImp , class DiffusionTensorType = void > class EllipticSWIPDGTraits { static_assert(std::is_base_of< Stuff::Tags::LocalizableFunction, DiffusionFactorType >::value, "DiffusionFactorType has to be derived from Stuff::LocalizableFunctionInterface!"); static_assert(std::is_base_of< Stuff::Tags::LocalizableFunction, DiffusionTensorType >::value, "DiffusionTensorType has to be derived from Stuff::LocalizableFunctionInterface!"); static_assert(std::is_base_of < Stuff::LA::MatrixInterface< typename MatrixImp::Traits, typename MatrixImp::Traits::ScalarType >, MatrixImp >::value, "MatrixImp has to be derived from Stuff::LA::MatrixInterface!"); static_assert(std::is_base_of< SpaceInterface< typename SourceSpaceImp::Traits >, SourceSpaceImp >::value, "SourceSpaceImp has to be derived from SpaceInterface!"); static_assert(std::is_base_of< SpaceInterface< typename RangeSpaceImp::Traits >, RangeSpaceImp >::value, "RangeSpaceImp has to be derived from SpaceInterface!"); public: typedef EllipticSWIPDG< DiffusionFactorType, MatrixImp, SourceSpaceImp , RangeSpaceImp, GridViewImp, DiffusionTensorType > derived_type; typedef MatrixImp MatrixType; typedef SourceSpaceImp SourceSpaceType; typedef RangeSpaceImp RangeSpaceType; typedef GridViewImp GridViewType; }; // class EllipticSWIPDGTraits template< class DiffusionType , class MatrixImp , class SourceSpaceImp , class RangeSpaceImp , class GridViewImp > class EllipticSWIPDGTraits< DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp, void > { static_assert(std::is_base_of< Stuff::Tags::LocalizableFunction, DiffusionType >::value, "DiffusionType has to be derived from Stuff::LocalizableFunctionInterface!"); static_assert(std::is_base_of < Stuff::LA::MatrixInterface< typename MatrixImp::Traits, typename MatrixImp::Traits::ScalarType >, MatrixImp >::value, "MatrixImp has to be derived from Stuff::LA::MatrixInterface!"); static_assert(std::is_base_of< SpaceInterface< typename SourceSpaceImp::Traits >, SourceSpaceImp >::value, "SourceSpaceImp has to be derived from SpaceInterface!"); static_assert(std::is_base_of< SpaceInterface< typename RangeSpaceImp::Traits >, RangeSpaceImp >::value, "RangeSpaceImp has to be derived from SpaceInterface!"); public: typedef EllipticSWIPDG< DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp, void > derived_type; typedef MatrixImp MatrixType; typedef SourceSpaceImp SourceSpaceType; typedef RangeSpaceImp RangeSpaceType; typedef GridViewImp GridViewType; }; // class EllipticSWIPDGTraits } // namespace internal template< class DiffusionType, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp, class GridViewImp > class EllipticSWIPDG< DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp, void > : Stuff::Common::StorageProvider< MatrixImp > , public Operators::MatrixBased< internal::EllipticSWIPDGTraits< DiffusionType, MatrixImp, SourceSpaceImp , RangeSpaceImp, GridViewImp, void > > , public SystemAssembler< RangeSpaceImp, GridViewImp, SourceSpaceImp > { typedef Stuff::Common::StorageProvider< MatrixImp > StorageProvider; typedef SystemAssembler< RangeSpaceImp, GridViewImp, SourceSpaceImp > AssemblerBaseType; typedef Operators::MatrixBased< internal::EllipticSWIPDGTraits< DiffusionType, MatrixImp , SourceSpaceImp, RangeSpaceImp , GridViewImp, void > > OperatorBaseType; typedef LocalOperator::Codim0Integral< LocalEvaluation::Elliptic< DiffusionType > > VolumeOperatorType; typedef LocalAssembler::Codim0Matrix< VolumeOperatorType > VolumeAssemblerType; typedef LocalOperator::Codim1CouplingIntegral< LocalEvaluation::SWIPDG::Inner< DiffusionType > > CouplingOperatorType; typedef LocalAssembler::Codim1CouplingMatrix< CouplingOperatorType > CouplingAssemblerType; typedef LocalOperator::Codim1BoundaryIntegral< LocalEvaluation::SWIPDG::BoundaryLHS< DiffusionType > > DirichletBoundaryOperatorType; typedef LocalAssembler::Codim1BoundaryMatrix< DirichletBoundaryOperatorType > DirichletBoundaryAssemblerType; typedef typename MatrixImp::ScalarType ScalarType; public: typedef internal::EllipticSWIPDGTraits< DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp, void > Traits; typedef typename Traits::MatrixType MatrixType; typedef typename Traits::SourceSpaceType SourceSpaceType; typedef typename Traits::RangeSpaceType RangeSpaceType; typedef typename Traits::GridViewType GridViewType; typedef Stuff::Grid::BoundaryInfoInterface< typename GridViewType::Intersection > BoundaryInfoType; using OperatorBaseType::pattern; static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space, const SourceSpaceType& source_space, const GridViewType& grid_view) { return range_space.compute_face_and_volume_pattern(grid_view, source_space); } EllipticSWIPDG(const DiffusionType& diffusion, const BoundaryInfoType& boundary_info, MatrixType& matrix, const SourceSpaceType& source_space, const RangeSpaceType& range_space, const GridViewType& grid_view, const ScalarType beta = LocalEvaluation::SWIPDG::internal::default_beta(GridViewType::dimension)) : StorageProvider(matrix) , OperatorBaseType(this->storage_access(), source_space, range_space, grid_view) , AssemblerBaseType(range_space, grid_view, source_space) , diffusion_(diffusion) , boundary_info_(boundary_info) , volume_operator_(diffusion_) , volume_assembler_(volume_operator_) , coupling_operator_(diffusion_, beta) , coupling_assembler_(coupling_operator_) , dirichlet_boundary_operator_(diffusion_, beta) , dirichlet_boundary_assembler_(dirichlet_boundary_operator_) { setup(); } EllipticSWIPDG(const DiffusionType& diffusion, const BoundaryInfoType& boundary_info, const SourceSpaceType& source_space, const RangeSpaceType& range_space, const GridViewType& grid_view, const ScalarType beta = LocalEvaluation::SWIPDG::internal::default_beta(GridViewType::dimension)) : StorageProvider(new MatrixType(range_space.mapper().size(), source_space.mapper().size(), pattern(range_space, source_space, grid_view))) , OperatorBaseType(this->storage_access(), source_space, range_space, grid_view) , AssemblerBaseType(range_space, grid_view, source_space) , diffusion_(diffusion) , boundary_info_(boundary_info) , volume_operator_(diffusion_) , volume_assembler_(volume_operator_) , coupling_operator_(diffusion_, beta) , coupling_assembler_(coupling_operator_) , dirichlet_boundary_operator_(diffusion_, beta) , dirichlet_boundary_assembler_(dirichlet_boundary_operator_) { setup(); } EllipticSWIPDG(const DiffusionType& diffusion, const BoundaryInfoType& boundary_info, MatrixType& matrix, const SourceSpaceType& source_space, const RangeSpaceType& range_space, const ScalarType beta = LocalEvaluation::SWIPDG::internal::default_beta(GridViewType::dimension)) : StorageProvider(matrix) , OperatorBaseType(this->storage_access(), source_space, range_space) , AssemblerBaseType(range_space, source_space) , diffusion_(diffusion) , boundary_info_(boundary_info) , volume_operator_(diffusion_) , volume_assembler_(volume_operator_) , coupling_operator_(diffusion_, beta) , coupling_assembler_(coupling_operator_) , dirichlet_boundary_operator_(diffusion_, beta) , dirichlet_boundary_assembler_(dirichlet_boundary_operator_) { setup(); } EllipticSWIPDG(const DiffusionType& diffusion, const BoundaryInfoType& boundary_info, const SourceSpaceType& source_space, const RangeSpaceType& range_space, const ScalarType beta = LocalEvaluation::SWIPDG::internal::default_beta(GridViewType::dimension)) : StorageProvider(new MatrixType(range_space.mapper().size(), source_space.mapper().size(), pattern(range_space, source_space))) , OperatorBaseType(this->storage_access(), source_space, range_space) , AssemblerBaseType(range_space, source_space) , diffusion_(diffusion) , boundary_info_(boundary_info) , volume_operator_(diffusion_) , volume_assembler_(volume_operator_) , coupling_operator_(diffusion_, beta) , coupling_assembler_(coupling_operator_) , dirichlet_boundary_operator_(diffusion_, beta) , dirichlet_boundary_assembler_(dirichlet_boundary_operator_) { setup(); } EllipticSWIPDG(const DiffusionType& diffusion, const BoundaryInfoType& boundary_info, MatrixType& matrix, const SourceSpaceType& source_space, const ScalarType beta = LocalEvaluation::SWIPDG::internal::default_beta(GridViewType::dimension)) : StorageProvider(matrix) , OperatorBaseType(this->storage_access(), source_space) , AssemblerBaseType(source_space) , diffusion_(diffusion) , boundary_info_(boundary_info) , volume_operator_(diffusion_) , volume_assembler_(volume_operator_) , coupling_operator_(diffusion_, beta) , coupling_assembler_(coupling_operator_) , dirichlet_boundary_operator_(diffusion_, beta) , dirichlet_boundary_assembler_(dirichlet_boundary_operator_) { setup(); } EllipticSWIPDG(const DiffusionType& diffusion, const BoundaryInfoType& boundary_info, const SourceSpaceType& source_space, const ScalarType beta = LocalEvaluation::SWIPDG::internal::default_beta(GridViewType::dimension)) : StorageProvider(new MatrixType(source_space.mapper().size(), source_space.mapper().size(), pattern(source_space))) , OperatorBaseType(this->storage_access(), source_space) , AssemblerBaseType(source_space) , diffusion_(diffusion) , boundary_info_(boundary_info) , volume_operator_(diffusion_) , volume_assembler_(volume_operator_) , coupling_operator_(diffusion_, beta) , coupling_assembler_(coupling_operator_) , dirichlet_boundary_operator_(diffusion_, beta) , dirichlet_boundary_assembler_(dirichlet_boundary_operator_) { setup(); } virtual ~EllipticSWIPDG() {} virtual void assemble() override final { AssemblerBaseType::assemble(); } private: void setup() { this->add(volume_assembler_, this->matrix()); this->add(coupling_assembler_, this->matrix(), new Stuff::Grid::ApplyOn::InnerIntersectionsPrimally< GridViewType >()); this->add(dirichlet_boundary_assembler_, this->matrix(), new Stuff::Grid::ApplyOn::DirichletIntersections< GridViewType >(boundary_info_)); } // ... setup(...) const DiffusionType& diffusion_; const BoundaryInfoType& boundary_info_; const VolumeOperatorType volume_operator_; const VolumeAssemblerType volume_assembler_; const CouplingOperatorType coupling_operator_; const CouplingAssemblerType coupling_assembler_; const DirichletBoundaryOperatorType dirichlet_boundary_operator_; const DirichletBoundaryAssemblerType dirichlet_boundary_assembler_; }; // class EllipticSWIPDG /// \todo use matrix as first template parameter, dro /*matrix*/ /// \todo return by value, implement move ctor template< class DF, class M, class S > std::unique_ptr< EllipticSWIPDG< DF, M, S, S, typename S::GridViewType > > make_elliptic_swipdg(const DF& diffusion_factor, const Stuff::Grid::BoundaryInfoInterface< typename S::GridViewType::Intersection >& boundary_info, const M& /*matrix*/, const S& space) { return Stuff::Common::make_unique< EllipticSWIPDG< DF, M, S, S, typename S::GridViewType > >(diffusion_factor, boundary_info, space); } // ... make_elliptic_swipdg(...) template< class DF, class M, class S > std::unique_ptr< EllipticSWIPDG< DF, M, S, S, typename S::GridViewType > > make_elliptic_swipdg(const DF& diffusion_factor, const Stuff::Grid::BoundaryInfoInterface< typename S::GridViewType::Intersection >& boundary_info, M& matrix, const S& space) { return Stuff::Common::make_unique< EllipticSWIPDG< DF, M, S, S, typename S::GridViewType > >(diffusion_factor, boundary_info, matrix, space); } // ... make_elliptic_swipdg(...) } // namespace Operators } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_ELLIPTIC_SWIPDG_HH
add todo, refs #32
[operators.elliptic-swipdg] add todo, refs #32
C++
bsd-2-clause
ftalbrecht/dune-gdt,BarbaraV/dune-gdt
1ed0b405281a7f2c9d5a587371c0b51794acc862
dune/grid/multiscale/provider/cube.hh
dune/grid/multiscale/provider/cube.hh
// This file is part of the dune-grid-multiscale project: // http://users.dune-project.org/projects/dune-grid-multiscale // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GRID_MULTISCALE_PROVIDER_CUBE_HH #define DUNE_GRID_MULTISCALE_PROVIDER_CUBE_HH #include <vector> #include <memory> #include <type_traits> #include <dune/common/exceptions.hh> #include <dune/grid/common/mcmgmapper.hh> #include <dune/grid/io/file/vtk/vtkwriter.hh> #include <dune/grid/io/file/dgfparser.hh> #if HAVE_ALUGRID #include <dune/grid/alugrid.hh> #endif #include <dune/stuff/grid/provider/cube.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/common/print.hh> #include <dune/stuff/common/memory.hh> #include <dune/stuff/common/type_utils.hh> #include <dune/grid/multiscale/factory/default.hh> #include "interface.hh" namespace Dune { namespace grid { namespace Multiscale { namespace Providers { #if HAVE_DUNE_FEM template <class GridImp> class Cube : public ProviderInterface<GridImp> { typedef ProviderInterface<GridImp> BaseType; typedef Cube<GridImp> ThisType; public: typedef typename BaseType::GridType GridType; typedef typename BaseType::MsGridType MsGridType; static const unsigned int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; static std::string static_id() { return BaseType::static_id() + ".cube"; } static Stuff::Common::Configuration default_config(const std::string sub_name = "") { Stuff::Common::Configuration config; config["type"] = static_id(); config["lower_left"] = "[0.0 0.0 0.0]"; config["upper_right"] = "[1.0 1.0 1.0]"; config["num_elements"] = "[8 8 8]"; config["num_partitions"] = "[2 2 2]"; config["oversampling_layers"] = "0"; if (sub_name.empty()) return config; else { Stuff::Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... createSampleDescription(...) static std::unique_ptr<ThisType> create(const Stuff::Common::Configuration config = default_config(), const std::string sub_name = static_id()) { // get correct config const Stuff::Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Stuff::Common::Configuration default_cfg = default_config(); return Stuff::Common::make_unique<ThisType>( cfg.get("lower_left", default_cfg.get<DomainType>("lower_left"), dimDomain), cfg.get("upper_right", default_cfg.get<DomainType>("upper_right"), dimDomain), cfg.get("num_elements", default_cfg.get<std::vector<unsigned int>>("num_elements"), dimDomain), cfg.get("num_partitions", default_cfg.get<std::vector<size_t>>("num_partitions"), dimDomain), cfg.get("oversampling_layers", default_cfg.get<size_t>("oversampling_layers"))); } // ... create(...) Cube(const DomainType lower_left = default_config().get<DomainType>("lower_left"), const DomainType upper_right = default_config().get<DomainType>("upper_right"), const std::vector<unsigned int> num_elements = default_config().get<std::vector<unsigned int>>("num_elements"), const std::vector<size_t> num_partittions = default_config().get<std::vector<size_t>>("num_partitions", dimDomain), const size_t num_oversampling_layers = default_config().get<size_t>("oversampling_layers"), std::ostream& out = DSC_LOG.devnull(), const std::string prefix = "") { if (num_partittions.size() < dimDomain) DUNE_THROW(Dune::RangeError, "num_partittions has to be at least of size " << dimDomain << " (is " << num_partittions.size() << ")!"); #ifndef DUNE_GRID_MULTISCALE_PROVIDER_CUBE_DISABLE_CHECKS for (size_t ii = 0; ii < dimDomain; ++ii) { if (num_partittions[ii] > num_elements[ii]) DUNE_THROW(Dune::RangeError, num_partittions[ii] << " = num_partittions[" << ii << "] has to be smaller than " << "num_elements[" << ii << "] = " << num_elements[ii] << "!)"); } #endif // DUNE_GRID_MULTISCALE_PROVIDER_CUBE_DISABLE_CHECKS typedef Dune::Stuff::Grid::Providers::Cube<GridType> CubeGridProvider; auto grd_ptr = CubeGridProvider(lower_left, upper_right, num_elements).grid_ptr(); #if HAVE_ALUGRID if (std::is_same<GridType, ALUGrid<2, 2, simplex, conforming>>::value) grd_ptr->globalRefine(1); #endif grid_ = grd_ptr; setup(lower_left, upper_right, num_partittions, num_oversampling_layers, out, prefix); } Cube(const std::shared_ptr<const GridType> grd, const DomainType lower_left = default_config().get<DomainType>("lower_left"), const DomainType upper_right = default_config().get<DomainType>("upper_right"), const std::vector<size_t> num_partittions = default_config().get<std::vector<size_t>>("num_partitions", dimDomain), const size_t num_oversampling_layers = default_config().get<size_t>("oversampling_layers"), std::ostream& out = DSC_LOG.devnull(), const std::string prefix = "") : grid_(grd) { if (num_partittions.size() < dimDomain) DUNE_THROW(Dune::RangeError, "num_partittions has to be at least of size " << dimDomain << " (is " << num_partittions.size() << ")!"); for (size_t ii = 0; ii < dimDomain; ++ii) { if (lower_left[ii] >= upper_right[ii]) DUNE_THROW(Dune::RangeError, lower_left[ii] << " = lower_left[" << ii << "] has to be smaller than upper_right[" << ii << "] = " << upper_right[ii] << "!)"); } setup(lower_left, upper_right, num_partittions, num_oversampling_layers, out, prefix); } virtual const GridType& grid() const override { return *grid_; } virtual const std::shared_ptr<const MsGridType>& ms_grid() const override { return ms_grid_; } std::shared_ptr<const GridType> grid_ptr() const { return grid_; } virtual std::unique_ptr<Stuff::Grid::ConstProviderInterface<GridType>> copy() const { DUNE_THROW(NotImplemented, ""); } private: void setup(const DomainType& lower_left, const DomainType& upper_right, const std::vector<size_t>& num_partitions, const size_t num_oversampling_layers, std::ostream& out = DSC_LOG.devnull(), const std::string prefix = "") { typedef Dune::grid::Multiscale::Factory::Default<GridType> MsGridFactoryType; const size_t neighbor_recursion_level = Factory::NeighborRecursionLevel<GridType>::compute(); // prepare MsGridFactoryType factory(grid_); factory.prepare(); #ifndef NDEBUG // debug output out << prefix << static_id() << ":" << std::endl; Stuff::Common::print(lower_left, "lower_left", out, prefix); Stuff::Common::print(upper_right, "upper_right", out, prefix); Stuff::Common::print(num_partitions, "num_partitions", out, prefix); #endif // NDEBUG // global grid part typedef typename MsGridType::GlobalGridPartType GridPartType; const auto global_grid_part = factory.globalGridPart(); // walk the grid const auto entity_it_end = global_grid_part->template end<0>(); for (auto entity_it = global_grid_part->template begin<0>(); entity_it != entity_it_end; ++entity_it) { // get center of entity const auto& entity = *entity_it; const auto center = entity.geometry().center(); #ifndef NDEBUG const size_t entity_index = global_grid_part->indexSet().index(entity); Stuff::Common::print(center, "entity (" + Stuff::Common::toString(entity_index) + ")", out, prefix); #endif // NDEBUG // decide on the subdomain this entity shall belong to std::vector<size_t> whichPartition(dimDomain, 0); for (size_t dd = 0; dd < dimDomain; ++dd) whichPartition[dd] = (std::min((size_t)(std::floor(num_partitions[dd] * ((center[dd] - lower_left[dd]) / (upper_right[dd] - lower_left[dd])))), num_partitions[dd] - 1)); size_t subdomain = 0; if (dimDomain == 1) subdomain = whichPartition[0]; else if (dimDomain == 2) subdomain = whichPartition[0] + whichPartition[1] * num_partitions[0]; else if (dimDomain == 3) subdomain = whichPartition[0] + whichPartition[1] * num_partitions[0] + whichPartition[2] * num_partitions[1] * num_partitions[0]; else DUNE_THROW(Dune::NotImplemented, "ERROR in " << static_id() << ": not implemented for grid dimDomains other than 1, 2 or 3!"); // add entity to subdomain factory.add(entity, subdomain, prefix + " ", out); } // walk the grid // finalize factory.finalize(num_oversampling_layers, neighbor_recursion_level, prefix + " ", out); // debug << std::flush; // be done with it ms_grid_ = factory.createMsGrid(); } // void setup(const Dune::ParameterTree& paramTree) std::shared_ptr<const GridType> grid_; std::shared_ptr<const MsGridType> ms_grid_; }; // class Cube #else // HAVE_DUNE_FEM template <class GridImp> class Cube { static_assert(AlwaysFalse<GridImp>::value, "Your are missing dune-fem!"); }; #endif // HAVE_DUNE_FEM } // namespace Providers } // namespace Multiscale } // namespace Grid } // namespace Dune #endif // DUNE_GRID_MULTISCALE_PROVIDER_CUBE_HH
// This file is part of the dune-grid-multiscale project: // http://users.dune-project.org/projects/dune-grid-multiscale // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GRID_MULTISCALE_PROVIDER_CUBE_HH #define DUNE_GRID_MULTISCALE_PROVIDER_CUBE_HH #include <vector> #include <memory> #include <type_traits> #include <dune/common/exceptions.hh> #include <dune/grid/common/mcmgmapper.hh> #include <dune/grid/io/file/vtk/vtkwriter.hh> #include <dune/grid/io/file/dgfparser.hh> #if HAVE_ALUGRID #include <dune/grid/alugrid.hh> #endif #include <dune/stuff/grid/provider/cube.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/common/print.hh> #include <dune/stuff/common/memory.hh> #include <dune/stuff/common/type_utils.hh> #include <dune/grid/multiscale/factory/default.hh> #include "interface.hh" namespace Dune { namespace grid { namespace Multiscale { namespace Providers { #if HAVE_DUNE_FEM template <class GridImp> class Cube : public ProviderInterface<GridImp> { typedef ProviderInterface<GridImp> BaseType; typedef Cube<GridImp> ThisType; public: typedef typename BaseType::GridType GridType; typedef typename BaseType::MsGridType MsGridType; static const unsigned int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; static std::string static_id() { return BaseType::static_id() + ".cube"; } static Stuff::Common::Configuration default_config(const std::string sub_name = "") { Stuff::Common::Configuration config; config["type"] = static_id(); config["lower_left"] = "[0.0 0.0 0.0]"; config["upper_right"] = "[1.0 1.0 1.0]"; config["num_elements"] = "[8 8 8]"; config["num_partitions"] = "[2 2 2]"; config["oversampling_layers"] = "0"; if (sub_name.empty()) return config; else { Stuff::Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... createSampleDescription(...) static std::unique_ptr<ThisType> create(const Stuff::Common::Configuration config = default_config(), const std::string sub_name = static_id()) { // get correct config const Stuff::Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Stuff::Common::Configuration default_cfg = default_config(); return Stuff::Common::make_unique<ThisType>( cfg.get("lower_left", default_cfg.get<DomainType>("lower_left"), dimDomain), cfg.get("upper_right", default_cfg.get<DomainType>("upper_right"), dimDomain), cfg.get("num_elements", default_cfg.get<std::vector<unsigned int>>("num_elements"), dimDomain), cfg.get("num_partitions", default_cfg.get<std::vector<size_t>>("num_partitions"), dimDomain), cfg.get("oversampling_layers", default_cfg.get<size_t>("oversampling_layers"))); } // ... create(...) Cube(const DomainType lower_left = default_config().template get<DomainType>("lower_left"), const DomainType upper_right = default_config().template get<DomainType>("upper_right"), const std::vector<unsigned int> num_elements = default_config().template get<std::vector<unsigned int>>("num_elements"), const std::vector<size_t> num_partittions = default_config().template get<std::vector<size_t>>("num_partitions", dimDomain), const size_t num_oversampling_layers = default_config().template get<size_t>("oversampling_layers"), std::ostream& out = DSC_LOG.devnull(), const std::string prefix = "") { if (num_partittions.size() < dimDomain) DUNE_THROW(Dune::RangeError, "num_partittions has to be at least of size " << dimDomain << " (is " << num_partittions.size() << ")!"); #ifndef DUNE_GRID_MULTISCALE_PROVIDER_CUBE_DISABLE_CHECKS for (size_t ii = 0; ii < dimDomain; ++ii) { if (num_partittions[ii] > num_elements[ii]) DUNE_THROW(Dune::RangeError, num_partittions[ii] << " = num_partittions[" << ii << "] has to be smaller than " << "num_elements[" << ii << "] = " << num_elements[ii] << "!)"); } #endif // DUNE_GRID_MULTISCALE_PROVIDER_CUBE_DISABLE_CHECKS typedef Dune::Stuff::Grid::Providers::Cube<GridType> CubeGridProvider; auto grd_ptr = CubeGridProvider(lower_left, upper_right, num_elements).grid_ptr(); #if HAVE_ALUGRID if (std::is_same<GridType, ALUGrid<2, 2, simplex, conforming>>::value) grd_ptr->globalRefine(1); #endif grid_ = grd_ptr; setup(lower_left, upper_right, num_partittions, num_oversampling_layers, out, prefix); } Cube(const std::shared_ptr<const GridType> grd, const DomainType lower_left = default_config().template get<DomainType>("lower_left"), const DomainType upper_right = default_config().template get<DomainType>("upper_right"), const std::vector<size_t> num_partittions = default_config().template get<std::vector<size_t>>("num_partitions", dimDomain), const size_t num_oversampling_layers = default_config().template get<size_t>("oversampling_layers"), std::ostream& out = DSC_LOG.devnull(), const std::string prefix = "") : grid_(grd) { if (num_partittions.size() < dimDomain) DUNE_THROW(Dune::RangeError, "num_partittions has to be at least of size " << dimDomain << " (is " << num_partittions.size() << ")!"); for (size_t ii = 0; ii < dimDomain; ++ii) { if (lower_left[ii] >= upper_right[ii]) DUNE_THROW(Dune::RangeError, lower_left[ii] << " = lower_left[" << ii << "] has to be smaller than upper_right[" << ii << "] = " << upper_right[ii] << "!)"); } setup(lower_left, upper_right, num_partittions, num_oversampling_layers, out, prefix); } virtual const GridType& grid() const override { return *grid_; } virtual const std::shared_ptr<const MsGridType>& ms_grid() const override { return ms_grid_; } std::shared_ptr<const GridType> grid_ptr() const { return grid_; } virtual std::unique_ptr<Stuff::Grid::ConstProviderInterface<GridType>> copy() const { DUNE_THROW(NotImplemented, ""); } private: void setup(const DomainType& lower_left, const DomainType& upper_right, const std::vector<size_t>& num_partitions, const size_t num_oversampling_layers, std::ostream& out = DSC_LOG.devnull(), const std::string prefix = "") { typedef Dune::grid::Multiscale::Factory::Default<GridType> MsGridFactoryType; const size_t neighbor_recursion_level = Factory::NeighborRecursionLevel<GridType>::compute(); // prepare MsGridFactoryType factory(grid_); factory.prepare(); #ifndef NDEBUG // debug output out << prefix << static_id() << ":" << std::endl; Stuff::Common::print(lower_left, "lower_left", out, prefix); Stuff::Common::print(upper_right, "upper_right", out, prefix); Stuff::Common::print(num_partitions, "num_partitions", out, prefix); #endif // NDEBUG // global grid part typedef typename MsGridType::GlobalGridPartType GridPartType; const auto global_grid_part = factory.globalGridPart(); // walk the grid const auto entity_it_end = global_grid_part->template end<0>(); for (auto entity_it = global_grid_part->template begin<0>(); entity_it != entity_it_end; ++entity_it) { // get center of entity const auto& entity = *entity_it; const auto center = entity.geometry().center(); #ifndef NDEBUG const size_t entity_index = global_grid_part->indexSet().index(entity); Stuff::Common::print(center, "entity (" + Stuff::Common::toString(entity_index) + ")", out, prefix); #endif // NDEBUG // decide on the subdomain this entity shall belong to std::vector<size_t> whichPartition(dimDomain, 0); for (size_t dd = 0; dd < dimDomain; ++dd) whichPartition[dd] = (std::min((size_t)(std::floor(num_partitions[dd] * ((center[dd] - lower_left[dd]) / (upper_right[dd] - lower_left[dd])))), num_partitions[dd] - 1)); size_t subdomain = 0; if (dimDomain == 1) subdomain = whichPartition[0]; else if (dimDomain == 2) subdomain = whichPartition[0] + whichPartition[1] * num_partitions[0]; else if (dimDomain == 3) subdomain = whichPartition[0] + whichPartition[1] * num_partitions[0] + whichPartition[2] * num_partitions[1] * num_partitions[0]; else DUNE_THROW(Dune::NotImplemented, "ERROR in " << static_id() << ": not implemented for grid dimDomains other than 1, 2 or 3!"); // add entity to subdomain factory.add(entity, subdomain, prefix + " ", out); } // walk the grid // finalize factory.finalize(num_oversampling_layers, neighbor_recursion_level, prefix + " ", out); // debug << std::flush; // be done with it ms_grid_ = factory.createMsGrid(); } // void setup(const Dune::ParameterTree& paramTree) std::shared_ptr<const GridType> grid_; std::shared_ptr<const MsGridType> ms_grid_; }; // class Cube #else // HAVE_DUNE_FEM template <class GridImp> class Cube { static_assert(AlwaysFalse<GridImp>::value, "Your are missing dune-fem!"); }; #endif // HAVE_DUNE_FEM } // namespace Providers } // namespace Multiscale } // namespace Grid } // namespace Dune #endif // DUNE_GRID_MULTISCALE_PROVIDER_CUBE_HH
make gcc-6.1.1 happy
make gcc-6.1.1 happy
C++
bsd-2-clause
pymor/dune-grid-multiscale
b4bed96ea56cf8ce2fadcebe0d81315734c0be66
src/SpectrumMatch.cpp
src/SpectrumMatch.cpp
#include <algorithm> #include <math.h> #include <tuple> #include "SpectrumMatch.h" using namespace ann_solo; SpectrumSpectrumMatch* SpectrumMatcher::dot( Spectrum *query, std::vector<Spectrum*> candidates, double fragment_mz_tolerance, bool allow_shift) { // compute a dot product score between the query spectrum and each candidate spectrum SpectrumSpectrumMatch *best_match = NULL; for(unsigned int candidate_index = 0; candidate_index < candidates.size(); candidate_index++) { Spectrum *candidate = candidates[candidate_index]; // compile a list of (potentially shifted) peaks for the candidate spectrum std::vector<Peak> candidate_peaks; for(unsigned int peak_index = 0; peak_index < candidate->getNumPeaks(); peak_index++) { candidate_peaks.push_back(Peak(candidate->getPeakMass(peak_index), candidate->getPeakIntensity(peak_index), unshifted, peak_index)); } // add shifted peaks if necessary double mass_dif = (query->getPrecursorMz() - candidate->getPrecursorMz()) * candidate->getPrecursorCharge(); if(allow_shift && mass_dif > fragment_mz_tolerance) { for(unsigned int peak_index = 0; peak_index < candidate->getNumPeaks(); peak_index++) { // peaks with a known charge (and therefore annotation) are shifted with a mass difference corresponding to this charge if(candidate->getPeakCharge(peak_index) > 0) { unsigned int charge = candidate->getPeakCharge(peak_index); double mass = candidate->getPeakMass(peak_index) - mass_dif / charge; if(mass > 0) { candidate_peaks.push_back(Peak(mass, candidate->getPeakIntensity(peak_index), shifted_annotation, peak_index)); } } // peaks without a known charge are shifted with a mass difference corresponding to all charges up to the precursor charge else { for(unsigned int charge = 1; charge < candidate->getPrecursorCharge(); charge++) { double mass = candidate->getPeakMass(peak_index) - mass_dif / charge; if(mass > 0) { candidate_peaks.push_back(Peak(mass, candidate->getPeakIntensity(peak_index), shifted, peak_index)); } } } } std::sort(candidate_peaks.begin(), candidate_peaks.end(), [](auto &peak1, auto &peak2) { return peak1.getMass() < peak2.getMass(); }); } // find the matching peaks between the query spectrum and the candidate spectrum std::vector<std::tuple<float, unsigned int, unsigned int>> peak_matches; unsigned int candidate_peak_index = 0; for(unsigned int query_peak_index = 0; query_peak_index < query->getNumPeaks(); query_peak_index++) { float query_peak_mass = query->getPeakMass(query_peak_index); float query_peak_intensity = query->getPeakIntensity(query_peak_index); // advance while there is an excessive mass difference while(candidate_peak_index < candidate_peaks.size() - 1 && query_peak_mass - fragment_mz_tolerance > candidate_peaks[candidate_peak_index].getMass()) { candidate_peak_index++; } // match the peaks within the fragment mass window if possible for(unsigned int index = 0; candidate_peak_index + index < candidate_peaks.size() && fabs(query_peak_mass - candidate_peaks[candidate_peak_index + index].getMass()) <= fragment_mz_tolerance; index++) { // slightly penalize matching peaks without an annotation double match_multiplier; switch(candidate_peaks[candidate_peak_index + index].getPeakStatus()) { case unshifted: match_multiplier = 1.0; break; case shifted_annotation: match_multiplier = 1.0; break; case shifted: match_multiplier = 2.0 / 3.0; break; default: match_multiplier = 0.0; break; } if(match_multiplier > 0.0) { peak_matches.push_back(std::make_tuple(match_multiplier * query_peak_intensity * candidate_peaks[candidate_peak_index + index].getIntensity(), query_peak_index, candidate_peaks[candidate_peak_index + index].getIndex())); } } } candidate_peaks.clear(); // use the most prominent peak matches to compute the score (sort in descending order) std::sort(peak_matches.begin(), peak_matches.end(), [](auto &peak_match1, auto &peak_match2) { return std::get<0>(peak_match1) > std::get<0>(peak_match2); }); SpectrumSpectrumMatch *this_match = new SpectrumSpectrumMatch(candidate_index); std::vector<bool> query_peaks_used(query->getNumPeaks(), false); std::vector<bool> candidate_peaks_used(candidate->getNumPeaks(), false); for(unsigned int peak_match_index = 0; peak_match_index < peak_matches.size(); peak_match_index++) { std::tuple<double, unsigned int, unsigned int> peak_match = peak_matches[peak_match_index]; unsigned int query_peak_index = std::get<1>(peak_match); unsigned int candidate_peak_index = std::get<2>(peak_match); if(query_peaks_used[query_peak_index] == false && candidate_peaks_used[candidate_peak_index] == false) { this_match->setScore(this_match->getScore() + std::get<0>(peak_match)); // save the matched peaks this_match->addPeakMatch(query_peak_index, candidate_peak_index); // make sure these peaks are not used anymore query_peaks_used[query_peak_index] = true; candidate_peaks_used[candidate_peak_index] = true; } } query_peaks_used.clear(); candidate_peaks_used.clear(); peak_matches.clear(); // retain the match with the highest score if(best_match == NULL || best_match->getScore() < this_match->getScore()) { if(best_match != NULL) { delete best_match; } best_match = this_match; } else { delete this_match; } } return best_match; }
#include <algorithm> #include <math.h> #include <tuple> #include "SpectrumMatch.h" using namespace ann_solo; SpectrumSpectrumMatch* SpectrumMatcher::dot( Spectrum *query, std::vector<Spectrum*> candidates, double fragment_mz_tolerance, bool allow_shift) { // compute a dot product score between the query spectrum and each candidate spectrum SpectrumSpectrumMatch *best_match = NULL; for(unsigned int candidate_index = 0; candidate_index < candidates.size(); candidate_index++) { Spectrum *candidate = candidates[candidate_index]; // compile a list of (potentially shifted) peaks for the candidate spectrum std::vector<Peak> candidate_peaks; for(unsigned int peak_index = 0; peak_index < candidate->getNumPeaks(); peak_index++) { candidate_peaks.push_back(Peak(candidate->getPeakMass(peak_index), candidate->getPeakIntensity(peak_index), unshifted, peak_index)); } // add shifted peaks if necessary double mass_dif = (query->getPrecursorMz() - candidate->getPrecursorMz()) * candidate->getPrecursorCharge(); if(allow_shift && fabs(mass_dif) > fragment_mz_tolerance) { for(unsigned int peak_index = 0; peak_index < candidate->getNumPeaks(); peak_index++) { // peaks with a known charge (and therefore annotation) are shifted with a mass difference corresponding to this charge if(candidate->getPeakCharge(peak_index) > 0) { unsigned int charge = candidate->getPeakCharge(peak_index); double mass = candidate->getPeakMass(peak_index) - mass_dif / charge; if(mass > 0) { candidate_peaks.push_back(Peak(mass, candidate->getPeakIntensity(peak_index), shifted_annotation, peak_index)); } } // peaks without a known charge are shifted with a mass difference corresponding to all charges up to the precursor charge else { for(unsigned int charge = 1; charge < candidate->getPrecursorCharge(); charge++) { double mass = candidate->getPeakMass(peak_index) - mass_dif / charge; if(mass > 0) { candidate_peaks.push_back(Peak(mass, candidate->getPeakIntensity(peak_index), shifted, peak_index)); } } } } std::sort(candidate_peaks.begin(), candidate_peaks.end(), [](auto &peak1, auto &peak2) { return peak1.getMass() < peak2.getMass(); }); } // find the matching peaks between the query spectrum and the candidate spectrum std::vector<std::tuple<float, unsigned int, unsigned int>> peak_matches; unsigned int candidate_peak_index = 0; for(unsigned int query_peak_index = 0; query_peak_index < query->getNumPeaks(); query_peak_index++) { float query_peak_mass = query->getPeakMass(query_peak_index); float query_peak_intensity = query->getPeakIntensity(query_peak_index); // advance while there is an excessive mass difference while(candidate_peak_index < candidate_peaks.size() - 1 && query_peak_mass - fragment_mz_tolerance > candidate_peaks[candidate_peak_index].getMass()) { candidate_peak_index++; } // match the peaks within the fragment mass window if possible for(unsigned int index = 0; candidate_peak_index + index < candidate_peaks.size() && fabs(query_peak_mass - candidate_peaks[candidate_peak_index + index].getMass()) <= fragment_mz_tolerance; index++) { // slightly penalize matching peaks without an annotation double match_multiplier; switch(candidate_peaks[candidate_peak_index + index].getPeakStatus()) { case unshifted: match_multiplier = 1.0; break; case shifted_annotation: match_multiplier = 1.0; break; case shifted: match_multiplier = 2.0 / 3.0; break; default: match_multiplier = 0.0; break; } if(match_multiplier > 0.0) { peak_matches.push_back(std::make_tuple(match_multiplier * query_peak_intensity * candidate_peaks[candidate_peak_index + index].getIntensity(), query_peak_index, candidate_peaks[candidate_peak_index + index].getIndex())); } } } candidate_peaks.clear(); // use the most prominent peak matches to compute the score (sort in descending order) std::sort(peak_matches.begin(), peak_matches.end(), [](auto &peak_match1, auto &peak_match2) { return std::get<0>(peak_match1) > std::get<0>(peak_match2); }); SpectrumSpectrumMatch *this_match = new SpectrumSpectrumMatch(candidate_index); std::vector<bool> query_peaks_used(query->getNumPeaks(), false); std::vector<bool> candidate_peaks_used(candidate->getNumPeaks(), false); for(unsigned int peak_match_index = 0; peak_match_index < peak_matches.size(); peak_match_index++) { std::tuple<double, unsigned int, unsigned int> peak_match = peak_matches[peak_match_index]; unsigned int query_peak_index = std::get<1>(peak_match); unsigned int candidate_peak_index = std::get<2>(peak_match); if(query_peaks_used[query_peak_index] == false && candidate_peaks_used[candidate_peak_index] == false) { this_match->setScore(this_match->getScore() + std::get<0>(peak_match)); // save the matched peaks this_match->addPeakMatch(query_peak_index, candidate_peak_index); // make sure these peaks are not used anymore query_peaks_used[query_peak_index] = true; candidate_peaks_used[candidate_peak_index] = true; } } query_peaks_used.clear(); candidate_peaks_used.clear(); peak_matches.clear(); // retain the match with the highest score if(best_match == NULL || best_match->getScore() < this_match->getScore()) { if(best_match != NULL) { delete best_match; } best_match = this_match; } else { delete this_match; } } return best_match; }
Check whether the _absolute_ mass diff is bigger than the tolerance
Check whether the _absolute_ mass diff is bigger than the tolerance
C++
apache-2.0
bittremieux/ANN-SoLo,bittremieux/ANN-SoLo
31018d5e618449e834919bf66cafbf71705153e3
Source/Processing/Test/NoteRgbSourceTest.cpp
Source/Processing/Test/NoteRgbSourceTest.cpp
/** * @file * @copyright (c) Daniel Schenk, 2017 * This file is part of MLC2. * * @brief Unit test for NoteRgbSource. */ #include <gtest/gtest.h> #include <Drivers/Mock/MockMidiInput.h> #include "../NoteRgbSource.h" #include "../LinearRgbFunction.h" using ::testing::_; using ::testing::SaveArg; using ::testing::Return; class NoteRgbSourceTest : public ::testing::Test { public: static constexpr unsigned int c_StripSize = 10; NoteRgbSourceTest() : m_mockMidiInput() , m_strip(c_StripSize) { // Store callbacks so we can simulate events EXPECT_CALL(m_mockMidiInput, subscribeNoteOnOff(_)) .WillOnce(DoAll(SaveArg<0>(&m_noteOnOffCallback), Return(42))); EXPECT_CALL(m_mockMidiInput, subscribeControlChange(_)) .WillOnce(DoAll(SaveArg<0>(&m_controlChangeCallback), Return(69))); m_pNoteRgbSource = new NoteRgbSource(m_mockMidiInput); for(int i = 0; i < c_StripSize; ++i) { // Default: simple 1-to-1 mapping m_noteToLightMap[i] = i; } m_pNoteRgbSource->setNoteToLightMap(m_noteToLightMap); } void SetUp() { // It's not ideal to re-assert this in every test, but cleaner and safer as almost every test // will call these ASSERT_NE(nullptr, m_noteOnOffCallback); ASSERT_NE(nullptr, m_controlChangeCallback); } virtual ~NoteRgbSourceTest() { EXPECT_CALL(m_mockMidiInput, unsubscribeNoteOnOff(42)); EXPECT_CALL(m_mockMidiInput, unsubscribeControlChange(69)); delete m_pNoteRgbSource; } MockMidiInput m_mockMidiInput; NoteRgbSource* m_pNoteRgbSource; Processing::TRgbStrip m_strip; IMidiInput::TNoteOnOffFunction m_noteOnOffCallback; IMidiInput::TControlChangeFunction m_controlChangeCallback; Processing::TNoteToLightMap m_noteToLightMap; }; TEST_F(NoteRgbSourceTest, noNotesSounding) { // m_strip is initialized with zeroes auto darkStrip = m_strip; m_strip[0] = {4, 5, 6}; m_strip[6] = {7, 8, 9}; m_strip[c_StripSize-1] = {11, 12, 13}; m_pNoteRgbSource->execute(m_strip); // No notes sounding should cause darkness ASSERT_EQ(darkStrip, m_strip); } TEST_F(NoteRgbSourceTest, noteOn) { // (channel, number, velocity, on/off) m_noteOnOffCallback(0, 0, 1, true); m_noteOnOffCallback(0, 5, 6, true); m_pNoteRgbSource->execute(m_strip); // Default: white, factor 255, so any velocity >0 will cause full on auto reference = Processing::TRgbStrip(c_StripSize); reference[0] = {0xff, 0xff, 0xff}; reference[5] = {0xff, 0xff, 0xff}; EXPECT_EQ(reference, m_strip); } TEST_F(NoteRgbSourceTest, noteOff) { // (channel, number, velocity, on/off) m_noteOnOffCallback(0, 0, 1, true); m_noteOnOffCallback(0, 5, 6, true); m_noteOnOffCallback(0, 0, 8, false); m_pNoteRgbSource->execute(m_strip); // Default: white, factor 255, so any velocity >0 will cause full on auto reference = Processing::TRgbStrip(c_StripSize); reference[5] = {0xff, 0xff, 0xff}; EXPECT_EQ(reference, m_strip); } TEST_F(NoteRgbSourceTest, ignoreOtherChannel) { m_noteOnOffCallback(1, 0, 1, true); auto darkStrip = m_strip; m_pNoteRgbSource->execute(m_strip); EXPECT_EQ(darkStrip, m_strip); } TEST_F(NoteRgbSourceTest, ignorePedal) { auto darkStrip = m_strip; m_noteOnOffCallback(0, 0, 1, true); m_controlChangeCallback(0, IMidiInterface::DAMPER_PEDAL, 0xff); m_noteOnOffCallback(0, 0, 1, false); m_pNoteRgbSource->execute(m_strip); EXPECT_EQ(darkStrip, m_strip); } TEST_F(NoteRgbSourceTest, usePedal) { m_pNoteRgbSource->setUsingPedal(true); // Press a key // (channel, number, velocity, on/off) m_noteOnOffCallback(0, 0, 1, true); // Press pedal // (channel, number, value) m_controlChangeCallback(0, IMidiInterface::DAMPER_PEDAL, 0xff); // Press another key m_noteOnOffCallback(0, 2, 1, true); auto reference = Processing::TRgbStrip(c_StripSize); // Both notes are still sounding reference[0] = {0xff, 0xff, 0xff}; reference[2] = {0xff, 0xff, 0xff}; m_pNoteRgbSource->execute(m_strip); EXPECT_EQ(reference, m_strip); // Release keys m_noteOnOffCallback(0, 0, 1, false); m_noteOnOffCallback(0, 2, 1, false); // Both notes are still sounding m_pNoteRgbSource->execute(m_strip); EXPECT_EQ(reference, m_strip); // Release pedal m_controlChangeCallback(0, IMidiInterface::DAMPER_PEDAL, 0); // Notes are not sounding anymore reference[0] = {0, 0, 0}; reference[2] = {0, 0, 0}; m_pNoteRgbSource->execute(m_strip); EXPECT_EQ(reference, m_strip); } TEST_F(NoteRgbSourceTest, otherRgbFunction) { // LinearRgbFunction takes a factor&offset pair for each color m_pNoteRgbSource->setRgbFunction(new LinearRgbFunction({0, 0}, {10, 0}, {1, 10})); // (channel, number, velocity, on/off) m_noteOnOffCallback(0, 0, 1, true); m_noteOnOffCallback(0, 5, 6, true); m_pNoteRgbSource->execute(m_strip); auto reference = Processing::TRgbStrip(c_StripSize); reference[0] = {0, 10, 11}; reference[5] = {0, 60, 16}; EXPECT_EQ(reference, m_strip); }
/** * @file * @copyright (c) Daniel Schenk, 2017 * This file is part of MLC2. * * @brief Unit test for NoteRgbSource. */ #include <gtest/gtest.h> #include <Drivers/Mock/MockMidiInput.h> #include "../NoteRgbSource.h" #include "../LinearRgbFunction.h" using ::testing::_; using ::testing::SaveArg; using ::testing::Return; class NoteRgbSourceTest : public ::testing::Test { public: static constexpr unsigned int c_StripSize = 10; NoteRgbSourceTest() : m_mockMidiInput() , m_strip(c_StripSize) { // Store callbacks so we can simulate events EXPECT_CALL(m_mockMidiInput, subscribeNoteOnOff(_)) .WillOnce(DoAll(SaveArg<0>(&m_noteOnOffCallback), Return(42))); EXPECT_CALL(m_mockMidiInput, subscribeControlChange(_)) .WillOnce(DoAll(SaveArg<0>(&m_controlChangeCallback), Return(69))); m_pNoteRgbSource = new NoteRgbSource(m_mockMidiInput); for(int i = 0; i < c_StripSize; ++i) { // Default: simple 1-to-1 mapping m_noteToLightMap[i] = i; } m_pNoteRgbSource->setNoteToLightMap(m_noteToLightMap); } void SetUp() { // It's not ideal to re-assert this in every test, but cleaner and safer as almost every test // will call these ASSERT_NE(nullptr, m_noteOnOffCallback); ASSERT_NE(nullptr, m_controlChangeCallback); } virtual ~NoteRgbSourceTest() { EXPECT_CALL(m_mockMidiInput, unsubscribeNoteOnOff(42)); EXPECT_CALL(m_mockMidiInput, unsubscribeControlChange(69)); delete m_pNoteRgbSource; } MockMidiInput m_mockMidiInput; NoteRgbSource* m_pNoteRgbSource; Processing::TRgbStrip m_strip; IMidiInput::TNoteOnOffFunction m_noteOnOffCallback; IMidiInput::TControlChangeFunction m_controlChangeCallback; Processing::TNoteToLightMap m_noteToLightMap; }; TEST_F(NoteRgbSourceTest, noNotesSounding) { // m_strip is initialized with zeroes auto darkStrip = m_strip; m_strip[0] = {4, 5, 6}; m_strip[6] = {7, 8, 9}; m_strip[c_StripSize-1] = {11, 12, 13}; m_pNoteRgbSource->execute(m_strip); // No notes sounding should cause darkness ASSERT_EQ(darkStrip, m_strip); } TEST_F(NoteRgbSourceTest, noteOn) { // (channel, number, velocity, on/off) m_noteOnOffCallback(0, 0, 1, true); m_noteOnOffCallback(0, 5, 6, true); m_pNoteRgbSource->execute(m_strip); // Default: white, factor 255, so any velocity >0 will cause full on auto reference = Processing::TRgbStrip(c_StripSize); reference[0] = {0xff, 0xff, 0xff}; reference[5] = {0xff, 0xff, 0xff}; EXPECT_EQ(reference, m_strip); } TEST_F(NoteRgbSourceTest, noteOff) { // (channel, number, velocity, on/off) m_noteOnOffCallback(0, 0, 1, true); m_noteOnOffCallback(0, 5, 6, true); m_noteOnOffCallback(0, 0, 8, false); m_pNoteRgbSource->execute(m_strip); // Default: white, factor 255, so any velocity >0 will cause full on auto reference = Processing::TRgbStrip(c_StripSize); reference[5] = {0xff, 0xff, 0xff}; EXPECT_EQ(reference, m_strip); } TEST_F(NoteRgbSourceTest, ignoreOtherChannel) { m_noteOnOffCallback(1, 0, 1, true); auto darkStrip = m_strip; m_pNoteRgbSource->execute(m_strip); EXPECT_EQ(darkStrip, m_strip); } TEST_F(NoteRgbSourceTest, ignorePedal) { auto darkStrip = m_strip; m_noteOnOffCallback(0, 0, 1, true); m_controlChangeCallback(0, IMidiInterface::DAMPER_PEDAL, 0xff); m_noteOnOffCallback(0, 0, 1, false); m_pNoteRgbSource->execute(m_strip); EXPECT_EQ(darkStrip, m_strip); } TEST_F(NoteRgbSourceTest, usePedal) { m_pNoteRgbSource->setUsingPedal(true); // Press a key // (channel, number, velocity, on/off) m_noteOnOffCallback(0, 0, 1, true); // Press pedal // (channel, number, value) m_controlChangeCallback(0, IMidiInterface::DAMPER_PEDAL, 0xff); // Press another key m_noteOnOffCallback(0, 2, 1, true); auto reference = Processing::TRgbStrip(c_StripSize); // Both notes are still sounding reference[0] = {0xff, 0xff, 0xff}; reference[2] = {0xff, 0xff, 0xff}; m_pNoteRgbSource->execute(m_strip); EXPECT_EQ(reference, m_strip); // Release keys m_noteOnOffCallback(0, 0, 1, false); m_noteOnOffCallback(0, 2, 1, false); // Both notes are still sounding m_pNoteRgbSource->execute(m_strip); EXPECT_EQ(reference, m_strip); // Release pedal m_controlChangeCallback(0, IMidiInterface::DAMPER_PEDAL, 0); // Notes are not sounding anymore reference[0] = {0, 0, 0}; reference[2] = {0, 0, 0}; m_pNoteRgbSource->execute(m_strip); EXPECT_EQ(reference, m_strip); } TEST_F(NoteRgbSourceTest, otherRgbFunction) { // LinearRgbFunction takes a factor&offset pair for each color m_pNoteRgbSource->setRgbFunction(new LinearRgbFunction({0, 0}, {10, 0}, {1, 10})); // (channel, number, velocity, on/off) m_noteOnOffCallback(0, 0, 1, true); m_noteOnOffCallback(0, 5, 6, true); m_pNoteRgbSource->execute(m_strip); auto reference = Processing::TRgbStrip(c_StripSize); reference[0] = {0, 10, 11}; reference[5] = {0, 60, 16}; EXPECT_EQ(reference, m_strip); } TEST_F(NoteRgbSourceTest, otherNoteToLightMap) { Processing::TNoteToLightMap newMap; newMap[0] = 9; newMap[5] = 8; m_pNoteRgbSource->setNoteToLightMap(newMap); // (channel, number, velocity, on/off) m_noteOnOffCallback(0, 0, 1, true); m_noteOnOffCallback(0, 5, 6, true); m_pNoteRgbSource->execute(m_strip); // Default: white, factor 255, so any velocity >0 will cause full on auto reference = Processing::TRgbStrip(c_StripSize); reference[9] = {0xff, 0xff, 0xff}; reference[8] = {0xff, 0xff, 0xff}; EXPECT_EQ(reference, m_strip); }
Add another NoteRgbSource test
Add another NoteRgbSource test
C++
mit
danielschenk/mlc2,danielschenk/mlc2,danielschenk/mlc2
d1fa44be8f5f0510f2de29d461514566254a57c2
Source/Processing/Test/NoteRgbSourceTest.cpp
Source/Processing/Test/NoteRgbSourceTest.cpp
/** * @file * @copyright (c) Daniel Schenk, 2017 * This file is part of MLC2. * * @brief Unit test for NoteRgbSource. */ #include <gtest/gtest.h> #include <Drivers/Mock/MockMidiInput.h> #include "../NoteRgbSource.h" using ::testing::_; using ::testing::SaveArg; using ::testing::Return; class NoteRgbSourceTest : public ::testing::Test { public: NoteRgbSourceTest() : m_mockMidiInput() , m_strip(50) { // Store callbacks so we can simulate events EXPECT_CALL(m_mockMidiInput, subscribeNoteOnOff(_)) .WillOnce(DoAll(SaveArg<0>(&m_noteOnOffCallback), Return(42))); EXPECT_CALL(m_mockMidiInput, subscribeControlChange(_)) .WillOnce(DoAll(SaveArg<0>(&m_controlChangeCallback), Return(69))); m_pNoteRgbSource = new NoteRgbSource(m_mockMidiInput); for(int i = 0; i < m_strip.size(); ++i) { // Default: simple 1-to-1 mapping m_noteToLightMap[i] = i; } m_pNoteRgbSource->setNoteToLightMap(m_noteToLightMap); } void SetUp() { // It's not ideal to re-assert this in every test, but cleaner and safer as almost every test // will call these ASSERT_NE(nullptr, m_noteOnOffCallback); ASSERT_NE(nullptr, m_controlChangeCallback); } virtual ~NoteRgbSourceTest() { EXPECT_CALL(m_mockMidiInput, unsubscribeNoteOnOff(42)); EXPECT_CALL(m_mockMidiInput, unsubscribeControlChange(69)); delete m_pNoteRgbSource; } MockMidiInput m_mockMidiInput; NoteRgbSource* m_pNoteRgbSource; Processing::TRgbStrip m_strip; IMidiInput::TNoteOnOffFunction m_noteOnOffCallback; IMidiInput::TControlChangeFunction m_controlChangeCallback; Processing::TNoteToLightMap m_noteToLightMap; }; TEST_F(NoteRgbSourceTest, noEventsNoChange) { Processing::TNoteToLightMap noteToLightMap; for(int i = 0; i < m_strip.size(); ++i) { m_strip[i] = {12, 23, 34}; } auto reference = m_strip; m_pNoteRgbSource->execute(m_strip); ASSERT_EQ(reference, m_strip); }
/** * @file * @copyright (c) Daniel Schenk, 2017 * This file is part of MLC2. * * @brief Unit test for NoteRgbSource. */ #include <gtest/gtest.h> #include <Drivers/Mock/MockMidiInput.h> #include "../NoteRgbSource.h" using ::testing::_; using ::testing::SaveArg; using ::testing::Return; class NoteRgbSourceTest : public ::testing::Test { public: static constexpr unsigned int c_StripSize = 50; NoteRgbSourceTest() : m_mockMidiInput() , m_strip(c_StripSize) { // Store callbacks so we can simulate events EXPECT_CALL(m_mockMidiInput, subscribeNoteOnOff(_)) .WillOnce(DoAll(SaveArg<0>(&m_noteOnOffCallback), Return(42))); EXPECT_CALL(m_mockMidiInput, subscribeControlChange(_)) .WillOnce(DoAll(SaveArg<0>(&m_controlChangeCallback), Return(69))); m_pNoteRgbSource = new NoteRgbSource(m_mockMidiInput); for(int i = 0; i < c_StripSize; ++i) { // Default: simple 1-to-1 mapping m_noteToLightMap[i] = i; } m_pNoteRgbSource->setNoteToLightMap(m_noteToLightMap); } void SetUp() { // It's not ideal to re-assert this in every test, but cleaner and safer as almost every test // will call these ASSERT_NE(nullptr, m_noteOnOffCallback); ASSERT_NE(nullptr, m_controlChangeCallback); } virtual ~NoteRgbSourceTest() { EXPECT_CALL(m_mockMidiInput, unsubscribeNoteOnOff(42)); EXPECT_CALL(m_mockMidiInput, unsubscribeControlChange(69)); delete m_pNoteRgbSource; } MockMidiInput m_mockMidiInput; NoteRgbSource* m_pNoteRgbSource; Processing::TRgbStrip m_strip; IMidiInput::TNoteOnOffFunction m_noteOnOffCallback; IMidiInput::TControlChangeFunction m_controlChangeCallback; Processing::TNoteToLightMap m_noteToLightMap; }; TEST_F(NoteRgbSourceTest, noNotesSounding) { Processing::TNoteToLightMap noteToLightMap; // m_strip is initialized with zeroes auto darkStrip = m_strip; m_strip[0] = {4, 5, 6}; m_strip[6] = {7, 8, 9}; m_strip[c_StripSize-1] = {11, 12, 13}; m_pNoteRgbSource->execute(m_strip); // No notes sounding should cause darkness ASSERT_EQ(darkStrip, m_strip); }
Fix unit test
Fix unit test
C++
mit
danielschenk/mlc2,danielschenk/mlc2,danielschenk/mlc2
3e58119fbfceec620baf53c35aae8ab52417ee69
Source/core/dom/MainThreadTaskRunnerTest.cpp
Source/core/dom/MainThreadTaskRunnerTest.cpp
/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * Copyright (C) 2013 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: * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" #include "core/dom/MainThreadTaskRunner.h" #include "core/dom/ExecutionContext.h" #include "core/dom/ExecutionContextTask.h" #include "core/events/EventQueue.h" #include "core/testing/UnitTestHelpers.h" #include <gtest/gtest.h> using namespace WebCore; namespace { class NullEventQueue : public EventQueue { public: NullEventQueue() { } virtual ~NullEventQueue() { } virtual bool enqueueEvent(PassRefPtr<Event>) OVERRIDE { return true; } virtual bool cancelEvent(Event*) OVERRIDE { return true; } virtual void close() OVERRIDE { } }; class NullExecutionContext : public ExecutionContext, public RefCounted<NullExecutionContext> { public: using RefCounted<NullExecutionContext>::ref; using RefCounted<NullExecutionContext>::deref; virtual void refExecutionContext() OVERRIDE { ref(); } virtual void derefExecutionContext() OVERRIDE { deref(); } virtual EventQueue* eventQueue() const OVERRIDE { return m_queue.get(); } virtual bool tasksNeedSuspension() { return m_tasksNeedSuspension; } void setTasksNeedSuspention(bool flag) { m_tasksNeedSuspension = flag; } NullExecutionContext(); private: bool m_tasksNeedSuspension; OwnPtr<EventQueue> m_queue; }; NullExecutionContext::NullExecutionContext() : m_tasksNeedSuspension(false) , m_queue(adoptPtr(new NullEventQueue())) { } class MarkingBooleanTask FINAL : public ExecutionContextTask { public: static PassOwnPtr<MarkingBooleanTask> create(bool* toBeMarked) { return adoptPtr(new MarkingBooleanTask(toBeMarked)); } virtual ~MarkingBooleanTask() { } private: MarkingBooleanTask(bool* toBeMarked) : m_toBeMarked(toBeMarked) { } virtual void performTask(ExecutionContext* context) OVERRIDE { *m_toBeMarked = true; } bool* m_toBeMarked; }; TEST(MainThreadTaskRunnerTest, PostTask) { RefPtr<NullExecutionContext> context = adoptRef(new NullExecutionContext()); OwnPtr<MainThreadTaskRunner> runner = MainThreadTaskRunner::create(context.get()); bool isMarked = false; runner->postTask(MarkingBooleanTask::create(&isMarked)); EXPECT_FALSE(isMarked); WebCore::testing::runPendingTasks(); EXPECT_TRUE(isMarked); } TEST(MainThreadTaskRunnerTest, SuspendTask) { RefPtr<NullExecutionContext> context = adoptRef(new NullExecutionContext()); OwnPtr<MainThreadTaskRunner> runner = MainThreadTaskRunner::create(context.get()); bool isMarked = false; context->setTasksNeedSuspention(true); runner->postTask(MarkingBooleanTask::create(&isMarked)); runner->suspend(); WebCore::testing::runPendingTasks(); EXPECT_FALSE(isMarked); context->setTasksNeedSuspention(false); runner->resume(); WebCore::testing::runPendingTasks(); EXPECT_TRUE(isMarked); } TEST(MainThreadTaskRunnerTest, RemoveRunner) { RefPtr<NullExecutionContext> context = adoptRef(new NullExecutionContext()); OwnPtr<MainThreadTaskRunner> runner = MainThreadTaskRunner::create(context.get()); bool isMarked = false; context->setTasksNeedSuspention(true); runner->postTask(MarkingBooleanTask::create(&isMarked)); runner.clear(); WebCore::testing::runPendingTasks(); EXPECT_FALSE(isMarked); } }
/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * Copyright (C) 2013 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: * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" #include "core/dom/MainThreadTaskRunner.h" #include "core/dom/ExecutionContext.h" #include "core/dom/ExecutionContextTask.h" #include "core/events/EventQueue.h" #include "core/testing/UnitTestHelpers.h" #include <gtest/gtest.h> using namespace WebCore; namespace { class NullEventQueue : public EventQueue { public: NullEventQueue() { } virtual ~NullEventQueue() { } virtual bool enqueueEvent(PassRefPtr<Event>) OVERRIDE { return true; } virtual bool cancelEvent(Event*) OVERRIDE { return true; } virtual void close() OVERRIDE { } }; class NullExecutionContext : public ExecutionContext, public RefCounted<NullExecutionContext> { public: using RefCounted<NullExecutionContext>::ref; using RefCounted<NullExecutionContext>::deref; virtual EventQueue* eventQueue() const OVERRIDE { return m_queue.get(); } virtual bool tasksNeedSuspension() { return m_tasksNeedSuspension; } void setTasksNeedSuspention(bool flag) { m_tasksNeedSuspension = flag; } NullExecutionContext(); private: bool m_tasksNeedSuspension; OwnPtr<EventQueue> m_queue; }; NullExecutionContext::NullExecutionContext() : m_tasksNeedSuspension(false) , m_queue(adoptPtr(new NullEventQueue())) { } class MarkingBooleanTask FINAL : public ExecutionContextTask { public: static PassOwnPtr<MarkingBooleanTask> create(bool* toBeMarked) { return adoptPtr(new MarkingBooleanTask(toBeMarked)); } virtual ~MarkingBooleanTask() { } private: MarkingBooleanTask(bool* toBeMarked) : m_toBeMarked(toBeMarked) { } virtual void performTask(ExecutionContext* context) OVERRIDE { *m_toBeMarked = true; } bool* m_toBeMarked; }; TEST(MainThreadTaskRunnerTest, PostTask) { RefPtr<NullExecutionContext> context = adoptRef(new NullExecutionContext()); OwnPtr<MainThreadTaskRunner> runner = MainThreadTaskRunner::create(context.get()); bool isMarked = false; runner->postTask(MarkingBooleanTask::create(&isMarked)); EXPECT_FALSE(isMarked); WebCore::testing::runPendingTasks(); EXPECT_TRUE(isMarked); } TEST(MainThreadTaskRunnerTest, SuspendTask) { RefPtr<NullExecutionContext> context = adoptRef(new NullExecutionContext()); OwnPtr<MainThreadTaskRunner> runner = MainThreadTaskRunner::create(context.get()); bool isMarked = false; context->setTasksNeedSuspention(true); runner->postTask(MarkingBooleanTask::create(&isMarked)); runner->suspend(); WebCore::testing::runPendingTasks(); EXPECT_FALSE(isMarked); context->setTasksNeedSuspention(false); runner->resume(); WebCore::testing::runPendingTasks(); EXPECT_TRUE(isMarked); } TEST(MainThreadTaskRunnerTest, RemoveRunner) { RefPtr<NullExecutionContext> context = adoptRef(new NullExecutionContext()); OwnPtr<MainThreadTaskRunner> runner = MainThreadTaskRunner::create(context.get()); bool isMarked = false; context->setTasksNeedSuspention(true); runner->postTask(MarkingBooleanTask::create(&isMarked)); runner.clear(); WebCore::testing::runPendingTasks(); EXPECT_FALSE(isMarked); } }
Remove wrong overload.
Remove wrong overload. This is a build fix against r161710. TBR=abarth BUG=305497 Review URL: https://codereview.chromium.org/68593002 git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@161714 bbb929c8-8fbe-4397-9dbb-9b2b20218538
C++
bsd-3-clause
primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs
0eeac1c10fdd0adab6be3001d0929fe2d89d0364
VisualizationBase/src/items/TextRenderer.cpp
VisualizationBase/src/items/TextRenderer.cpp
/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ #include "TextRenderer.h" #include "ItemWithNode.h" #include "../Scene.h" #include "../VisualizationException.h" #include "../shapes/Shape.h" #include "../cursor/TextCursor.h" namespace Visualization { DEFINE_ITEM_COMMON(TextRenderer, "item") TextRenderer::TextRenderer(Item* parent, const StyleType *style, const QString& text) : Super{parent, style}, staticText_{text}, editable_(true) { staticText_.setPerformanceHint(QStaticText::AggressiveCaching); setTextFormat(style->htmlFormat() ? Qt::RichText : Qt::PlainText); } bool TextRenderer::setText(const QString& newText) { staticText_.setText( newText ); this->setUpdateNeeded(StandardUpdate); return true; } QString TextRenderer::selectedText() { if (hasSceneCursor() && !isHtml()) { TextCursor* cur = correspondingSceneCursor<TextCursor>(); int xstart = cur->selectionFirstIndex(); int xend = cur->selectionLastIndex(); return staticText_.text().mid(xstart, xend - xstart); } else return QString{}; } void TextRenderer::determineChildren() { } inline QSize TextRenderer::staticTextSize(QFontMetrics& qfm) { if (staticText_.text().isEmpty()) return QSize{MIN_TEXT_WIDTH, qfm.height()}; else return staticText_.size().toSize(); } inline QRectF TextRenderer::nonStaticTextBound() { Q_ASSERT(!isHtml()); QRectF bound; QFontMetrics qfm{style()->font()}; if (staticText_.text().isEmpty()) bound.setRect(0, 0, MIN_TEXT_WIDTH, qfm.height()); else { bound = qfm.boundingRect(staticText_.text()); if (bound.width() < qfm.width(staticText_.text())) bound.setWidth(qfm.width(staticText_.text())); if (bound.height() < qfm.height()) bound.setHeight(qfm.height()); } return bound; } void TextRenderer::updateGeometry(int, int) { staticText_.setText(currentText()); QFontMetrics qfm{style()->font()}; QSize textSize; if (drawApproximately_ == Unknown) drawApproximately_ = scene()->approximateUpdate() ? Approximate : Exact; if (drawApproximately_ == Approximate) { int approxWidth = currentText().length() * qfm.averageCharWidth(); textSize = QSize{approxWidth, qfm.height()}; } else { // It's important to call this in order to give the static text the correct font. This is used when computing bound. staticText_.prepare(QTransform{}, style()->font()); textSize = this->staticTextSize(qfm); } if (this->hasShape()) { this->getShape()->setInnerSize(textSize.width(), textSize.height()); textXOffset_ = this->getShape()->contentLeft(); textYOffset_ = this->getShape()->contentTop(); } else { textXOffset_ = 0; textYOffset_ = 0; this->setSize(textSize); } // Correct underline, otherwise it is drawn in the middle of two pixels and appears fat and transparent. // This was updated when drawing the line manually (in order to workaround qt no translating the line properly when // scaling). The old condition is below // if (style()->font().underline() && (qfm.lineWidth() % 2 == 0)) if (style()->underline() && (qfm.lineWidth() % 2 == 1)) { textXOffset_ += 0.5; textYOffset_ += 0.5; } if ( hasSceneCursor() && !isHtml()) correspondingSceneCursor<TextCursor>()->update(qfm); } void TextRenderer::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { if (drawApproximately_ == Approximate) { setUpdateNeeded(StandardUpdate); drawApproximately_ = Exact; return; } if (isCategoryHiddenDuringPaint()) return; Item::paint(painter, option, widget); TextCursor* selectionCursor = (hasSceneCursor() && !isHtml()) ? correspondingSceneCursor<TextCursor>() : nullptr; if (selectionCursor && !selectionCursor->hasSelection()) selectionCursor = nullptr; if ( !selectionCursor ) { // In this common case use static text. qreal size = painter->worldTransform().m11() * style()->font().pixelSize(); if (size < 0.5) return; if (size < 3.0) { // Draw just a filler auto c = style()->pen().color(); c.setAlpha(64); painter->fillRect(QRectF{textXOffset_, textYOffset_ + heightInLocal()/4.0, staticText_.size().width(), staticText_.size().height()/2.0}, c); } else { // Draw actual text painter->setPen(style()->pen()); painter->setFont(style()->font()); painter->drawStaticText(QPointF{textXOffset_, textYOffset_}, staticText_); if (style()->underline()) painter->drawLine(QPointF{textXOffset_, textYOffset_ + staticText_.size().height()}, QPointF{textXOffset_ + staticText_.size().width(), textYOffset_ + staticText_.size().height()}); } } else { // In the selected case do not use static text. // Some text is selected, draw it differently than non-selected text. int start = selectionCursor->selectionFirstIndex(); int end = selectionCursor->selectionLastIndex(); QPointF offset{textXOffset_, textYOffset_}; // Might be a bit slow but that's OK, since we have very little selected text // Here topLeft is the absolute corner of the text if it is drawn at 0, 0. offset -= nonStaticTextBound().topLeft(); // Draw selection background painter->setPen(Qt::NoPen); painter->setBrush(style()->selectionBackground()); painter->drawRect(textXOffset_ + selectionCursor->xBegin(), 0, selectionCursor->xEnd() - selectionCursor->xBegin(), this->heightInLocal()); painter->setBrush(Qt::NoBrush); // Draw selected text painter->setPen(style()->selectionPen()); painter->setFont(style()->selectionFont()); painter->drawText(QPointF{offset.x() + selectionCursor->xBegin(), offset.y()}, staticText_.text().mid(start, end - start)); auto underlineY = textYOffset_ + staticText_.size().height(); if (style()->underline()) painter->drawLine(QPointF{offset.x() + selectionCursor->xBegin(), underlineY}, QPointF{offset.x() + selectionCursor->xEnd(), underlineY}); // Draw non-selected text painter->setPen(style()->pen()); painter->setFont(style()->font()); painter->drawText(offset, staticText_.text().left(start)); painter->drawText(QPointF{offset.x() + selectionCursor->xEnd(), offset.y()}, staticText_.text().mid(end)); if (style()->underline()) { painter->drawLine(QPointF{textXOffset_, underlineY}, QPointF{offset.x() + selectionCursor->xBegin(), underlineY}); painter->drawLine(QPointF{offset.x() + selectionCursor->xEnd(), underlineY}, QPointF{textXOffset_ + staticText_.size().width(), underlineY}); } } } bool TextRenderer::moveCursor(CursorMoveDirection dir, QRect reference, CursorMoveOptions options) { if ( isHtml() ) return Super::moveCursor(dir, reference, options); QPoint referenceCenter = reference.center(); if ( dir == MoveUpOf || dir == MoveDownOf || dir == MoveLeftOf || dir == MoveRightOf ) { PositionConstraints pc = satisfiedPositionConstraints(referenceCenter); if ( (dir == MoveUpOf && (pc & Above)) || (dir == MoveDownOf && (pc & Below)) || (dir == MoveLeftOf && (pc & LeftOf)) || (dir == MoveRightOf && (pc & RightOf)) ) { TextCursor* tc = new TextCursor{this}; tc->setSelectedByDrag(referenceCenter.x(), referenceCenter.x()); scene()->setMainCursor(tc); return true; } else return false; } else if (dir == MoveOnPosition || dir == MoveDefault || dir == MoveOnTop || dir == MoveOnLeft || dir == MoveOnBottom || dir == MoveOnRight || dir == MoveOnTopLeft || dir == MoveOnBottomRight || dir == MoveOnCenter) { setFocus(); TextCursor* tc = new TextCursor{this}; auto xEnd = widthInLocal() - 1; auto xMid = widthInLocal()/2; switch (dir) { case MoveDefault: tc->setCaretPosition(0); break; case MoveOnPosition: tc->setSelectedByDrag(referenceCenter.x(), referenceCenter.x()); break; case MoveOnTop: tc->setSelectedByDrag(xMid, xMid); break; case MoveOnLeft: tc->setSelectedByDrag(0, 0); break; case MoveOnBottom: tc->setSelectedByDrag(xMid, xMid); break; case MoveOnRight: tc->setSelectedByDrag(xEnd, xEnd); break; case MoveOnTopLeft: tc->setSelectedByDrag(0, 0); break; case MoveOnBottomRight: tc->setSelectedByDrag(xEnd, xEnd); break; case MoveOnCenter: tc->setSelectedByDrag(xMid, xMid); break; default: Q_ASSERT(false); break; } scene()->setMainCursor(tc); return true; } else if (dir == MoveLeft) { int position = correspondingSceneCursor<Visualization::TextCursor>()->caretPosition(); if ( staticText_.text().isEmpty() || position <= 0) return false; else correspondingSceneCursor<Visualization::TextCursor>()->setCaretPosition(position - 1); return true; } else if (dir == MoveRight) { int position = correspondingSceneCursor<Visualization::TextCursor>()->caretPosition(); if ( staticText_.text().isEmpty() || position >= staticText_.text().size()) return false; else correspondingSceneCursor<Visualization::TextCursor>()->setCaretPosition(position + 1); return true; } return false; } void TextRenderer::setTextFormat(Qt::TextFormat textFormat) { Q_ASSERT(textFormat == Qt::PlainText || textFormat == Qt::RichText); if (textFormat != staticText_.textFormat()) { staticText_.setTextFormat(textFormat); auto to = staticText_.textOption(); to.setWrapMode(QTextOption::NoWrap); staticText_.setTextOption(to); this->setUpdateNeeded(StandardUpdate); } } bool TextRenderer::ignoresCopyAndPaste() { return suppressDefaultCopyPasteHandler_; } }
/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ #include "TextRenderer.h" #include "ItemWithNode.h" #include "../Scene.h" #include "../VisualizationException.h" #include "../shapes/Shape.h" #include "../cursor/TextCursor.h" namespace Visualization { DEFINE_ITEM_COMMON(TextRenderer, "item") TextRenderer::TextRenderer(Item* parent, const StyleType *style, const QString& text) : Super{parent, style}, staticText_{text}, editable_(true) { staticText_.setPerformanceHint(QStaticText::AggressiveCaching); setTextFormat(style->htmlFormat() ? Qt::RichText : Qt::PlainText); } bool TextRenderer::setText(const QString& newText) { if ( newText != staticText_.text()) { staticText_.setText( newText ); this->setUpdateNeeded(StandardUpdate); } return true; } QString TextRenderer::selectedText() { if (hasSceneCursor() && !isHtml()) { TextCursor* cur = correspondingSceneCursor<TextCursor>(); int xstart = cur->selectionFirstIndex(); int xend = cur->selectionLastIndex(); return staticText_.text().mid(xstart, xend - xstart); } else return QString{}; } void TextRenderer::determineChildren() { } inline QSize TextRenderer::staticTextSize(QFontMetrics& qfm) { if (staticText_.text().isEmpty()) return QSize{MIN_TEXT_WIDTH, qfm.height()}; else return staticText_.size().toSize(); } inline QRectF TextRenderer::nonStaticTextBound() { Q_ASSERT(!isHtml()); QRectF bound; QFontMetrics qfm{style()->font()}; if (staticText_.text().isEmpty()) bound.setRect(0, 0, MIN_TEXT_WIDTH, qfm.height()); else { bound = qfm.boundingRect(staticText_.text()); if (bound.width() < qfm.width(staticText_.text())) bound.setWidth(qfm.width(staticText_.text())); if (bound.height() < qfm.height()) bound.setHeight(qfm.height()); } return bound; } void TextRenderer::updateGeometry(int, int) { staticText_.setText(currentText()); QFontMetrics qfm{style()->font()}; QSize textSize; if (drawApproximately_ == Unknown) drawApproximately_ = scene()->approximateUpdate() ? Approximate : Exact; if (drawApproximately_ == Approximate) { int approxWidth = currentText().length() * qfm.averageCharWidth(); textSize = QSize{approxWidth, qfm.height()}; } else { // It's important to call this in order to give the static text the correct font. This is used when computing bound. staticText_.prepare(QTransform{}, style()->font()); textSize = this->staticTextSize(qfm); } if (this->hasShape()) { this->getShape()->setInnerSize(textSize.width(), textSize.height()); textXOffset_ = this->getShape()->contentLeft(); textYOffset_ = this->getShape()->contentTop(); } else { textXOffset_ = 0; textYOffset_ = 0; this->setSize(textSize); } // Correct underline, otherwise it is drawn in the middle of two pixels and appears fat and transparent. // This was updated when drawing the line manually (in order to workaround qt no translating the line properly when // scaling). The old condition is below // if (style()->font().underline() && (qfm.lineWidth() % 2 == 0)) if (style()->underline() && (qfm.lineWidth() % 2 == 1)) { textXOffset_ += 0.5; textYOffset_ += 0.5; } if ( hasSceneCursor() && !isHtml()) correspondingSceneCursor<TextCursor>()->update(qfm); } void TextRenderer::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { if (drawApproximately_ == Approximate) { setUpdateNeeded(StandardUpdate); drawApproximately_ = Exact; return; } if (isCategoryHiddenDuringPaint()) return; Item::paint(painter, option, widget); TextCursor* selectionCursor = (hasSceneCursor() && !isHtml()) ? correspondingSceneCursor<TextCursor>() : nullptr; if (selectionCursor && !selectionCursor->hasSelection()) selectionCursor = nullptr; if ( !selectionCursor ) { // In this common case use static text. qreal size = painter->worldTransform().m11() * style()->font().pixelSize(); if (size < 0.5) return; if (size < 3.0) { // Draw just a filler auto c = style()->pen().color(); c.setAlpha(64); painter->fillRect(QRectF{textXOffset_, textYOffset_ + heightInLocal()/4.0, staticText_.size().width(), staticText_.size().height()/2.0}, c); } else { // Draw actual text painter->setPen(style()->pen()); painter->setFont(style()->font()); painter->drawStaticText(QPointF{textXOffset_, textYOffset_}, staticText_); if (style()->underline()) painter->drawLine(QPointF{textXOffset_, textYOffset_ + staticText_.size().height()}, QPointF{textXOffset_ + staticText_.size().width(), textYOffset_ + staticText_.size().height()}); } } else { // In the selected case do not use static text. // Some text is selected, draw it differently than non-selected text. int start = selectionCursor->selectionFirstIndex(); int end = selectionCursor->selectionLastIndex(); QPointF offset{textXOffset_, textYOffset_}; // Might be a bit slow but that's OK, since we have very little selected text // Here topLeft is the absolute corner of the text if it is drawn at 0, 0. offset -= nonStaticTextBound().topLeft(); // Draw selection background painter->setPen(Qt::NoPen); painter->setBrush(style()->selectionBackground()); painter->drawRect(textXOffset_ + selectionCursor->xBegin(), 0, selectionCursor->xEnd() - selectionCursor->xBegin(), this->heightInLocal()); painter->setBrush(Qt::NoBrush); // Draw selected text painter->setPen(style()->selectionPen()); painter->setFont(style()->selectionFont()); painter->drawText(QPointF{offset.x() + selectionCursor->xBegin(), offset.y()}, staticText_.text().mid(start, end - start)); auto underlineY = textYOffset_ + staticText_.size().height(); if (style()->underline()) painter->drawLine(QPointF{offset.x() + selectionCursor->xBegin(), underlineY}, QPointF{offset.x() + selectionCursor->xEnd(), underlineY}); // Draw non-selected text painter->setPen(style()->pen()); painter->setFont(style()->font()); painter->drawText(offset, staticText_.text().left(start)); painter->drawText(QPointF{offset.x() + selectionCursor->xEnd(), offset.y()}, staticText_.text().mid(end)); if (style()->underline()) { painter->drawLine(QPointF{textXOffset_, underlineY}, QPointF{offset.x() + selectionCursor->xBegin(), underlineY}); painter->drawLine(QPointF{offset.x() + selectionCursor->xEnd(), underlineY}, QPointF{textXOffset_ + staticText_.size().width(), underlineY}); } } } bool TextRenderer::moveCursor(CursorMoveDirection dir, QRect reference, CursorMoveOptions options) { if ( isHtml() ) return Super::moveCursor(dir, reference, options); QPoint referenceCenter = reference.center(); if ( dir == MoveUpOf || dir == MoveDownOf || dir == MoveLeftOf || dir == MoveRightOf ) { PositionConstraints pc = satisfiedPositionConstraints(referenceCenter); if ( (dir == MoveUpOf && (pc & Above)) || (dir == MoveDownOf && (pc & Below)) || (dir == MoveLeftOf && (pc & LeftOf)) || (dir == MoveRightOf && (pc & RightOf)) ) { TextCursor* tc = new TextCursor{this}; tc->setSelectedByDrag(referenceCenter.x(), referenceCenter.x()); scene()->setMainCursor(tc); return true; } else return false; } else if (dir == MoveOnPosition || dir == MoveDefault || dir == MoveOnTop || dir == MoveOnLeft || dir == MoveOnBottom || dir == MoveOnRight || dir == MoveOnTopLeft || dir == MoveOnBottomRight || dir == MoveOnCenter) { setFocus(); TextCursor* tc = new TextCursor{this}; auto xEnd = widthInLocal() - 1; auto xMid = widthInLocal()/2; switch (dir) { case MoveDefault: tc->setCaretPosition(0); break; case MoveOnPosition: tc->setSelectedByDrag(referenceCenter.x(), referenceCenter.x()); break; case MoveOnTop: tc->setSelectedByDrag(xMid, xMid); break; case MoveOnLeft: tc->setSelectedByDrag(0, 0); break; case MoveOnBottom: tc->setSelectedByDrag(xMid, xMid); break; case MoveOnRight: tc->setSelectedByDrag(xEnd, xEnd); break; case MoveOnTopLeft: tc->setSelectedByDrag(0, 0); break; case MoveOnBottomRight: tc->setSelectedByDrag(xEnd, xEnd); break; case MoveOnCenter: tc->setSelectedByDrag(xMid, xMid); break; default: Q_ASSERT(false); break; } scene()->setMainCursor(tc); return true; } else if (dir == MoveLeft) { int position = correspondingSceneCursor<Visualization::TextCursor>()->caretPosition(); if ( staticText_.text().isEmpty() || position <= 0) return false; else correspondingSceneCursor<Visualization::TextCursor>()->setCaretPosition(position - 1); return true; } else if (dir == MoveRight) { int position = correspondingSceneCursor<Visualization::TextCursor>()->caretPosition(); if ( staticText_.text().isEmpty() || position >= staticText_.text().size()) return false; else correspondingSceneCursor<Visualization::TextCursor>()->setCaretPosition(position + 1); return true; } return false; } void TextRenderer::setTextFormat(Qt::TextFormat textFormat) { Q_ASSERT(textFormat == Qt::PlainText || textFormat == Qt::RichText); if (textFormat != staticText_.textFormat()) { staticText_.setTextFormat(textFormat); auto to = staticText_.textOption(); to.setWrapMode(QTextOption::NoWrap); staticText_.setTextOption(to); this->setUpdateNeeded(StandardUpdate); } } bool TextRenderer::ignoresCopyAndPaste() { return suppressDefaultCopyPasteHandler_; } }
Optimize TextRenderer to only set the new text when it is different.
Optimize TextRenderer to only set the new text when it is different.
C++
bsd-3-clause
dimitar-asenov/Envision,Vaishal-shah/Envision,mgalbier/Envision,Vaishal-shah/Envision,dimitar-asenov/Envision,mgalbier/Envision,dimitar-asenov/Envision,lukedirtwalker/Envision,lukedirtwalker/Envision,Vaishal-shah/Envision,mgalbier/Envision,lukedirtwalker/Envision,Vaishal-shah/Envision,Vaishal-shah/Envision,mgalbier/Envision,dimitar-asenov/Envision,mgalbier/Envision,dimitar-asenov/Envision,Vaishal-shah/Envision,mgalbier/Envision,lukedirtwalker/Envision,lukedirtwalker/Envision,dimitar-asenov/Envision,lukedirtwalker/Envision
dd5f169b32278fd06fc35b5fc09600b22c91650b
chrome/browser/ui/panels/detached_panel_browsertest.cc
chrome/browser/ui/panels/detached_panel_browsertest.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop.h" #include "chrome/browser/ui/panels/base_panel_browser_test.h" #include "chrome/browser/ui/panels/detached_panel_collection.h" #include "chrome/browser/ui/panels/native_panel.h" #include "chrome/browser/ui/panels/panel.h" #include "chrome/browser/ui/panels/panel_manager.h" class DetachedPanelBrowserTest : public BasePanelBrowserTest { }; // http://crbug.com/143247 #if !defined(OS_WIN) #define MAYBE_CheckDetachedPanelProperties DISABLED_CheckDetachedPanelProperties #else #define MAYBE_CheckDetachedPanelProperties CheckDetachedPanelProperties #endif IN_PROC_BROWSER_TEST_F(DetachedPanelBrowserTest, MAYBE_CheckDetachedPanelProperties) { PanelManager* panel_manager = PanelManager::GetInstance(); DetachedPanelCollection* detached_collection = panel_manager->detached_collection(); // Create an initially detached panel (as opposed to other tests which create // a docked panel, then detaches it). gfx::Rect bounds(300, 200, 250, 200); CreatePanelParams params("1", bounds, SHOW_AS_ACTIVE); params.create_mode = PanelManager::CREATE_AS_DETACHED; Panel* panel = CreatePanelWithParams(params); scoped_ptr<NativePanelTesting> panel_testing( CreateNativePanelTesting(panel)); EXPECT_EQ(1, panel_manager->num_panels()); EXPECT_TRUE(detached_collection->HasPanel(panel)); EXPECT_EQ(bounds.x(), panel->GetBounds().x()); // Ignore checking y position since the detached panel will be placed near // the top if the stacking mode is enabled. if (!PanelManager::IsPanelStackingEnabled()) EXPECT_EQ(bounds.y(), panel->GetBounds().y()); EXPECT_EQ(bounds.width(), panel->GetBounds().width()); EXPECT_EQ(bounds.height(), panel->GetBounds().height()); EXPECT_FALSE(panel->IsAlwaysOnTop()); EXPECT_TRUE(panel_testing->IsButtonVisible(panel::CLOSE_BUTTON)); EXPECT_TRUE(panel_testing->IsButtonVisible(panel::MINIMIZE_BUTTON)); EXPECT_FALSE(panel_testing->IsButtonVisible(panel::RESTORE_BUTTON)); EXPECT_EQ(panel::RESIZABLE_ALL, panel->CanResizeByMouse()); EXPECT_EQ(panel::ALL_ROUNDED, panel_testing->GetWindowCornerStyle()); Panel::AttentionMode expected_attention_mode = static_cast<Panel::AttentionMode>(Panel::USE_PANEL_ATTENTION | Panel::USE_SYSTEM_ATTENTION); EXPECT_EQ(expected_attention_mode, panel->attention_mode()); panel_manager->CloseAll(); } // http://crbug.com/143247 #if !defined(OS_WIN) #define MAYBE_DrawAttentionOnActive DISABLED_DrawAttentionOnActive #else #define MAYBE_DrawAttentionOnActive DrawAttentionOnActive #endif IN_PROC_BROWSER_TEST_F(DetachedPanelBrowserTest, MAYBE_DrawAttentionOnActive) { // Create a detached panel that is initially active. Panel* panel = CreateDetachedPanel("1", gfx::Rect(300, 200, 250, 200)); scoped_ptr<NativePanelTesting> native_panel_testing( CreateNativePanelTesting(panel)); // Test that the attention should not be drawn if the detached panel is in // focus. WaitForPanelActiveState(panel, SHOW_AS_ACTIVE); // doublecheck active state EXPECT_FALSE(panel->IsDrawingAttention()); panel->FlashFrame(true); EXPECT_FALSE(panel->IsDrawingAttention()); EXPECT_FALSE(native_panel_testing->VerifyDrawingAttention()); panel->Close(); } // http://crbug.com/143247 #if !defined(OS_WIN) #define MAYBE_DrawAttentionOnInactive DISABLED_DrawAttentionOnInactive #else #define MAYBE_DrawAttentionOnInactive DrawAttentionOnInactive #endif IN_PROC_BROWSER_TEST_F(DetachedPanelBrowserTest, MAYBE_DrawAttentionOnInactive) { // Create two panels so that first panel becomes inactive. Panel* panel = CreateDetachedPanel("1", gfx::Rect(300, 200, 250, 200)); CreateDetachedPanel("2", gfx::Rect(100, 100, 250, 200)); WaitForPanelActiveState(panel, SHOW_AS_INACTIVE); scoped_ptr<NativePanelTesting> native_panel_testing( CreateNativePanelTesting(panel)); // Test that the attention is drawn when the detached panel is not in focus. EXPECT_FALSE(panel->IsActive()); EXPECT_FALSE(panel->IsDrawingAttention()); panel->FlashFrame(true); EXPECT_TRUE(panel->IsDrawingAttention()); EXPECT_TRUE(native_panel_testing->VerifyDrawingAttention()); // Stop drawing attention. panel->FlashFrame(false); EXPECT_FALSE(panel->IsDrawingAttention()); EXPECT_FALSE(native_panel_testing->VerifyDrawingAttention()); PanelManager::GetInstance()->CloseAll(); } // http://crbug.com/143247 #if !defined(OS_WIN) #define MAYBE_DrawAttentionResetOnActivate DISABLED_DrawAttentionResetOnActivate #else #define MAYBE_DrawAttentionResetOnActivate DrawAttentionResetOnActivate #endif IN_PROC_BROWSER_TEST_F(DetachedPanelBrowserTest, MAYBE_DrawAttentionResetOnActivate) { // Create 2 panels so we end up with an inactive panel that can // be made to draw attention. Panel* panel1 = CreateDetachedPanel("test panel1", gfx::Rect(300, 200, 250, 200)); Panel* panel2 = CreateDetachedPanel("test panel2", gfx::Rect(100, 100, 250, 200)); WaitForPanelActiveState(panel1, SHOW_AS_INACTIVE); scoped_ptr<NativePanelTesting> native_panel_testing( CreateNativePanelTesting(panel1)); // Test that the attention is drawn when the detached panel is not in focus. panel1->FlashFrame(true); EXPECT_TRUE(panel1->IsDrawingAttention()); EXPECT_TRUE(native_panel_testing->VerifyDrawingAttention()); // Test that the attention is cleared when panel gets focus. panel1->Activate(); WaitForPanelActiveState(panel1, SHOW_AS_ACTIVE); EXPECT_FALSE(panel1->IsDrawingAttention()); EXPECT_FALSE(native_panel_testing->VerifyDrawingAttention()); panel1->Close(); panel2->Close(); } // http://crbug.com/143247 #if !defined(OS_WIN) #define MAYBE_ClickTitlebar DISABLED_ClickTitlebar #else #define MAYBE_ClickTitlebar ClickTitlebar #endif IN_PROC_BROWSER_TEST_F(DetachedPanelBrowserTest, MAYBE_ClickTitlebar) { PanelManager* panel_manager = PanelManager::GetInstance(); Panel* panel = CreateDetachedPanel("1", gfx::Rect(300, 200, 250, 200)); EXPECT_FALSE(panel->IsMinimized()); // Clicking on an active detached panel's titlebar has no effect, regardless // of modifier. WaitForPanelActiveState(panel, SHOW_AS_ACTIVE); // doublecheck active state scoped_ptr<NativePanelTesting> test_panel( CreateNativePanelTesting(panel)); test_panel->PressLeftMouseButtonTitlebar(panel->GetBounds().origin()); test_panel->ReleaseMouseButtonTitlebar(); EXPECT_TRUE(panel->IsActive()); EXPECT_FALSE(panel->IsMinimized()); test_panel->PressLeftMouseButtonTitlebar(panel->GetBounds().origin(), panel::APPLY_TO_ALL); test_panel->ReleaseMouseButtonTitlebar(panel::APPLY_TO_ALL); EXPECT_TRUE(panel->IsActive()); EXPECT_FALSE(panel->IsMinimized()); // Create a second panel to cause the first to become inactive. CreateDetachedPanel("2", gfx::Rect(100, 200, 230, 345)); WaitForPanelActiveState(panel, SHOW_AS_INACTIVE); // Clicking on an inactive detached panel's titlebar activates it. test_panel->PressLeftMouseButtonTitlebar(panel->GetBounds().origin()); test_panel->ReleaseMouseButtonTitlebar(); WaitForPanelActiveState(panel, SHOW_AS_ACTIVE); EXPECT_FALSE(panel->IsMinimized()); panel_manager->CloseAll(); } IN_PROC_BROWSER_TEST_F(DetachedPanelBrowserTest, UpdateDetachedPanelOnPrimaryDisplayChange) { PanelManager* panel_manager = PanelManager::GetInstance(); // Create a big detached panel on the primary display. gfx::Rect initial_bounds(50, 50, 700, 500); Panel* panel = CreateDetachedPanel("1", initial_bounds); EXPECT_EQ(initial_bounds, panel->GetBounds()); // Make the primary display smaller. // Expect that the panel should be resized to fit within the display. gfx::Rect primary_display_area(0, 0, 500, 300); gfx::Rect primary_work_area(0, 0, 500, 280); mock_display_settings_provider()->SetPrimaryDisplay( primary_display_area, primary_work_area); gfx::Rect bounds = panel->GetBounds(); EXPECT_LE(primary_work_area.x(), bounds.x()); EXPECT_LE(bounds.x(), primary_work_area.right()); EXPECT_LE(primary_work_area.y(), bounds.y()); EXPECT_LE(bounds.y(), primary_work_area.bottom()); panel_manager->CloseAll(); } IN_PROC_BROWSER_TEST_F(DetachedPanelBrowserTest, UpdateDetachedPanelOnSecondaryDisplayChange) { PanelManager* panel_manager = PanelManager::GetInstance(); // Setup 2 displays with secondary display on the right side of primary // display. gfx::Rect primary_display_area(0, 0, 400, 600); gfx::Rect primary_work_area(0, 0, 400, 560); mock_display_settings_provider()->SetPrimaryDisplay( primary_display_area, primary_work_area); gfx::Rect secondary_display_area(400, 0, 400, 500); gfx::Rect secondary_work_area(400, 0, 400, 460); mock_display_settings_provider()->SetSecondaryDisplay( secondary_display_area, secondary_work_area); // Create a big detached panel on the seconday display. gfx::Rect initial_bounds(450, 50, 350, 400); Panel* panel = CreateDetachedPanel("1", initial_bounds); EXPECT_EQ(initial_bounds, panel->GetBounds()); // Move down the secondary display and make it smaller. // Expect that the panel should be resized to fit within the display. secondary_display_area.SetRect(400, 100, 300, 400); secondary_work_area.SetRect(400, 100, 300, 360); mock_display_settings_provider()->SetSecondaryDisplay( secondary_display_area, secondary_work_area); gfx::Rect bounds = panel->GetBounds(); EXPECT_LE(secondary_work_area.x(), bounds.x()); EXPECT_LE(bounds.x(), secondary_work_area.right()); EXPECT_LE(secondary_work_area.y(), bounds.y()); EXPECT_LE(bounds.y(), secondary_work_area.bottom()); panel_manager->CloseAll(); }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop.h" #include "chrome/browser/ui/panels/base_panel_browser_test.h" #include "chrome/browser/ui/panels/detached_panel_collection.h" #include "chrome/browser/ui/panels/native_panel.h" #include "chrome/browser/ui/panels/panel.h" #include "chrome/browser/ui/panels/panel_manager.h" class DetachedPanelBrowserTest : public BasePanelBrowserTest { }; IN_PROC_BROWSER_TEST_F(DetachedPanelBrowserTest, CheckDetachedPanelProperties) { PanelManager* panel_manager = PanelManager::GetInstance(); DetachedPanelCollection* detached_collection = panel_manager->detached_collection(); // Create an initially detached panel (as opposed to other tests which create // a docked panel, then detaches it). gfx::Rect bounds(300, 200, 250, 200); CreatePanelParams params("1", bounds, SHOW_AS_ACTIVE); params.create_mode = PanelManager::CREATE_AS_DETACHED; Panel* panel = CreatePanelWithParams(params); scoped_ptr<NativePanelTesting> panel_testing( CreateNativePanelTesting(panel)); EXPECT_EQ(1, panel_manager->num_panels()); EXPECT_TRUE(detached_collection->HasPanel(panel)); EXPECT_EQ(bounds.x(), panel->GetBounds().x()); // Ignore checking y position since the detached panel will be placed near // the top if the stacking mode is enabled. if (!PanelManager::IsPanelStackingEnabled()) EXPECT_EQ(bounds.y(), panel->GetBounds().y()); EXPECT_EQ(bounds.width(), panel->GetBounds().width()); EXPECT_EQ(bounds.height(), panel->GetBounds().height()); EXPECT_FALSE(panel->IsAlwaysOnTop()); EXPECT_TRUE(panel_testing->IsButtonVisible(panel::CLOSE_BUTTON)); // The minimize button will not be shown on some Linux desktop environment // that does not support system minimize. if (PanelManager::CanUseSystemMinimize()) EXPECT_TRUE(panel_testing->IsButtonVisible(panel::MINIMIZE_BUTTON)); else EXPECT_FALSE(panel_testing->IsButtonVisible(panel::MINIMIZE_BUTTON)); EXPECT_FALSE(panel_testing->IsButtonVisible(panel::RESTORE_BUTTON)); EXPECT_EQ(panel::RESIZABLE_ALL, panel->CanResizeByMouse()); EXPECT_EQ(panel::ALL_ROUNDED, panel_testing->GetWindowCornerStyle()); Panel::AttentionMode expected_attention_mode = static_cast<Panel::AttentionMode>(Panel::USE_PANEL_ATTENTION | Panel::USE_SYSTEM_ATTENTION); EXPECT_EQ(expected_attention_mode, panel->attention_mode()); panel_manager->CloseAll(); } // http://crbug.com/143247 #if !defined(OS_WIN) #define MAYBE_DrawAttentionOnActive DISABLED_DrawAttentionOnActive #else #define MAYBE_DrawAttentionOnActive DrawAttentionOnActive #endif IN_PROC_BROWSER_TEST_F(DetachedPanelBrowserTest, MAYBE_DrawAttentionOnActive) { // Create a detached panel that is initially active. Panel* panel = CreateDetachedPanel("1", gfx::Rect(300, 200, 250, 200)); scoped_ptr<NativePanelTesting> native_panel_testing( CreateNativePanelTesting(panel)); // Test that the attention should not be drawn if the detached panel is in // focus. WaitForPanelActiveState(panel, SHOW_AS_ACTIVE); // doublecheck active state EXPECT_FALSE(panel->IsDrawingAttention()); panel->FlashFrame(true); EXPECT_FALSE(panel->IsDrawingAttention()); EXPECT_FALSE(native_panel_testing->VerifyDrawingAttention()); panel->Close(); } // http://crbug.com/143247 #if !defined(OS_WIN) #define MAYBE_DrawAttentionOnInactive DISABLED_DrawAttentionOnInactive #else #define MAYBE_DrawAttentionOnInactive DrawAttentionOnInactive #endif IN_PROC_BROWSER_TEST_F(DetachedPanelBrowserTest, MAYBE_DrawAttentionOnInactive) { // Create two panels so that first panel becomes inactive. Panel* panel = CreateDetachedPanel("1", gfx::Rect(300, 200, 250, 200)); CreateDetachedPanel("2", gfx::Rect(100, 100, 250, 200)); WaitForPanelActiveState(panel, SHOW_AS_INACTIVE); scoped_ptr<NativePanelTesting> native_panel_testing( CreateNativePanelTesting(panel)); // Test that the attention is drawn when the detached panel is not in focus. EXPECT_FALSE(panel->IsActive()); EXPECT_FALSE(panel->IsDrawingAttention()); panel->FlashFrame(true); EXPECT_TRUE(panel->IsDrawingAttention()); EXPECT_TRUE(native_panel_testing->VerifyDrawingAttention()); // Stop drawing attention. panel->FlashFrame(false); EXPECT_FALSE(panel->IsDrawingAttention()); EXPECT_FALSE(native_panel_testing->VerifyDrawingAttention()); PanelManager::GetInstance()->CloseAll(); } // http://crbug.com/143247 #if !defined(OS_WIN) #define MAYBE_DrawAttentionResetOnActivate DISABLED_DrawAttentionResetOnActivate #else #define MAYBE_DrawAttentionResetOnActivate DrawAttentionResetOnActivate #endif IN_PROC_BROWSER_TEST_F(DetachedPanelBrowserTest, MAYBE_DrawAttentionResetOnActivate) { // Create 2 panels so we end up with an inactive panel that can // be made to draw attention. Panel* panel1 = CreateDetachedPanel("test panel1", gfx::Rect(300, 200, 250, 200)); Panel* panel2 = CreateDetachedPanel("test panel2", gfx::Rect(100, 100, 250, 200)); WaitForPanelActiveState(panel1, SHOW_AS_INACTIVE); scoped_ptr<NativePanelTesting> native_panel_testing( CreateNativePanelTesting(panel1)); // Test that the attention is drawn when the detached panel is not in focus. panel1->FlashFrame(true); EXPECT_TRUE(panel1->IsDrawingAttention()); EXPECT_TRUE(native_panel_testing->VerifyDrawingAttention()); // Test that the attention is cleared when panel gets focus. panel1->Activate(); WaitForPanelActiveState(panel1, SHOW_AS_ACTIVE); EXPECT_FALSE(panel1->IsDrawingAttention()); EXPECT_FALSE(native_panel_testing->VerifyDrawingAttention()); panel1->Close(); panel2->Close(); } // http://crbug.com/143247 #if !defined(OS_WIN) #define MAYBE_ClickTitlebar DISABLED_ClickTitlebar #else #define MAYBE_ClickTitlebar ClickTitlebar #endif IN_PROC_BROWSER_TEST_F(DetachedPanelBrowserTest, MAYBE_ClickTitlebar) { PanelManager* panel_manager = PanelManager::GetInstance(); Panel* panel = CreateDetachedPanel("1", gfx::Rect(300, 200, 250, 200)); EXPECT_FALSE(panel->IsMinimized()); // Clicking on an active detached panel's titlebar has no effect, regardless // of modifier. WaitForPanelActiveState(panel, SHOW_AS_ACTIVE); // doublecheck active state scoped_ptr<NativePanelTesting> test_panel( CreateNativePanelTesting(panel)); test_panel->PressLeftMouseButtonTitlebar(panel->GetBounds().origin()); test_panel->ReleaseMouseButtonTitlebar(); EXPECT_TRUE(panel->IsActive()); EXPECT_FALSE(panel->IsMinimized()); test_panel->PressLeftMouseButtonTitlebar(panel->GetBounds().origin(), panel::APPLY_TO_ALL); test_panel->ReleaseMouseButtonTitlebar(panel::APPLY_TO_ALL); EXPECT_TRUE(panel->IsActive()); EXPECT_FALSE(panel->IsMinimized()); // Create a second panel to cause the first to become inactive. CreateDetachedPanel("2", gfx::Rect(100, 200, 230, 345)); WaitForPanelActiveState(panel, SHOW_AS_INACTIVE); // Clicking on an inactive detached panel's titlebar activates it. test_panel->PressLeftMouseButtonTitlebar(panel->GetBounds().origin()); test_panel->ReleaseMouseButtonTitlebar(); WaitForPanelActiveState(panel, SHOW_AS_ACTIVE); EXPECT_FALSE(panel->IsMinimized()); panel_manager->CloseAll(); } IN_PROC_BROWSER_TEST_F(DetachedPanelBrowserTest, UpdateDetachedPanelOnPrimaryDisplayChange) { PanelManager* panel_manager = PanelManager::GetInstance(); // Create a big detached panel on the primary display. gfx::Rect initial_bounds(50, 50, 700, 500); Panel* panel = CreateDetachedPanel("1", initial_bounds); EXPECT_EQ(initial_bounds, panel->GetBounds()); // Make the primary display smaller. // Expect that the panel should be resized to fit within the display. gfx::Rect primary_display_area(0, 0, 500, 300); gfx::Rect primary_work_area(0, 0, 500, 280); mock_display_settings_provider()->SetPrimaryDisplay( primary_display_area, primary_work_area); gfx::Rect bounds = panel->GetBounds(); EXPECT_LE(primary_work_area.x(), bounds.x()); EXPECT_LE(bounds.x(), primary_work_area.right()); EXPECT_LE(primary_work_area.y(), bounds.y()); EXPECT_LE(bounds.y(), primary_work_area.bottom()); panel_manager->CloseAll(); } IN_PROC_BROWSER_TEST_F(DetachedPanelBrowserTest, UpdateDetachedPanelOnSecondaryDisplayChange) { PanelManager* panel_manager = PanelManager::GetInstance(); // Setup 2 displays with secondary display on the right side of primary // display. gfx::Rect primary_display_area(0, 0, 400, 600); gfx::Rect primary_work_area(0, 0, 400, 560); mock_display_settings_provider()->SetPrimaryDisplay( primary_display_area, primary_work_area); gfx::Rect secondary_display_area(400, 0, 400, 500); gfx::Rect secondary_work_area(400, 0, 400, 460); mock_display_settings_provider()->SetSecondaryDisplay( secondary_display_area, secondary_work_area); // Create a big detached panel on the seconday display. gfx::Rect initial_bounds(450, 50, 350, 400); Panel* panel = CreateDetachedPanel("1", initial_bounds); EXPECT_EQ(initial_bounds, panel->GetBounds()); // Move down the secondary display and make it smaller. // Expect that the panel should be resized to fit within the display. secondary_display_area.SetRect(400, 100, 300, 400); secondary_work_area.SetRect(400, 100, 300, 360); mock_display_settings_provider()->SetSecondaryDisplay( secondary_display_area, secondary_work_area); gfx::Rect bounds = panel->GetBounds(); EXPECT_LE(secondary_work_area.x(), bounds.x()); EXPECT_LE(bounds.x(), secondary_work_area.right()); EXPECT_LE(secondary_work_area.y(), bounds.y()); EXPECT_LE(bounds.y(), secondary_work_area.bottom()); panel_manager->CloseAll(); }
Fix and reenable DetachedPanelBrowserTest.CheckDetachedPanelProperties
Fix and reenable DetachedPanelBrowserTest.CheckDetachedPanelProperties The failure is due to that the minimize button is not shown on some Linux desktop environment that does not support system minimize well. The fix is to add the check for that. BUG=143247 TEST=test reenabled Review URL: https://chromiumcodereview.appspot.com/18328011 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@209539 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
markYoungH/chromium.src,anirudhSK/chromium,Chilledheart/chromium,jaruba/chromium.src,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,jaruba/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,jaruba/chromium.src,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,bright-sparks/chromium-spacewalk,Just-D/chromium-1,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,jaruba/chromium.src,ondra-novak/chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,anirudhSK/chromium,ChromiumWebApps/chromium,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,Chilledheart/chromium,markYoungH/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,Jonekee/chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,dushu1203/chromium.src,anirudhSK/chromium,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,littlstar/chromium.src,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,patrickm/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,littlstar/chromium.src,chuan9/chromium-crosswalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,dednal/chromium.src,littlstar/chromium.src,littlstar/chromium.src,Just-D/chromium-1,Jonekee/chromium.src,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,krieger-od/nwjs_chromium.src,Chilledheart/chromium,Jonekee/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,ondra-novak/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk,patrickm/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,anirudhSK/chromium,Just-D/chromium-1,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,jaruba/chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,ChromiumWebApps/chromium,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,littlstar/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,ondra-novak/chromium.src,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,patrickm/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ltilve/chromium,ltilve/chromium,ltilve/chromium,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,ltilve/chromium,Fireblend/chromium-crosswalk,dednal/chromium.src,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,patrickm/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,Fireblend/chromium-crosswalk,patrickm/chromium.src,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,Just-D/chromium-1,axinging/chromium-crosswalk,M4sse/chromium.src,M4sse/chromium.src,mogoweb/chromium-crosswalk,Chilledheart/chromium,ChromiumWebApps/chromium,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,Jonekee/chromium.src,dushu1203/chromium.src,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,markYoungH/chromium.src,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,markYoungH/chromium.src,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,jaruba/chromium.src,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,ltilve/chromium,dednal/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,dednal/chromium.src,fujunwei/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,dednal/chromium.src,Chilledheart/chromium,chuan9/chromium-crosswalk,jaruba/chromium.src,M4sse/chromium.src,dednal/chromium.src,ltilve/chromium,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,patrickm/chromium.src,patrickm/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,dushu1203/chromium.src
1cabead420ff11bd51d4ae4e01c23062c50e881e
pythran/pythonic/include/numpy/dot.hpp
pythran/pythonic/include/numpy/dot.hpp
#ifndef PYTHONIC_INCLUDE_NUMPY_DOT_HPP #define PYTHONIC_INCLUDE_NUMPY_DOT_HPP #include "pythonic/include/types/ndarray.hpp" #include "pythonic/include/numpy/sum.hpp" #include "pythonic/include/types/numpy_expr.hpp" #include "pythonic/include/types/traits.hpp" template <class T> struct is_blas_type : pythonic::types::is_complex<T> { }; template <> struct is_blas_type<float> : std::true_type { }; template <> struct is_blas_type<double> : std::true_type { }; PYTHONIC_NS_BEGIN namespace numpy { template <class E, class F> typename std::enable_if<types::is_dtype<E>::value && types::is_dtype<F>::value, decltype(std::declval<E>() * std::declval<F>())>::type dot(E const &e, F const &f); /// Vector / Vector multiplication template <class E, class F> typename std::enable_if< types::is_numexpr_arg<E>::value && types::is_numexpr_arg<F>::value // Arguments are array_like && E::value == 1 && F::value == 1, // It is a two vectors. typename __combined<typename E::dtype, typename F::dtype>::type>::type dot(E const &e, F const &f); template <class pS0, class pS1> typename std::enable_if<std::tuple_size<pS0>::value == 1 && std::tuple_size<pS1>::value == 1, float>::type dot(types::ndarray<float, pS0> const &e, types::ndarray<float, pS1> const &f); template <class pS0, class pS1> typename std::enable_if<std::tuple_size<pS0>::value == 1 && std::tuple_size<pS1>::value == 1, double>::type dot(types::ndarray<double, pS0> const &e, types::ndarray<double, pS1> const &f); /// Matrice / Vector multiplication // We transpose the matrix to reflect our C order template <class E, class pS0, class pS1> typename std::enable_if<is_blas_type<E>::value && std::tuple_size<pS0>::value == 2 && std::tuple_size<pS1>::value == 1, types::ndarray<E, types::pshape<long>>>::type dot(types::ndarray<E, pS0> const &f, types::ndarray<E, pS1> const &e); // The trick is to ! transpose the matrix so that MV become VM template <class E, class pS0, class pS1> typename std::enable_if<is_blas_type<E>::value && std::tuple_size<pS0>::value == 1 && std::tuple_size<pS1>::value == 2, types::ndarray<E, types::pshape<long>>>::type dot(types::ndarray<E, pS0> const &e, types::ndarray<E, pS1> const &f); // If arguments could be use with blas, we evaluate them as we need pointer // on array for blas template <class E, class F> typename std::enable_if< types::is_numexpr_arg<E>::value && types::is_numexpr_arg<F>::value // It is an array_like && !(types::is_ndarray<E>::value && types::is_ndarray<F>::value) && is_blas_type<typename E::dtype>::value && is_blas_type<typename F::dtype>::value // With dtype compatible with // blas && E::value == 2 && F::value == 1, // And it is matrix / vect types::ndarray< typename __combined<typename E::dtype, typename F::dtype>::type, types::pshape<long>>>::type dot(E const &e, F const &f); // If arguments could be use with blas, we evaluate them as we need pointer // on array for blas template <class E, class F> typename std::enable_if< types::is_numexpr_arg<E>::value && types::is_numexpr_arg<F>::value // It is an array_like && !(types::is_ndarray<E>::value && types::is_ndarray<F>::value) && is_blas_type<typename E::dtype>::value && is_blas_type<typename F::dtype>::value // With dtype compatible with // blas && E::value == 1 && F::value == 2, // And it is vect / matrix types::ndarray< typename __combined<typename E::dtype, typename F::dtype>::type, types::pshape<long>>>::type dot(E const &e, F const &f); // If one of the arg doesn't have a "blas compatible type", we use a slow // matrix vector multiplication. template <class E, class F> typename std::enable_if< (!is_blas_type<typename E::dtype>::value || !is_blas_type<typename F::dtype>::value) && E::value == 1 && F::value == 2, // And it is vect / matrix types::ndarray< typename __combined<typename E::dtype, typename F::dtype>::type, types::pshape<long>>>::type dot(E const &e, F const &f); // If one of the arg doesn't have a "blas compatible type", we use a slow // matrix vector multiplication. template <class E, class F> typename std::enable_if< (!is_blas_type<typename E::dtype>::value || !is_blas_type<typename F::dtype>::value) && E::value == 2 && F::value == 1, // And it is vect / matrix types::ndarray< typename __combined<typename E::dtype, typename F::dtype>::type, types::pshape<long>>>::type dot(E const &e, F const &f); /// Matrix / Matrix multiplication // The trick is to use the transpose arguments to reflect C order. // We want to perform A * B in C order but blas order is F order. // So we compute B'A' == (AB)'. As this equality is perform with F order // We doesn't have to return a texpr because we want a C order matrice!! template <class E, class pS0, class pS1> typename std::enable_if<is_blas_type<E>::value && std::tuple_size<pS0>::value == 2 && std::tuple_size<pS1>::value == 2, types::ndarray<E, types::array<long, 2>>>::type dot(types::ndarray<E, pS0> const &a, types::ndarray<E, pS1> const &b); template <class E, class pS0, class pS1, class pS2> typename std::enable_if< is_blas_type<E>::value && std::tuple_size<pS0>::value == 2 && std::tuple_size<pS1>::value == 2 && std::tuple_size<pS2>::value == 2, types::ndarray<E, pS2>>::type & dot(types::ndarray<E, pS0> const &a, types::ndarray<E, pS1> const &b, types::ndarray<E, pS2> &c); // If arguments could be sue with blas, we evaluate them as we need pointer // on array for blas template <class E, class F> typename std::enable_if< types::is_numexpr_arg<E>::value && types::is_numexpr_arg<F>::value // It is an array_like && !(types::is_ndarray<E>::value && types::is_ndarray<F>::value) && is_blas_type<typename E::dtype>::value && is_blas_type<typename F::dtype>::value // With dtype compatible with // blas && E::value == 2 && F::value == 2, // And both are matrix types::ndarray< typename __combined<typename E::dtype, typename F::dtype>::type, types::array<long, 2>>>::type dot(E const &e, F const &f); // If one of the arg doesn't have a "blas compatible type", we use a slow // matrix multiplication. template <class E, class F> typename std::enable_if< (!is_blas_type<typename E::dtype>::value || !is_blas_type<typename F::dtype>::value) && E::value == 2 && F::value == 2, // And it is matrix / matrix types::ndarray< typename __combined<typename E::dtype, typename F::dtype>::type, types::array<long, 2>>>::type dot(E const &e, F const &f); DEFINE_FUNCTOR(pythonic::numpy, dot); } PYTHONIC_NS_END #endif
#ifndef PYTHONIC_INCLUDE_NUMPY_DOT_HPP #define PYTHONIC_INCLUDE_NUMPY_DOT_HPP #include "pythonic/include/types/ndarray.hpp" #include "pythonic/include/numpy/sum.hpp" #include "pythonic/include/types/numpy_expr.hpp" #include "pythonic/include/types/traits.hpp" template <class T> struct is_blas_type : pythonic::types::is_complex<T> { }; template <> struct is_blas_type<float> : std::true_type { }; template <> struct is_blas_type<double> : std::true_type { }; PYTHONIC_NS_BEGIN namespace numpy { template <class E, class F> typename std::enable_if<types::is_dtype<E>::value && types::is_dtype<F>::value, decltype(std::declval<E>() * std::declval<F>())>::type dot(E const &e, F const &f); /// Vector / Vector multiplication template <class E, class F> typename std::enable_if< types::is_numexpr_arg<E>::value && types::is_numexpr_arg<F>::value // Arguments are array_like && E::value == 1 && F::value == 1, // It is a two vectors. typename __combined<typename E::dtype, typename F::dtype>::type>::type dot(E const &e, F const &f); template <class pS0, class pS1> typename std::enable_if<std::tuple_size<pS0>::value == 1 && std::tuple_size<pS1>::value == 1, float>::type dot(types::ndarray<float, pS0> const &e, types::ndarray<float, pS1> const &f); template <class pS0, class pS1> typename std::enable_if<std::tuple_size<pS0>::value == 1 && std::tuple_size<pS1>::value == 1, double>::type dot(types::ndarray<double, pS0> const &e, types::ndarray<double, pS1> const &f); /// Matrice / Vector multiplication // We transpose the matrix to reflect our C order template <class E, class pS0, class pS1> typename std::enable_if<is_blas_type<E>::value && std::tuple_size<pS0>::value == 2 && std::tuple_size<pS1>::value == 1, types::ndarray<E, types::pshape<long>>>::type dot(types::ndarray<E, pS0> const &f, types::ndarray<E, pS1> const &e); // The trick is to ! transpose the matrix so that MV become VM template <class E, class pS0, class pS1> typename std::enable_if<is_blas_type<E>::value && std::tuple_size<pS0>::value == 1 && std::tuple_size<pS1>::value == 2, types::ndarray<E, types::pshape<long>>>::type dot(types::ndarray<E, pS0> const &e, types::ndarray<E, pS1> const &f); // If arguments could be use with blas, we evaluate them as we need pointer // on array for blas template <class E, class F> typename std::enable_if< types::is_numexpr_arg<E>::value && types::is_numexpr_arg<F>::value // It is an array_like && !(types::is_ndarray<E>::value && types::is_ndarray<F>::value) && is_blas_type<typename E::dtype>::value && is_blas_type<typename F::dtype>::value // With dtype compatible with // blas && E::value == 2 && F::value == 1, // And it is matrix / vect types::ndarray< typename __combined<typename E::dtype, typename F::dtype>::type, types::pshape<long>>>::type dot(E const &e, F const &f); // If arguments could be use with blas, we evaluate them as we need pointer // on array for blas template <class E, class F> typename std::enable_if< types::is_numexpr_arg<E>::value && types::is_numexpr_arg<F>::value // It is an array_like && !(types::is_ndarray<E>::value && types::is_ndarray<F>::value) && is_blas_type<typename E::dtype>::value && is_blas_type<typename F::dtype>::value // With dtype compatible with // blas && E::value == 1 && F::value == 2, // And it is vect / matrix types::ndarray< typename __combined<typename E::dtype, typename F::dtype>::type, types::pshape<long>>>::type dot(E const &e, F const &f); // If one of the arg doesn't have a "blas compatible type", we use a slow // matrix vector multiplication. template <class E, class F> typename std::enable_if< (!is_blas_type<typename E::dtype>::value || !is_blas_type<typename F::dtype>::value) && E::value == 1 && F::value == 2, // And it is vect / matrix types::ndarray< typename __combined<typename E::dtype, typename F::dtype>::type, types::pshape<long>>>::type dot(E const &e, F const &f); // If one of the arg doesn't have a "blas compatible type", we use a slow // matrix vector multiplication. template <class E, class F> typename std::enable_if< (!is_blas_type<typename E::dtype>::value || !is_blas_type<typename F::dtype>::value) && E::value == 2 && F::value == 1, // And it is vect / matrix types::ndarray< typename __combined<typename E::dtype, typename F::dtype>::type, types::pshape<long>>>::type dot(E const &e, F const &f); /// Matrix / Matrix multiplication // The trick is to use the transpose arguments to reflect C order. // We want to perform A * B in C order but blas order is F order. // So we compute B'A' == (AB)'. As this equality is perform with F order // We doesn't have to return a texpr because we want a C order matrice!! template <class E, class pS0, class pS1> typename std::enable_if<is_blas_type<E>::value && std::tuple_size<pS0>::value == 2 && std::tuple_size<pS1>::value == 2, types::ndarray<E, types::array<long, 2>>>::type dot(types::ndarray<E, pS0> const &a, types::ndarray<E, pS1> const &b); template <class E, class pS0, class pS1, class pS2> typename std::enable_if< is_blas_type<E>::value && std::tuple_size<pS0>::value == 2 && std::tuple_size<pS1>::value == 2 && std::tuple_size<pS2>::value == 2, types::ndarray<E, pS2>>::type & dot(types::ndarray<E, pS0> const &a, types::ndarray<E, pS1> const &b, types::ndarray<E, pS2> &c); // texpr variants: MT, TM, TT template <class E, class pS0, class pS1> typename std::enable_if<is_blas_type<E>::value && std::tuple_size<pS0>::value == 2 && std::tuple_size<pS1>::value == 2, types::ndarray<E, types::array<long, 2>>>::type dot(types::numpy_texpr<types::ndarray<E, pS0>> const &a, types::ndarray<E, pS1> const &b); template <class E, class pS0, class pS1> typename std::enable_if<is_blas_type<E>::value && std::tuple_size<pS0>::value == 2 && std::tuple_size<pS1>::value == 2, types::ndarray<E, types::array<long, 2>>>::type dot(types::ndarray<E, pS0> const &a, types::numpy_texpr<types::ndarray<E, pS1>> const &b); template <class E, class pS0, class pS1> typename std::enable_if<is_blas_type<E>::value && std::tuple_size<pS0>::value == 2 && std::tuple_size<pS1>::value == 2, types::ndarray<E, types::array<long, 2>>>::type dot(types::numpy_texpr<types::ndarray<E, pS0>> const &a, types::numpy_texpr<types::ndarray<E, pS1>> const &b); // If arguments could be use with blas, we evaluate them as we need pointer // on array for blas template <class E, class F> typename std::enable_if< types::is_numexpr_arg<E>::value && types::is_numexpr_arg<F>::value // It is an array_like && !(types::is_ndarray<E>::value && types::is_ndarray<F>::value) && is_blas_type<typename E::dtype>::value && is_blas_type<typename F::dtype>::value // With dtype compatible with // blas && E::value == 2 && F::value == 2, // And both are matrix types::ndarray< typename __combined<typename E::dtype, typename F::dtype>::type, types::array<long, 2>>>::type dot(E const &e, F const &f); // If one of the arg doesn't have a "blas compatible type", we use a slow // matrix multiplication. template <class E, class F> typename std::enable_if< (!is_blas_type<typename E::dtype>::value || !is_blas_type<typename F::dtype>::value) && E::value == 2 && F::value == 2, // And it is matrix / matrix types::ndarray< typename __combined<typename E::dtype, typename F::dtype>::type, types::array<long, 2>>>::type dot(E const &e, F const &f); DEFINE_FUNCTOR(pythonic::numpy, dot); } PYTHONIC_NS_END #endif
Fix matrix multiply forward declaration
Fix matrix multiply forward declaration Otherwise some specialization are never taken into account.
C++
bsd-3-clause
pombredanne/pythran,pombredanne/pythran,serge-sans-paille/pythran,serge-sans-paille/pythran,pombredanne/pythran
dec042f9c22397e20b4365309f890b51606fb98e
core/async-action.hh
core/async-action.hh
/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef ASYNC_ACTION_HH_ #define ASYNC_ACTION_HH_ #include "future.hh" #include "reactor.hh" // The AsyncAction concept represents an action which can complete later than // the actual function invocation. It is represented by a function which // returns a future which resolves when the action is done. template<typename AsyncAction, typename StopCondition> static inline void do_until_continued(StopCondition&& stop_cond, AsyncAction&& action, promise<> p) { while (!stop_cond()) { auto&& f = action(); if (!f.available()) { f.then([action = std::forward<AsyncAction>(action), stop_cond = std::forward<StopCondition>(stop_cond), p = std::move(p)]() mutable { do_until_continued(stop_cond, action, std::move(p)); }); return; } if (f.failed()) { f.forward_to(std::move(p)); return; } } p.set_value(); } // Invokes given action until it fails or given condition evaluates to true. template<typename AsyncAction, typename StopCondition> static inline future<> do_until(StopCondition&& stop_cond, AsyncAction&& action) { promise<> p; auto f = p.get_future(); do_until_continued(std::forward<StopCondition>(stop_cond), std::forward<AsyncAction>(action), std::move(p)); return f; } // Invoke given action undefinitely. Next invocation starts when previous completes or fails. template<typename AsyncAction> static inline void keep_doing(AsyncAction&& action) { while (true) { auto f = action(); if (!f.available()) { f.then([action = std::forward<AsyncAction>(action)] () mutable { keep_doing(std::forward<AsyncAction>(action)); }); return; } } } #endif
/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef ASYNC_ACTION_HH_ #define ASYNC_ACTION_HH_ #include "future.hh" #include "reactor.hh" // The AsyncAction concept represents an action which can complete later than // the actual function invocation. It is represented by a function which // returns a future which resolves when the action is done. template<typename AsyncAction, typename StopCondition> static inline void do_until_continued(StopCondition&& stop_cond, AsyncAction&& action, promise<> p) { while (!stop_cond()) { auto&& f = action(); if (!f.available()) { f.then([action = std::forward<AsyncAction>(action), stop_cond = std::forward<StopCondition>(stop_cond), p = std::move(p)]() mutable { do_until_continued(stop_cond, action, std::move(p)); }); return; } if (f.failed()) { f.forward_to(std::move(p)); return; } } p.set_value(); } // Invokes given action until it fails or given condition evaluates to true. template<typename AsyncAction, typename StopCondition> static inline future<> do_until(StopCondition&& stop_cond, AsyncAction&& action) { promise<> p; auto f = p.get_future(); do_until_continued(std::forward<StopCondition>(stop_cond), std::forward<AsyncAction>(action), std::move(p)); return f; } // Invoke given action undefinitely. Next invocation starts when previous completes or fails. template<typename AsyncAction> static inline void keep_doing(AsyncAction&& action) { while (true) { auto f = action(); if (!f.available()) { f.then([action = std::forward<AsyncAction>(action)] () mutable { keep_doing(std::forward<AsyncAction>(action)); }); return; } } } template<typename Iterator, typename AsyncAction> static inline future<> do_for_each(Iterator begin, Iterator end, AsyncAction&& action) { while (begin != end) { auto f = action(*begin++); if (!f.available()) { return f.then([action = std::forward<AsyncAction>(action), begin = std::move(begin), end = std::move(end)] () mutable { return do_for_each(std::move(begin), std::move(end), std::forward<AsyncAction>(action)); }); } } return make_ready_future<>(); } #endif
introduce do_for_each()
core: introduce do_for_each() Useful when composing iteration with async operations.
C++
apache-2.0
scylladb/scylla-seastar,ducthangho/imdb,avikivity/seastar,tempbottle/seastar,tempbottle/scylla,hongliangzhao/seastar,cloudius-systems/seastar,rentongzhang/scylla,bowlofstew/seastar,joerg84/seastar,rluta/scylla,asias/scylla,slivne/seastar,bowlofstew/seastar,kangkot/scylla,justintung/scylla,kjniemi/scylla,shyamalschandra/seastar,dwdm/seastar,kjniemi/scylla,acbellini/seastar,koolhazz/seastar,linearregression/scylla,kjniemi/seastar,bowlofstew/scylla,raphaelsc/scylla,senseb/scylla,flashbuckets/seastar,guiquanz/scylla,syuu1228/seastar,justintung/scylla,syuu1228/seastar,raphaelsc/seastar,guiquanz/scylla,scylladb/scylla,acbellini/scylla,duarten/scylla,jonathanleang/seastar,tempbottle/scylla,avikivity/scylla,bowlofstew/scylla,xtao/seastar,norcimo5/seastar,linearregression/seastar,eklitzke/scylla,bzero/seastar,asias/scylla,jonathanleang/seastar,acbellini/seastar,raphaelsc/scylla,xtao/seastar,scylladb/seastar,jonathanleang/seastar,scylladb/scylla,dwdm/seastar,leejir/seastar,mixja/seastar,flashbuckets/seastar,norcimo5/seastar,guiquanz/scylla,kjniemi/seastar,gwicke/scylla,wildinto/scylla,sjperkins/seastar,dreamsxin/seastar,capturePointer/scylla,victorbriz/scylla,anzihenry/seastar,asias/scylla,tempbottle/seastar,dwdm/scylla,avikivity/seastar,hongliangzhao/seastar,avikivity/seastar,wildinto/seastar,cloudius-systems/seastar,scylladb/seastar,glommer/scylla,eklitzke/scylla,acbellini/scylla,scylladb/scylla-seastar,shaunstanislaus/scylla,hongliangzhao/seastar,wildinto/seastar,acbellini/seastar,respu/scylla,respu/scylla,slivne/seastar,dreamsxin/seastar,printedheart/seastar,shyamalschandra/seastar,scylladb/scylla,raphaelsc/scylla,stamhe/scylla,linearregression/seastar,ducthangho/imdb,koolhazz/seastar,chunshengster/seastar,wildinto/scylla,linearregression/scylla,printedheart/seastar,duarten/scylla,glommer/scylla,shaunstanislaus/scylla,stamhe/scylla,wildinto/seastar,victorbriz/scylla,sjperkins/seastar,stamhe/scylla,linearregression/scylla,raphaelsc/seastar,joerg84/seastar,dwdm/scylla,chunshengster/seastar,acbellini/scylla,phonkee/scylla,bowlofstew/seastar,syuu1228/seastar,bzero/seastar,stamhe/seastar,stamhe/seastar,capturePointer/scylla,gwicke/scylla,linearregression/seastar,flashbuckets/seastar,scylladb/scylla,shaunstanislaus/scylla,tempbottle/seastar,duarten/scylla,koolhazz/seastar,bowlofstew/scylla,senseb/scylla,senseb/scylla,cloudius-systems/seastar,wildinto/scylla,rluta/scylla,capturePointer/scylla,dreamsxin/seastar,dwdm/scylla,phonkee/scylla,avikivity/scylla,kjniemi/scylla,tempbottle/scylla,victorbriz/scylla,leejir/seastar,leejir/seastar,mixja/seastar,slivne/seastar,aruanruan/scylla,norcimo5/seastar,respu/scylla,aruanruan/scylla,chunshengster/seastar,ducthangho/imdb,scylladb/scylla-seastar,gwicke/scylla,printedheart/seastar,justintung/scylla,scylladb/seastar,aruanruan/scylla,stamhe/seastar,xtao/seastar,avikivity/scylla,kangkot/scylla,anzihenry/seastar,shyamalschandra/seastar,dwdm/seastar,bzero/seastar,anzihenry/seastar,rluta/scylla,glommer/scylla,rentongzhang/scylla,sjperkins/seastar,kangkot/scylla,joerg84/seastar,rentongzhang/scylla,phonkee/scylla,mixja/seastar,eklitzke/scylla,raphaelsc/seastar,kjniemi/seastar
abb49e24699d093b77c7db50428e8f9048c9f42b
gfx/font_win.cc
gfx/font_win.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gfx/font.h" #include <windows.h> #include <math.h> #include <algorithm> #include "base/logging.h" #include "base/string_util.h" #include "base/win_util.h" #include "gfx/canvas_skia.h" namespace gfx { // static Font::HFontRef* Font::base_font_ref_; // static Font::AdjustFontCallback Font::adjust_font_callback = NULL; Font::GetMinimumFontSizeCallback Font::get_minimum_font_size_callback = NULL; // If the tmWeight field of a TEXTMETRIC structure has a value >= this, the // font is bold. static const int kTextMetricWeightBold = 700; // Returns either minimum font allowed for a current locale or // lf_height + size_delta value. static int AdjustFontSize(int lf_height, int size_delta) { if (lf_height < 0) { lf_height -= size_delta; } else { lf_height += size_delta; } int min_font_size = 0; if (Font::get_minimum_font_size_callback) min_font_size = Font::get_minimum_font_size_callback(); // Make sure lf_height is not smaller than allowed min font size for current // locale. if (abs(lf_height) < min_font_size) { return lf_height < 0 ? -min_font_size : min_font_size; } else { return lf_height; } } // // Font // Font::Font() : font_ref_(GetBaseFontRef()) { } int Font::height() const { return font_ref_->height(); } int Font::baseline() const { return font_ref_->baseline(); } int Font::ave_char_width() const { return font_ref_->ave_char_width(); } int Font::GetExpectedTextWidth(int length) const { return length * std::min(font_ref_->dlu_base_x(), ave_char_width()); } int Font::style() const { return font_ref_->style(); } NativeFont Font::nativeFont() const { return hfont(); } // static Font Font::CreateFont(HFONT font) { DCHECK(font); LOGFONT font_info; GetObject(font, sizeof(LOGFONT), &font_info); return Font(CreateHFontRef(CreateFontIndirect(&font_info))); } Font Font::CreateFont(const std::wstring& font_name, int font_size) { HDC hdc = GetDC(NULL); long lf_height = -MulDiv(font_size, GetDeviceCaps(hdc, LOGPIXELSY), 72); ReleaseDC(NULL, hdc); HFONT hf = ::CreateFont(lf_height, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, font_name.c_str()); return Font::CreateFont(hf); } // static Font::HFontRef* Font::GetBaseFontRef() { if (base_font_ref_ == NULL) { NONCLIENTMETRICS metrics; win_util::GetNonClientMetrics(&metrics); if (adjust_font_callback) adjust_font_callback(&metrics.lfMessageFont); metrics.lfMessageFont.lfHeight = AdjustFontSize(metrics.lfMessageFont.lfHeight, 0); HFONT font = CreateFontIndirect(&metrics.lfMessageFont); DLOG_ASSERT(font); base_font_ref_ = Font::CreateHFontRef(font); // base_font_ref_ is global, up the ref count so it's never deleted. base_font_ref_->AddRef(); } return base_font_ref_; } const std::wstring& Font::FontName() const { return font_ref_->font_name(); } int Font::FontSize() { LOGFONT font_info; GetObject(hfont(), sizeof(LOGFONT), &font_info); long lf_height = font_info.lfHeight; HDC hdc = GetDC(NULL); int device_caps = GetDeviceCaps(hdc, LOGPIXELSY); int font_size = 0; if (device_caps != 0) { float font_size_float = -static_cast<float>(lf_height)*72/device_caps; font_size = static_cast<int>(::ceil(font_size_float - 0.5)); } ReleaseDC(NULL, hdc); return font_size; } Font::HFontRef::HFontRef(HFONT hfont, int height, int baseline, int ave_char_width, int style, int dlu_base_x) : hfont_(hfont), height_(height), baseline_(baseline), ave_char_width_(ave_char_width), style_(style), dlu_base_x_(dlu_base_x) { DLOG_ASSERT(hfont); LOGFONT font_info; GetObject(hfont_, sizeof(LOGFONT), &font_info); font_name_ = std::wstring(font_info.lfFaceName); } Font::HFontRef::~HFontRef() { DeleteObject(hfont_); } Font Font::DeriveFont(int size_delta, int style) const { LOGFONT font_info; GetObject(hfont(), sizeof(LOGFONT), &font_info); font_info.lfHeight = AdjustFontSize(font_info.lfHeight, size_delta); font_info.lfUnderline = ((style & UNDERLINED) == UNDERLINED); font_info.lfItalic = ((style & ITALIC) == ITALIC); font_info.lfWeight = (style & BOLD) ? FW_BOLD : FW_NORMAL; HFONT hfont = CreateFontIndirect(&font_info); return Font(CreateHFontRef(hfont)); } int Font::GetStringWidth(const std::wstring& text) const { int width = 0, height = 0; CanvasSkia::SizeStringInt(text, *this, &width, &height, gfx::Canvas::NO_ELLIPSIS); return width; } Font::HFontRef* Font::CreateHFontRef(HFONT font) { TEXTMETRIC font_metrics; HDC screen_dc = GetDC(NULL); HFONT previous_font = static_cast<HFONT>(SelectObject(screen_dc, font)); int last_map_mode = SetMapMode(screen_dc, MM_TEXT); GetTextMetrics(screen_dc, &font_metrics); // Yes, this is how Microsoft recommends calculating the dialog unit // conversions. SIZE ave_text_size; GetTextExtentPoint32(screen_dc, L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 52, &ave_text_size); const int dlu_base_x = (ave_text_size.cx / 26 + 1) / 2; // To avoid the DC referencing font_handle_, select the previous font. SelectObject(screen_dc, previous_font); SetMapMode(screen_dc, last_map_mode); ReleaseDC(NULL, screen_dc); const int height = std::max(1, static_cast<int>(font_metrics.tmHeight)); const int baseline = std::max(1, static_cast<int>(font_metrics.tmAscent)); const int ave_char_width = std::max(1, static_cast<int>(font_metrics.tmAveCharWidth)); int style = 0; if (font_metrics.tmItalic) { style |= Font::ITALIC; } if (font_metrics.tmUnderlined) { style |= Font::UNDERLINED; } if (font_metrics.tmWeight >= kTextMetricWeightBold) { style |= Font::BOLD; } return new HFontRef(font, height, baseline, ave_char_width, style, dlu_base_x); } } // namespace gfx
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gfx/font.h" #include <windows.h> #include <math.h> #include <algorithm> #include "base/logging.h" #include "base/string_util.h" #include "base/win_util.h" #include "gfx/canvas_skia.h" namespace gfx { // static Font::HFontRef* Font::base_font_ref_; // static Font::AdjustFontCallback Font::adjust_font_callback = NULL; Font::GetMinimumFontSizeCallback Font::get_minimum_font_size_callback = NULL; // If the tmWeight field of a TEXTMETRIC structure has a value >= this, the // font is bold. static const int kTextMetricWeightBold = 700; // Returns either minimum font allowed for a current locale or // lf_height + size_delta value. static int AdjustFontSize(int lf_height, int size_delta) { if (lf_height < 0) { lf_height -= size_delta; } else { lf_height += size_delta; } int min_font_size = 0; if (Font::get_minimum_font_size_callback) min_font_size = Font::get_minimum_font_size_callback(); // Make sure lf_height is not smaller than allowed min font size for current // locale. if (abs(lf_height) < min_font_size) { return lf_height < 0 ? -min_font_size : min_font_size; } else { return lf_height; } } // // Font // Font::Font() : font_ref_(GetBaseFontRef()) { } int Font::height() const { return font_ref_->height(); } int Font::baseline() const { return font_ref_->baseline(); } int Font::ave_char_width() const { return font_ref_->ave_char_width(); } int Font::GetExpectedTextWidth(int length) const { return length * std::min(font_ref_->dlu_base_x(), ave_char_width()); } int Font::style() const { return font_ref_->style(); } NativeFont Font::nativeFont() const { return hfont(); } // static Font Font::CreateFont(HFONT font) { DCHECK(font); LOGFONT font_info; GetObject(font, sizeof(LOGFONT), &font_info); return Font(CreateHFontRef(CreateFontIndirect(&font_info))); } Font Font::CreateFont(const std::wstring& font_name, int font_size) { HDC hdc = GetDC(NULL); long lf_height = -MulDiv(font_size, GetDeviceCaps(hdc, LOGPIXELSY), 72); ReleaseDC(NULL, hdc); HFONT hf = ::CreateFont(lf_height, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, font_name.c_str()); return Font::CreateFont(hf); } // static Font::HFontRef* Font::GetBaseFontRef() { if (base_font_ref_ == NULL) { NONCLIENTMETRICS metrics; win_util::GetNonClientMetrics(&metrics); if (adjust_font_callback) adjust_font_callback(&metrics.lfMessageFont); metrics.lfMessageFont.lfHeight = AdjustFontSize(metrics.lfMessageFont.lfHeight, 0); HFONT font = CreateFontIndirect(&metrics.lfMessageFont); DLOG_ASSERT(font); base_font_ref_ = Font::CreateHFontRef(font); // base_font_ref_ is global, up the ref count so it's never deleted. base_font_ref_->AddRef(); } return base_font_ref_; } const std::wstring& Font::FontName() const { return font_ref_->font_name(); } int Font::FontSize() { LOGFONT font_info; GetObject(hfont(), sizeof(LOGFONT), &font_info); long lf_height = font_info.lfHeight; HDC hdc = GetDC(NULL); int device_caps = GetDeviceCaps(hdc, LOGPIXELSY); int font_size = 0; if (device_caps != 0) { float font_size_float = -static_cast<float>(lf_height)*72/device_caps; font_size = static_cast<int>(::ceil(font_size_float - 0.5)); } ReleaseDC(NULL, hdc); return font_size; } Font::HFontRef::HFontRef(HFONT hfont, int height, int baseline, int ave_char_width, int style, int dlu_base_x) : hfont_(hfont), height_(height), baseline_(baseline), ave_char_width_(ave_char_width), style_(style), dlu_base_x_(dlu_base_x) { DLOG_ASSERT(hfont); LOGFONT font_info; GetObject(hfont_, sizeof(LOGFONT), &font_info); font_name_ = std::wstring(font_info.lfFaceName); } Font::HFontRef::~HFontRef() { DeleteObject(hfont_); } Font Font::DeriveFont(int size_delta, int style) const { LOGFONT font_info; GetObject(hfont(), sizeof(LOGFONT), &font_info); font_info.lfHeight = AdjustFontSize(font_info.lfHeight, size_delta); font_info.lfUnderline = ((style & UNDERLINED) == UNDERLINED); font_info.lfItalic = ((style & ITALIC) == ITALIC); font_info.lfWeight = (style & BOLD) ? FW_BOLD : FW_NORMAL; HFONT hfont = CreateFontIndirect(&font_info); return Font(CreateHFontRef(hfont)); } int Font::GetStringWidth(const std::wstring& text) const { int width = 0; HDC dc = GetDC(NULL); HFONT previous_font = static_cast<HFONT>(SelectObject(dc, hfont())); SIZE size; if (GetTextExtentPoint32(dc, text.c_str(), static_cast<int>(text.size()), &size)) { width = size.cx; } else { width = 0; } SelectObject(dc, previous_font); ReleaseDC(NULL, dc); return width; } Font::HFontRef* Font::CreateHFontRef(HFONT font) { TEXTMETRIC font_metrics; HDC screen_dc = GetDC(NULL); HFONT previous_font = static_cast<HFONT>(SelectObject(screen_dc, font)); int last_map_mode = SetMapMode(screen_dc, MM_TEXT); GetTextMetrics(screen_dc, &font_metrics); // Yes, this is how Microsoft recommends calculating the dialog unit // conversions. SIZE ave_text_size; GetTextExtentPoint32(screen_dc, L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 52, &ave_text_size); const int dlu_base_x = (ave_text_size.cx / 26 + 1) / 2; // To avoid the DC referencing font_handle_, select the previous font. SelectObject(screen_dc, previous_font); SetMapMode(screen_dc, last_map_mode); ReleaseDC(NULL, screen_dc); const int height = std::max(1, static_cast<int>(font_metrics.tmHeight)); const int baseline = std::max(1, static_cast<int>(font_metrics.tmAscent)); const int ave_char_width = std::max(1, static_cast<int>(font_metrics.tmAveCharWidth)); int style = 0; if (font_metrics.tmItalic) { style |= Font::ITALIC; } if (font_metrics.tmUnderlined) { style |= Font::UNDERLINED; } if (font_metrics.tmWeight >= kTextMetricWeightBold) { style |= Font::BOLD; } return new HFontRef(font, height, baseline, ave_char_width, style, dlu_base_x); } } // namespace gfx
Revert Win specific elements of 46492 to look for perf impact
Revert Win specific elements of 46492 to look for perf impact There was a regression in the moz page cycler around when landed. This was ONLY a single core regression, which suggests it was time spent in the browser becoming critical path. This change involved font layout in the browser, and so it MIGHT be related. I'll land this, let the per bots start their run, and then revert. TBR=pkasting Review URL: http://codereview.chromium.org/2895017 git-svn-id: http://src.chromium.org/svn/trunk/src@52441 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: ad4edddcba892764ef75ad5c21b7a6f8c2f8b827
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
3cd4fcb03d1737554d35eeeff9bbb81000ab4646
gfx_es2/fbo.cpp
gfx_es2/fbo.cpp
#include <string.h> #include "base/logging.h" #include "gfx/gl_common.h" #include "gfx_es2/fbo.h" #include "gfx/gl_common.h" #include "gfx_es2/gl_state.h" #if defined(USING_GLES2) && !defined(BLACKBERRY) #ifndef GL_READ_FRAMEBUFFER // Careful - our ES3 header defines these. Means that we must make sure // to only use them if ES3 support is detected to be available and otherwise // use GL_FRAMEBUFFER only. #define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER #define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER #endif #ifndef GL_DEPTH_COMPONENT24 #define GL_DEPTH_COMPONENT24 GL_DEPTH_COMPONENT24_OES #endif #ifndef GL_DEPTH24_STENCIL8_OES #define GL_DEPTH24_STENCIL8_OES 0x88F0 #endif #endif #ifdef IOS extern void bindDefaultFBO(); #endif struct FBO { GLuint handle; GLuint color_texture; GLuint z_stencil_buffer; // Either this is set, or the two below. GLuint z_buffer; GLuint stencil_buffer; int width; int height; FBOColorDepth colorDepth; }; // On PC, we always use GL_DEPTH24_STENCIL8. // On Android, we try to use what's available. #ifndef USING_GLES2 FBO *fbo_ext_create(int width, int height, int num_color_textures, bool z_stencil, FBOColorDepth colorDepth) { FBO *fbo = new FBO(); fbo->width = width; fbo->height = height; fbo->colorDepth = colorDepth; // Color texture is same everywhere glGenFramebuffersEXT(1, &fbo->handle); glGenTextures(1, &fbo->color_texture); // Create the surfaces. glBindTexture(GL_TEXTURE_2D, fbo->color_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // TODO: We could opt to only create 16-bit render targets on slow devices. For later. switch (colorDepth) { case FBO_8888: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); break; case FBO_4444: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, NULL); break; case FBO_5551: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, NULL); break; case FBO_565: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL); break; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); fbo->stencil_buffer = 0; fbo->z_buffer = 0; // 24-bit Z, 8-bit stencil glGenRenderbuffersEXT(1, &fbo->z_stencil_buffer); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, fbo->z_stencil_buffer); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_STENCIL_EXT, width, height); //glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH24_STENCIL8, width, height); // Bind it all together glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, fbo->z_stencil_buffer); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, fbo->z_stencil_buffer); GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); switch(status) { case GL_FRAMEBUFFER_COMPLETE_EXT: // ILOG("Framebuffer verified complete."); break; case GL_FRAMEBUFFER_UNSUPPORTED_EXT: ELOG("GL_FRAMEBUFFER_UNSUPPORTED"); break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT: ELOG("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT "); break; default: FLOG("Other framebuffer error: %i", status); break; } // Unbind state we don't need glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0); glBindTexture(GL_TEXTURE_2D, 0); return fbo; } #endif FBO *fbo_create(int width, int height, int num_color_textures, bool z_stencil, FBOColorDepth colorDepth) { CheckGLExtensions(); #ifndef USING_GLES2 if(!gl_extensions.FBO_ARB) return fbo_ext_create(width, height, num_color_textures, z_stencil, colorDepth); #endif FBO *fbo = new FBO(); fbo->width = width; fbo->height = height; fbo->colorDepth = colorDepth; // Color texture is same everywhere glGenFramebuffers(1, &fbo->handle); glGenTextures(1, &fbo->color_texture); // Create the surfaces. glBindTexture(GL_TEXTURE_2D, fbo->color_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // TODO: We could opt to only create 16-bit render targets on slow devices. For later. switch (colorDepth) { case FBO_8888: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); break; case FBO_4444: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, NULL); break; case FBO_5551: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, NULL); break; case FBO_565: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL); break; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); #ifdef USING_GLES2 if (gl_extensions.OES_packed_depth_stencil) { ILOG("Creating %i x %i FBO using DEPTH24_STENCIL8", width, height); // Standard method fbo->stencil_buffer = 0; fbo->z_buffer = 0; // 24-bit Z, 8-bit stencil combined glGenRenderbuffers(1, &fbo->z_stencil_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_stencil_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, width, height); // Bind it all together glBindFramebuffer(GL_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); } else { ILOG("Creating %i x %i FBO using separate stencil", width, height); // TEGRA fbo->z_stencil_buffer = 0; // 16/24-bit Z, separate 8-bit stencil glGenRenderbuffers(1, &fbo->z_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_buffer); glRenderbufferStorage(GL_RENDERBUFFER, gl_extensions.OES_depth24 ? GL_DEPTH_COMPONENT24 : GL_DEPTH_COMPONENT16, width, height); // 8-bit stencil buffer glGenRenderbuffers(1, &fbo->stencil_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->stencil_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, width, height); // Bind it all together glBindFramebuffer(GL_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_buffer); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->stencil_buffer); } #else fbo->stencil_buffer = 0; fbo->z_buffer = 0; // 24-bit Z, 8-bit stencil glGenRenderbuffers(1, &fbo->z_stencil_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_stencil_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); // Bind it all together glBindFramebuffer(GL_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); #endif GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); switch(status) { case GL_FRAMEBUFFER_COMPLETE: // ILOG("Framebuffer verified complete."); break; case GL_FRAMEBUFFER_UNSUPPORTED: ELOG("GL_FRAMEBUFFER_UNSUPPORTED"); break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: ELOG("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT "); break; default: FLOG("Other framebuffer error: %i", status); break; } // Unbind state we don't need glBindRenderbuffer(GL_RENDERBUFFER, 0); glBindTexture(GL_TEXTURE_2D, 0); return fbo; } void fbo_unbind() { CheckGLExtensions(); if (gl_extensions.FBO_ARB) { glBindFramebuffer(GL_FRAMEBUFFER, 0); } else { #ifndef USING_GLES2 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); #endif } #ifdef IOS bindDefaultFBO(); #endif } void fbo_bind_as_render_target(FBO *fbo) { if (gl_extensions.FBO_ARB) { if (gl_extensions.GLES3) { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); } else { // This will collide with bind_for_read - but there's nothing in ES 2.0 // that actually separate them anyway of course, so doesn't matter. glBindFramebuffer(GL_FRAMEBUFFER, fbo->handle); } }else{ #ifndef USING_GLES2 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle); #endif } } void fbo_bind_for_read(FBO *fbo) { if (gl_extensions.FBO_ARB) { if (gl_extensions.GLES3) { glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo->handle); } else { // This will collide with bind_as_render_target - but there's nothing in ES 2.0 // that actually separate them anyway of course, so doesn't matter. glBindFramebuffer(GL_FRAMEBUFFER, fbo->handle); } } else { #ifndef USING_GLES2 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle); #endif } } void fbo_bind_color_as_texture(FBO *fbo, int color) { if (fbo) { glBindTexture(GL_TEXTURE_2D, fbo->color_texture); } } void fbo_destroy(FBO *fbo) { if (gl_extensions.FBO_ARB) { glBindFramebuffer(GL_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); glDeleteFramebuffers(1, &fbo->handle); glDeleteRenderbuffers(1, &fbo->z_stencil_buffer); } else { #ifndef USING_GLES2 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER_EXT, 0); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); glDeleteFramebuffersEXT(1, &fbo->handle); glDeleteRenderbuffersEXT(1, &fbo->z_stencil_buffer); #endif } glDeleteTextures(1, &fbo->color_texture); delete fbo; } void fbo_get_dimensions(FBO *fbo, int *w, int *h) { *w = fbo->width; *h = fbo->height; } int fbo_get_color_texture(FBO *fbo) { return fbo->color_texture; }
#include <string.h> #include "base/logging.h" #include "gfx/gl_common.h" #include "gfx_es2/fbo.h" #include "gfx/gl_common.h" #include "gfx_es2/gl_state.h" #if defined(USING_GLES2) && !defined(BLACKBERRY) #ifndef GL_READ_FRAMEBUFFER // Careful - our ES3 header defines these. Means that we must make sure // to only use them if ES3 support is detected to be available and otherwise // use GL_FRAMEBUFFER only. #define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER #define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER #endif #ifndef GL_DEPTH_COMPONENT24 #define GL_DEPTH_COMPONENT24 GL_DEPTH_COMPONENT24_OES #endif #ifndef GL_DEPTH24_STENCIL8_OES #define GL_DEPTH24_STENCIL8_OES 0x88F0 #endif #endif #ifdef IOS extern void bindDefaultFBO(); #endif struct FBO { GLuint handle; GLuint color_texture; GLuint z_stencil_buffer; // Either this is set, or the two below. GLuint z_buffer; GLuint stencil_buffer; int width; int height; FBOColorDepth colorDepth; }; // On PC, we always use GL_DEPTH24_STENCIL8. // On Android, we try to use what's available. #ifndef USING_GLES2 FBO *fbo_ext_create(int width, int height, int num_color_textures, bool z_stencil, FBOColorDepth colorDepth) { FBO *fbo = new FBO(); fbo->width = width; fbo->height = height; fbo->colorDepth = colorDepth; // Color texture is same everywhere glGenFramebuffersEXT(1, &fbo->handle); glGenTextures(1, &fbo->color_texture); // Create the surfaces. glBindTexture(GL_TEXTURE_2D, fbo->color_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // TODO: We could opt to only create 16-bit render targets on slow devices. For later. switch (colorDepth) { case FBO_8888: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); break; case FBO_4444: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, NULL); break; case FBO_5551: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, NULL); break; case FBO_565: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL); break; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); fbo->stencil_buffer = 0; fbo->z_buffer = 0; // 24-bit Z, 8-bit stencil glGenRenderbuffersEXT(1, &fbo->z_stencil_buffer); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, fbo->z_stencil_buffer); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_STENCIL_EXT, width, height); //glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH24_STENCIL8, width, height); // Bind it all together glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, fbo->z_stencil_buffer); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, fbo->z_stencil_buffer); GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); switch(status) { case GL_FRAMEBUFFER_COMPLETE_EXT: // ILOG("Framebuffer verified complete."); break; case GL_FRAMEBUFFER_UNSUPPORTED_EXT: ELOG("GL_FRAMEBUFFER_UNSUPPORTED"); break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT: ELOG("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT "); break; default: FLOG("Other framebuffer error: %i", status); break; } // Unbind state we don't need glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0); glBindTexture(GL_TEXTURE_2D, 0); return fbo; } #endif FBO *fbo_create(int width, int height, int num_color_textures, bool z_stencil, FBOColorDepth colorDepth) { CheckGLExtensions(); #ifndef USING_GLES2 if(!gl_extensions.FBO_ARB) return fbo_ext_create(width, height, num_color_textures, z_stencil, colorDepth); #endif FBO *fbo = new FBO(); fbo->width = width; fbo->height = height; fbo->colorDepth = colorDepth; // Color texture is same everywhere glGenFramebuffers(1, &fbo->handle); glGenTextures(1, &fbo->color_texture); // Create the surfaces. glBindTexture(GL_TEXTURE_2D, fbo->color_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // TODO: We could opt to only create 16-bit render targets on slow devices. For later. switch (colorDepth) { case FBO_8888: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); break; case FBO_4444: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, NULL); break; case FBO_5551: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, NULL); break; case FBO_565: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL); break; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); #ifdef USING_GLES2 if (gl_extensions.OES_packed_depth_stencil) { ILOG("Creating %i x %i FBO using DEPTH24_STENCIL8", width, height); // Standard method fbo->stencil_buffer = 0; fbo->z_buffer = 0; // 24-bit Z, 8-bit stencil combined glGenRenderbuffers(1, &fbo->z_stencil_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_stencil_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, width, height); // Bind it all together glBindFramebuffer(GL_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); } else { ILOG("Creating %i x %i FBO using separate stencil", width, height); // TEGRA fbo->z_stencil_buffer = 0; // 16/24-bit Z, separate 8-bit stencil glGenRenderbuffers(1, &fbo->z_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_buffer); glRenderbufferStorage(GL_RENDERBUFFER, gl_extensions.OES_depth24 ? GL_DEPTH_COMPONENT24 : GL_DEPTH_COMPONENT16, width, height); // 8-bit stencil buffer glGenRenderbuffers(1, &fbo->stencil_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->stencil_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, width, height); // Bind it all together glBindFramebuffer(GL_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_buffer); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->stencil_buffer); } #else fbo->stencil_buffer = 0; fbo->z_buffer = 0; // 24-bit Z, 8-bit stencil glGenRenderbuffers(1, &fbo->z_stencil_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_stencil_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); // Bind it all together glBindFramebuffer(GL_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); #endif GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); switch(status) { case GL_FRAMEBUFFER_COMPLETE: // ILOG("Framebuffer verified complete."); break; case GL_FRAMEBUFFER_UNSUPPORTED: ELOG("GL_FRAMEBUFFER_UNSUPPORTED"); break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: ELOG("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT "); break; default: FLOG("Other framebuffer error: %i", status); break; } // Unbind state we don't need glBindRenderbuffer(GL_RENDERBUFFER, 0); glBindTexture(GL_TEXTURE_2D, 0); return fbo; } void fbo_unbind() { CheckGLExtensions(); if (gl_extensions.FBO_ARB) { glBindFramebuffer(GL_FRAMEBUFFER, 0); } else { #ifndef USING_GLES2 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); #endif } #ifdef IOS bindDefaultFBO(); #endif } void fbo_bind_as_render_target(FBO *fbo) { if (gl_extensions.FBO_ARB) { if (gl_extensions.GLES3) { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); } else { // This will collide with bind_for_read - but there's nothing in ES 2.0 // that actually separate them anyway of course, so doesn't matter. glBindFramebuffer(GL_FRAMEBUFFER, fbo->handle); } }else{ #ifndef USING_GLES2 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle); #endif } } void fbo_bind_for_read(FBO *fbo) { if (gl_extensions.FBO_ARB) { if (gl_extensions.GLES3) { glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo->handle); } else { // This will collide with bind_as_render_target - but there's nothing in ES 2.0 // that actually separate them anyway of course, so doesn't matter. glBindFramebuffer(GL_FRAMEBUFFER, fbo->handle); } } else { #ifndef USING_GLES2 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle); #endif } } void fbo_bind_color_as_texture(FBO *fbo, int color) { if (fbo) { glBindTexture(GL_TEXTURE_2D, fbo->color_texture); } } void fbo_destroy(FBO *fbo) { if (gl_extensions.FBO_ARB) { glBindFramebuffer(GL_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); glDeleteFramebuffers(1, &fbo->handle); glDeleteRenderbuffers(1, &fbo->z_stencil_buffer); } else { #ifndef USING_GLES2 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->handle); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER_EXT, 0); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); glDeleteFramebuffersEXT(1, &fbo->handle); glDeleteRenderbuffersEXT(1, &fbo->z_stencil_buffer); #endif } glDeleteTextures(1, &fbo->color_texture); delete fbo; } void fbo_get_dimensions(FBO *fbo, int *w, int *h) { *w = fbo->width; *h = fbo->height; } int fbo_get_color_texture(FBO *fbo) { return fbo->color_texture; } int fbo_get_depth_buffer(FBO *fbo) { return fbo->z_buffer; } int fbo_get_stencil_buffer(FBO *fbo) { return fbo->stencil_buffer; }
Add fbo_get_depth_buffer & fbo_get_stencil_buffer
Add fbo_get_depth_buffer & fbo_get_stencil_buffer
C++
mit
hrydgard/native,hrydgard/native,libretro/ppsspp-native,libretro/ppsspp-native,libretro/ppsspp-native,unknownbrackets/native,zhykzhykzhyk/ppsspp-native,hrydgard/native,zhykzhykzhyk/ppsspp-native,zhykzhykzhyk/ppsspp-native,libretro/ppsspp-native,unknownbrackets/native,zhykzhykzhyk/ppsspp-native,unknownbrackets/native,hrydgard/native,unknownbrackets/native
d2a72c45bb125271df1e68aa66bdf6bc77a2ce96
src/abort_message.cpp
src/abort_message.cpp
//===------------------------- abort_message.cpp --------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include "abort_message.h" #ifdef __BIONIC__ #include <android/set_abort_message.h> #include <syslog.h> #endif #pragma GCC visibility push(hidden) #if __APPLE__ # if defined(__has_include) && __has_include(<CrashReporterClient.h>) # define HAVE_CRASHREPORTERCLIENT_H 1 # include <CrashReporterClient.h> # endif #endif __attribute__((visibility("hidden"), noreturn)) void abort_message(const char* format, ...) { // write message to stderr #if __APPLE__ fprintf(stderr, "libc++abi.dylib: "); #endif va_list list; va_start(list, format); vfprintf(stderr, format, list); va_end(list); fprintf(stderr, "\n"); #if __APPLE__ && HAVE_CRASHREPORTERCLIENT_H // record message in crash report char* buffer; va_list list2; va_start(list2, format); vasprintf(&buffer, format, list2); va_end(list2); CRSetCrashLogMessage(buffer); #elif __BIONIC__ char* buffer; va_list list2; va_start(list2, format); vasprintf(&buffer, format, list2); va_end(list2); // Show error in tombstone. android_set_abort_message(buffer); // Show error in logcat. openlog("libc++abi", 0, 0); syslog(LOG_CRIT, "%s", buffer); closelog(); #endif abort(); } #pragma GCC visibility pop
//===------------------------- abort_message.cpp --------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include "abort_message.h" #ifdef __BIONIC__ #include <android/api-level.h> #if __ANDROID_API__ >= 21 #include <syslog.h> extern "C" void android_set_abort_message(const char* msg); #else #include <assert.h> #endif // __ANDROID_API__ >= 21 #endif // __BIONIC__ #pragma GCC visibility push(hidden) #if __APPLE__ # if defined(__has_include) && __has_include(<CrashReporterClient.h>) # define HAVE_CRASHREPORTERCLIENT_H 1 # include <CrashReporterClient.h> # endif #endif __attribute__((visibility("hidden"), noreturn)) void abort_message(const char* format, ...) { // write message to stderr #if __APPLE__ fprintf(stderr, "libc++abi.dylib: "); #endif va_list list; va_start(list, format); vfprintf(stderr, format, list); va_end(list); fprintf(stderr, "\n"); #if __APPLE__ && HAVE_CRASHREPORTERCLIENT_H // record message in crash report char* buffer; va_list list2; va_start(list2, format); vasprintf(&buffer, format, list2); va_end(list2); CRSetCrashLogMessage(buffer); #elif __BIONIC__ char* buffer; va_list list2; va_start(list2, format); vasprintf(&buffer, format, list2); va_end(list2); #if __ANDROID_API__ >= 21 // Show error in tombstone. android_set_abort_message(buffer); // Show error in logcat. openlog("libc++abi", 0, 0); syslog(LOG_CRIT, "%s", buffer); closelog(); #else // The good error reporting wasn't available in Android until L. Since we're // about to abort anyway, just call __assert2, which will log _somewhere_ // (tombstone and/or logcat) in older releases. __assert2(__FILE__, __LINE__, __func__, buffer); #endif // __ANDROID_API__ >= 21 #endif // __BIONIC__ abort(); } #pragma GCC visibility pop
Fix abort_message.cpp for the NDK.
Fix abort_message.cpp for the NDK. The NDK doesn't have access to `android/set_abort_message.h`, so use an extern declaration instead for API 21. For older releases, just use `__assert2`, which will report to logcat and/or the tombstone for some older releases. git-svn-id: 6a9f6578bdee8d959f0ed58970538b4ab6004734@226310 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/libcxxabi,llvm-mirror/libcxxabi,llvm-mirror/libcxxabi,llvm-mirror/libcxxabi,llvm-mirror/libcxxabi
1e26954a78bcec693b93193e54aee5cb895b6b97
test/datum.cc
test/datum.cc
#include "test.h" #include "field.h" #include "datum.h" void test_datum_serialize_string ( ) { Datum datum; Container container = Container(); container.t_string = "test"; datum = Datum(container, "foo", CDB_STRING); check(datum.container.t_string == "test", "the value is correct"); check(datum.type == CDB_STRING, "the type is correct"); string serialized = datum.serialize(); check(serialized == "1:foo:test\n", "the field is serialized correctly"); Datum datum2; datum2.deserialize(serialized); check(datum2.type == CDB_STRING, "the unserialized type is correct"); check(datum2.container.t_string == "test", "the unserialized value is correct"); } void test_datum_serialize_int8 ( ) { Datum datum; Container container = Container(); container.t_8 = 32; datum = Datum(container, "foo", CDB_INT8); check(datum.container.t_8 == 32, "the value is correct"); check(datum.type == CDB_INT8, "the type is correct"); string serialized = datum.serialize(); check(serialized == "2:foo:32\n", "the field is serialized correctly"); Datum datum2; datum2.deserialize(serialized); check(datum2.type == CDB_INT8, "the unserialized type is correct"); check(datum2.container.t_8 == 32, "the unserialized value is correct"); } void test_datum_serialize_int16 ( ) { Datum datum; Container container = Container(); container.t_16 = 32; datum = Datum(container, "foo", CDB_INT16); check(datum.container.t_16 == 32, "the value is correct"); check(datum.type == CDB_INT16, "the type is correct"); string serialized = datum.serialize(); check(serialized == "3:foo:32\n", "the field is serialized correctly"); Datum datum2; datum2.deserialize(serialized); check(datum2.type == CDB_INT16, "the unserialized type is correct"); check(datum2.container.t_16 == 32, "the unserialized value is correct"); } void test_datum_serialize_int32 ( ) { Datum datum; Container container = Container(); container.t_32 = 32; datum = Datum(container, "foo", CDB_INT32); check(datum.container.t_32 == 32, "the value is correct"); check(datum.type == CDB_INT32, "the type is correct"); string serialized = datum.serialize(); check(serialized == "4:foo:32\n", "the field is serialized and unserialized correctly"); Datum datum2; datum2.deserialize(serialized); check(datum2.type == CDB_INT32, "the unserialized type is correct"); check(datum2.container.t_32 == 32, "the unserialized value is correct"); } void test_datum_serialize_double ( ) { Datum datum; Container container = Container(); container.t_double = 3.14159; datum = Datum(container, "foo", CDB_DOUBLE); check(datum.container.t_double == 3.14159, "the value is correct"); check(datum.type == CDB_DOUBLE, "the type is correct"); string serialized = datum.serialize(); check(serialized.substr(0, 13) == "5:foo:3.14159", "the field is serialized and unserialized correctly"); Datum datum2; datum2.deserialize(serialized); check(datum2.type == CDB_DOUBLE, "the unserialized type is correct"); check(datum2.container.t_double == 3.14159, "the unserialized value is correct"); } void test_datum_deserialize_constructor ( ) { Datum datum("4:foo:32\n"); check(datum.type == CDB_INT32, "the unserialized type is correct"); check(datum.container.t_32 == 32, "the unserialized value is correct"); } void test_datum_deserialize_not_ok ( ) { Datum datum; datum.deserialize("foo:bar"); check(datum.is_ok() == false, "incorrectly deserialized type sets is_ok() to false"); } int test_datum ( ) { test_datum_serialize_string(); test_datum_serialize_int8(); test_datum_serialize_int16(); test_datum_serialize_int32(); test_datum_serialize_double(); test_datum_deserialize_constructor(); test_datum_deserialize_not_ok(); done(); }
#include "test.h" #include "field.h" #include "datum.h" void test_datum_serialize_string ( ) { Datum datum; Container container = Container(); container.t_string = "test"; datum = Datum(container, "foo", CDB_STRING); check(datum.container.t_string == "test", "the value is correct"); check(datum.type == CDB_STRING, "the type is correct"); string serialized = datum.serialize(); check(serialized == "1:foo:test\n", "the field is serialized correctly"); Datum datum2; datum2.deserialize(serialized); check(datum2.type == CDB_STRING, "the unserialized type is correct"); check(datum2.container.t_string == "test", "the unserialized value is correct"); } void test_datum_serialize_int8 ( ) { Datum datum; Container container = Container(); container.t_8 = 32; datum = Datum(container, "foo", CDB_INT8); check(datum.container.t_8 == 32, "the value is correct"); check(datum.type == CDB_INT8, "the type is correct"); string serialized = datum.serialize(); check(serialized == "2:foo:32\n", "the field is serialized correctly"); Datum datum2; datum2.deserialize(serialized); check(datum2.type == CDB_INT8, "the unserialized type is correct"); check(datum2.container.t_8 == 32, "the unserialized value is correct"); } void test_datum_serialize_int16 ( ) { Datum datum; Container container = Container(); container.t_16 = 32; datum = Datum(container, "foo", CDB_INT16); check(datum.container.t_16 == 32, "the value is correct"); check(datum.type == CDB_INT16, "the type is correct"); string serialized = datum.serialize(); check(serialized == "3:foo:32\n", "the field is serialized correctly"); Datum datum2; datum2.deserialize(serialized); check(datum2.type == CDB_INT16, "the unserialized type is correct"); check(datum2.container.t_16 == 32, "the unserialized value is correct"); } void test_datum_serialize_int32 ( ) { Datum datum; Container container = Container(); container.t_32 = 32; datum = Datum(container, "foo", CDB_INT32); check(datum.container.t_32 == 32, "the value is correct"); check(datum.type == CDB_INT32, "the type is correct"); string serialized = datum.serialize(); check(serialized == "4:foo:32\n", "the field is serialized and unserialized correctly"); Datum datum2; datum2.deserialize(serialized); check(datum2.type == CDB_INT32, "the unserialized type is correct"); check(datum2.container.t_32 == 32, "the unserialized value is correct"); } void test_datum_serialize_double ( ) { Datum datum; Container container = Container(); container.t_double = 3.14159; datum = Datum(container, "foo", CDB_DOUBLE); check(datum.container.t_double == 3.14159, "the value is correct"); check(datum.type == CDB_DOUBLE, "the type is correct"); string serialized = datum.serialize(); check(serialized.substr(0, 13) == "5:foo:3.14159", "the field is serialized and unserialized correctly"); Datum datum2; datum2.deserialize(serialized); check(datum2.type == CDB_DOUBLE, "the unserialized type is correct"); check(datum2.container.t_double == 3.14159, "the unserialized value is correct"); } void test_datum_deserialize_constructor ( ) { Datum datum("4:foo:32\n"); check(datum.type == CDB_INT32, "the unserialized type is correct"); check(datum.container.t_32 == 32, "the unserialized value is correct"); } void test_datum_deserialize_not_ok ( ) { Datum datum; datum.deserialize("foo:bar"); check(datum.is_ok() == false, "incorrectly deserialized type sets is_ok() to false"); } void test_datum_deserialize_zero ( ) { Datum datum("0:foo:32\n"); check(datum.is_ok() == false, "a zero serialization is not ok"); } int test_datum ( ) { test_datum_serialize_string(); test_datum_serialize_int8(); test_datum_serialize_int16(); test_datum_serialize_int32(); test_datum_serialize_double(); test_datum_deserialize_constructor(); test_datum_deserialize_not_ok(); test_datum_deserialize_zero(); done(); }
add additional test
add additional test
C++
mit
JerrySievert/cdb,JerrySievert/cdb
05007312a74c82bfe812bf6777e763590e3bbd77
packages/grpc-native-core/ext/server_credentials.cc
packages/grpc-native-core/ext/server_credentials.cc
/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <vector> #include <nan.h> #include <node.h> #include "grpc/grpc.h" #include "grpc/grpc_security.h" #include "grpc/support/log.h" #include "server_credentials.h" #include "util.h" namespace grpc { namespace node { using Nan::Callback; using Nan::EscapableHandleScope; using Nan::HandleScope; using Nan::Maybe; using Nan::MaybeLocal; using Nan::ObjectWrap; using Nan::Persistent; using Nan::Utf8String; using v8::Array; using v8::Exception; using v8::External; using v8::Function; using v8::FunctionTemplate; using v8::Integer; using v8::Local; using v8::Object; using v8::ObjectTemplate; using v8::String; using v8::Value; Nan::Callback *ServerCredentials::constructor; Persistent<FunctionTemplate> ServerCredentials::fun_tpl; ServerCredentials::ServerCredentials(grpc_server_credentials *credentials) : wrapped_credentials(credentials) {} ServerCredentials::~ServerCredentials() { grpc_server_credentials_release(wrapped_credentials); } void ServerCredentials::Init(Local<Object> exports) { Nan::HandleScope scope; Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New); tpl->SetClassName(Nan::New("ServerCredentials").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Local<Function> ctr = tpl->GetFunction(); Nan::Set( ctr, Nan::New("createSsl").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(CreateSsl)).ToLocalChecked()); Nan::Set(ctr, Nan::New("createInsecure").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(CreateInsecure)) .ToLocalChecked()); fun_tpl.Reset(tpl); constructor = new Nan::Callback(ctr); Nan::Set(exports, Nan::New("ServerCredentials").ToLocalChecked(), ctr); } bool ServerCredentials::HasInstance(Local<Value> val) { Nan::HandleScope scope; return Nan::New(fun_tpl)->HasInstance(val); } Local<Value> ServerCredentials::WrapStruct( grpc_server_credentials *credentials) { Nan::EscapableHandleScope scope; const int argc = 1; Local<Value> argv[argc] = { Nan::New<External>(reinterpret_cast<void *>(credentials))}; MaybeLocal<Object> maybe_instance = Nan::NewInstance(constructor->GetFunction(), argc, argv); if (maybe_instance.IsEmpty()) { return scope.Escape(Nan::Null()); } else { return scope.Escape(maybe_instance.ToLocalChecked()); } } grpc_server_credentials *ServerCredentials::GetWrappedServerCredentials() { return wrapped_credentials; } NAN_METHOD(ServerCredentials::New) { if (info.IsConstructCall()) { if (!info[0]->IsExternal()) { return Nan::ThrowTypeError( "ServerCredentials can only be created with the provided functions"); } Local<External> ext = info[0].As<External>(); grpc_server_credentials *creds_value = reinterpret_cast<grpc_server_credentials *>(ext->Value()); ServerCredentials *credentials = new ServerCredentials(creds_value); credentials->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } else { // This should never be called directly return Nan::ThrowTypeError( "ServerCredentials can only be created with the provided functions"); } } NAN_METHOD(ServerCredentials::CreateSsl) { Nan::HandleScope scope; StringOrNull root_certs; if (::node::Buffer::HasInstance(info[0])) { root_certs.assign(info[0]); } else if (!(info[0]->IsNull() || info[0]->IsUndefined())) { return Nan::ThrowTypeError( "createSSl's first argument must be a Buffer if provided"); } if (!info[1]->IsArray()) { return Nan::ThrowTypeError( "createSsl's second argument must be a list of objects"); } // Default to not requesting the client certificate grpc_ssl_client_certificate_request_type client_certificate_request = GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE; if (info[2]->IsBoolean()) { client_certificate_request = Nan::To<bool>(info[2]).FromJust() ? GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY : GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE; } else if (!(info[2]->IsUndefined() || info[2]->IsNull())) { return Nan::ThrowTypeError( "createSsl's third argument must be a boolean if provided"); } Local<Array> pair_list = Local<Array>::Cast(info[1]); uint32_t key_cert_pair_count = pair_list->Length(); grpc_ssl_pem_key_cert_pair key_cert_pairs[key_cert_pair_count]; std::vector<StringOrNull> key_strings(key_cert_pair_count); std::vector<StringOrNull> cert_strings(key_cert_pair_count); Local<String> key_key = Nan::New("private_key").ToLocalChecked(); Local<String> cert_key = Nan::New("cert_chain").ToLocalChecked(); for (uint32_t i = 0; i < key_cert_pair_count; i++) { Local<Value> pair_val = Nan::Get(pair_list, i).ToLocalChecked(); if (!pair_val->IsObject()) { return Nan::ThrowTypeError("Key/cert pairs must be objects"); } Local<Object> pair_obj = Nan::To<Object>(pair_val).ToLocalChecked(); Local<Value> maybe_key = Nan::Get(pair_obj, key_key).ToLocalChecked(); Local<Value> maybe_cert = Nan::Get(pair_obj, cert_key).ToLocalChecked(); if (!::node::Buffer::HasInstance(maybe_key)) { return Nan::ThrowTypeError("private_key must be a Buffer"); } if (!::node::Buffer::HasInstance(maybe_cert)) { return Nan::ThrowTypeError("cert_chain must be a Buffer"); } key_strings[i].assign(maybe_key); cert_strings[i].assign(maybe_cert); key_cert_pairs[i].private_key = key_strings[i].get(); key_cert_pairs[i].cert_chain = cert_strings[i].get(); } grpc_server_credentials *creds = grpc_ssl_server_credentials_create_ex( root_certs.get(), key_cert_pairs, key_cert_pair_count, client_certificate_request, NULL); if (creds == NULL) { info.GetReturnValue().SetNull(); } else { info.GetReturnValue().Set(WrapStruct(creds)); } } NAN_METHOD(ServerCredentials::CreateInsecure) { info.GetReturnValue().Set(WrapStruct(NULL)); } } // namespace node } // namespace grpc
/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <vector> #include <nan.h> #include <node.h> #include "grpc/grpc.h" #include "grpc/grpc_security.h" #include "grpc/support/log.h" #include "server_credentials.h" #include "util.h" namespace grpc { namespace node { using Nan::Callback; using Nan::EscapableHandleScope; using Nan::HandleScope; using Nan::Maybe; using Nan::MaybeLocal; using Nan::ObjectWrap; using Nan::Persistent; using Nan::Utf8String; using v8::Array; using v8::Exception; using v8::External; using v8::Function; using v8::FunctionTemplate; using v8::Integer; using v8::Local; using v8::Object; using v8::ObjectTemplate; using v8::String; using v8::Value; Nan::Callback *ServerCredentials::constructor; Persistent<FunctionTemplate> ServerCredentials::fun_tpl; ServerCredentials::ServerCredentials(grpc_server_credentials *credentials) : wrapped_credentials(credentials) {} ServerCredentials::~ServerCredentials() { grpc_server_credentials_release(wrapped_credentials); } void ServerCredentials::Init(Local<Object> exports) { Nan::HandleScope scope; Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New); tpl->SetClassName(Nan::New("ServerCredentials").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Local<Function> ctr = tpl->GetFunction(); Nan::Set( ctr, Nan::New("createSsl").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(CreateSsl)).ToLocalChecked()); Nan::Set(ctr, Nan::New("createInsecure").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(CreateInsecure)) .ToLocalChecked()); fun_tpl.Reset(tpl); constructor = new Nan::Callback(ctr); Nan::Set(exports, Nan::New("ServerCredentials").ToLocalChecked(), ctr); } bool ServerCredentials::HasInstance(Local<Value> val) { Nan::HandleScope scope; return Nan::New(fun_tpl)->HasInstance(val); } Local<Value> ServerCredentials::WrapStruct( grpc_server_credentials *credentials) { Nan::EscapableHandleScope scope; const int argc = 1; Local<Value> argv[argc] = { Nan::New<External>(reinterpret_cast<void *>(credentials))}; MaybeLocal<Object> maybe_instance = Nan::NewInstance(constructor->GetFunction(), argc, argv); if (maybe_instance.IsEmpty()) { return scope.Escape(Nan::Null()); } else { return scope.Escape(maybe_instance.ToLocalChecked()); } } grpc_server_credentials *ServerCredentials::GetWrappedServerCredentials() { return wrapped_credentials; } NAN_METHOD(ServerCredentials::New) { if (info.IsConstructCall()) { if (!info[0]->IsExternal()) { return Nan::ThrowTypeError( "ServerCredentials can only be created with the provided functions"); } Local<External> ext = info[0].As<External>(); grpc_server_credentials *creds_value = reinterpret_cast<grpc_server_credentials *>(ext->Value()); ServerCredentials *credentials = new ServerCredentials(creds_value); credentials->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } else { // This should never be called directly return Nan::ThrowTypeError( "ServerCredentials can only be created with the provided functions"); } } NAN_METHOD(ServerCredentials::CreateSsl) { Nan::HandleScope scope; StringOrNull root_certs; if (::node::Buffer::HasInstance(info[0])) { root_certs.assign(info[0]); } else if (!(info[0]->IsNull() || info[0]->IsUndefined())) { return Nan::ThrowTypeError( "createSSl's first argument must be a Buffer if provided"); } if (!info[1]->IsArray()) { return Nan::ThrowTypeError( "createSsl's second argument must be a list of objects"); } // Default to not requesting the client certificate grpc_ssl_client_certificate_request_type client_certificate_request = GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE; if (info[2]->IsBoolean()) { client_certificate_request = Nan::To<bool>(info[2]).FromJust() ? GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY : GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE; } else if (!(info[2]->IsUndefined() || info[2]->IsNull())) { return Nan::ThrowTypeError( "createSsl's third argument must be a boolean if provided"); } Local<Array> pair_list = Local<Array>::Cast(info[1]); uint32_t key_cert_pair_count = pair_list->Length(); std::vector<grpc_ssl_pem_key_cert_pair> key_cert_pairs(key_cert_pair_count); std::vector<StringOrNull> key_strings(key_cert_pair_count); std::vector<StringOrNull> cert_strings(key_cert_pair_count); Local<String> key_key = Nan::New("private_key").ToLocalChecked(); Local<String> cert_key = Nan::New("cert_chain").ToLocalChecked(); for (uint32_t i = 0; i < key_cert_pair_count; i++) { Local<Value> pair_val = Nan::Get(pair_list, i).ToLocalChecked(); if (!pair_val->IsObject()) { return Nan::ThrowTypeError("Key/cert pairs must be objects"); } Local<Object> pair_obj = Nan::To<Object>(pair_val).ToLocalChecked(); Local<Value> maybe_key = Nan::Get(pair_obj, key_key).ToLocalChecked(); Local<Value> maybe_cert = Nan::Get(pair_obj, cert_key).ToLocalChecked(); if (!::node::Buffer::HasInstance(maybe_key)) { return Nan::ThrowTypeError("private_key must be a Buffer"); } if (!::node::Buffer::HasInstance(maybe_cert)) { return Nan::ThrowTypeError("cert_chain must be a Buffer"); } key_strings[i].assign(maybe_key); cert_strings[i].assign(maybe_cert); key_cert_pairs[i].private_key = key_strings[i].get(); key_cert_pairs[i].cert_chain = cert_strings[i].get(); } grpc_server_credentials *creds = grpc_ssl_server_credentials_create_ex( root_certs.get(), key_cert_pairs.data(), key_cert_pair_count, client_certificate_request, NULL); if (creds == NULL) { info.GetReturnValue().SetNull(); } else { info.GetReturnValue().Set(WrapStruct(creds)); } } NAN_METHOD(ServerCredentials::CreateInsecure) { info.GetReturnValue().Set(WrapStruct(NULL)); } } // namespace node } // namespace grpc
Replace another variable length stack array with a vector
Replace another variable length stack array with a vector
C++
apache-2.0
grpc/grpc-node,grpc/grpc-node,grpc/grpc-node,grpc/grpc-node
fb49b3cc90d5db216e1840303165c0009745c78d
test/mining-manager/t_AutofillManager.cpp
test/mining-manager/t_AutofillManager.cpp
/// /// @file t_AutofillManager.cpp /// @brief test autofill works /// @author Hongliang Zhao <[email protected]> /// @date Created 2013-02-05 /// #include <mining-manager/auto-fill-submanager/AutoFillSubManager.h> #include <mining-manager/auto-fill-submanager/AutoFillChildManager.h> #include <boost/test/unit_test.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/path.hpp> #include <log-manager/UserQuery.h> #include <log-manager/LogAnalysis.h> using namespace sf1r; using namespace std; using namespace boost; namespace sf1r { void prepareQueryData_Update(std::vector<UserQuery> & QueryList) { std::vector<string> rawQueryList; rawQueryList.push_back("ipad 3"); rawQueryList.push_back("ipad 2"); rawQueryList.push_back("ipad 2 16g"); rawQueryList.push_back("iphone"); rawQueryList.push_back("iphone4s"); rawQueryList.push_back(" jia fang "); rawQueryList.push_back("jeep , "); rawQueryList.push_back(",iphone "); rawQueryList.push_back("jiafang|jianpan"); unsigned int queryCount = 0; for (std::vector<string>::iterator i = rawQueryList.begin(); i != rawQueryList.end(); ++i) { ++queryCount; UserQuery userQuery; userQuery.setHitDocsNum(queryCount); userQuery.setCount(queryCount); userQuery.setQuery(*i); QueryList.push_back(userQuery); } } void prepareQueryData(std::vector<UserQuery> & QueryList) { std::vector<string> rawQueryList; rawQueryList.push_back("iphone"); rawQueryList.push_back("iphone5"); rawQueryList.push_back("iphone4s"); rawQueryList.push_back("iphone4s8g"); rawQueryList.push_back("ipad"); rawQueryList.push_back("jiezhi"); rawQueryList.push_back("jiake"); rawQueryList.push_back("jiafa");; rawQueryList.push_back("jiumuwang"); rawQueryList.push_back("jianpan"); rawQueryList.push_back("jeep"); rawQueryList.push_back("jiafang1"); rawQueryList.push_back("jiafang|jianpan"); rawQueryList.push_back(" jia fang "); rawQueryList.push_back("jeep , "); rawQueryList.push_back(",iphone "); unsigned int queryCount = 0; for (std::vector<string>::iterator i = rawQueryList.begin(); i != rawQueryList.end(); ++i) { ++queryCount; UserQuery userQuery; userQuery.setHitDocsNum(queryCount); userQuery.setCount(queryCount); userQuery.setQuery(*i); QueryList.push_back(userQuery); } } void createAutoFillDic() { if (!boost::filesystem::is_directory("./querydata")) { boost::filesystem::create_directories("./querydata"); } if (!boost::filesystem::is_directory("./scd")) { boost::filesystem::create_directories("./scd"); } } void removeAutoFillDic() { if (boost::filesystem::is_directory("./querydata")) { boost::filesystem::remove_all("./querydata"); } if (boost::filesystem::is_directory("./scd")) { boost::filesystem::remove_all("./scd"); } } void clearAutoFillDic() { boost::filesystem::path path1("./querydata"); boost::filesystem::remove_all(path1); boost::filesystem::path path2("./scd"); boost::filesystem::remove_all(path2); } class AutoFillTestFixture { private: AutoFillChildManager* autofillManager_; public: AutoFillTestFixture() { autofillManager_ = new AutoFillChildManager(false); } ~AutoFillTestFixture() { if (autofillManager_ != NULL) { delete autofillManager_; autofillManager_ = NULL; } } void buildNewAutoFill() { stopAutofill(); autofillManager_ = new AutoFillChildManager(false); } void checkAutofillUpdateResult() { std::vector<std::pair<izenelib::util::UString, uint32_t> > ResultList; std::string topString; std::string bottomString; std::string prefix = "i"; izenelib::util::UString Uquery(prefix, izenelib::util::UString::UTF_8); ResultList.clear(); autofillManager_->getAutoFillList(Uquery, ResultList); BOOST_CHECK_EQUAL(ResultList.size(), 8U); cout<<"TEST 1"<<endl; izenelib::util::UString USTR; USTR = ResultList[0].first; USTR.convertString(topString, izenelib::util::UString::UTF_8); USTR = ResultList[ResultList.size() - 1].first; USTR.convertString(bottomString, izenelib::util::UString::UTF_8); BOOST_CHECK_EQUAL(topString, "iphone4s"); BOOST_CHECK_EQUAL(bottomString, "ipad 3"); prefix = "j"; ResultList.clear(); cout<<"TEST 2"<<endl; izenelib::util::UString Uquery1(prefix, izenelib::util::UString::UTF_8); autofillManager_->getAutoFillList(Uquery1, ResultList); BOOST_CHECK_EQUAL(ResultList.size(), 8U); USTR = ResultList[0].first; USTR.convertString(topString, izenelib::util::UString::UTF_8); USTR = ResultList[ResultList.size() - 1].first; USTR.convertString(bottomString, izenelib::util::UString::UTF_8); BOOST_CHECK_EQUAL(topString, "jia fang"); BOOST_CHECK_EQUAL(bottomString, "jiezhi"); prefix = "jia"; ResultList.clear(); cout<<"TEST 3"<<endl; izenelib::util::UString Uquery2(prefix, izenelib::util::UString::UTF_8); autofillManager_->getAutoFillList(Uquery2, ResultList); BOOST_CHECK_EQUAL(ResultList.size(), 5U); USTR = ResultList[0].first; USTR.convertString(topString, izenelib::util::UString::UTF_8); USTR = ResultList[ResultList.size() - 1].first; USTR.convertString(bottomString, izenelib::util::UString::UTF_8); BOOST_CHECK_EQUAL(topString, "jia fang"); BOOST_CHECK_EQUAL(bottomString, "jiake"); } void checkAutofillResult() { std::vector<std::pair<izenelib::util::UString, uint32_t> > ResultList; std::string topString; std::string bottomString; std::string prefix = "i"; izenelib::util::UString Uquery(prefix, izenelib::util::UString::UTF_8); ResultList.clear(); autofillManager_->getAutoFillList(Uquery, ResultList); BOOST_CHECK_EQUAL(ResultList.size(), 5U); cout<<"TEST 1"<<endl; izenelib::util::UString USTR; USTR = ResultList[0].first; USTR.convertString(topString, izenelib::util::UString::UTF_8); USTR = ResultList[ResultList.size() - 1].first; USTR.convertString(bottomString, izenelib::util::UString::UTF_8); BOOST_CHECK_EQUAL(topString, "ipad"); BOOST_CHECK_EQUAL(bottomString, "iphone"); prefix = "j"; ResultList.clear(); cout<<"TEST 2"<<endl; izenelib::util::UString Uquery1(prefix, izenelib::util::UString::UTF_8); autofillManager_->getAutoFillList(Uquery1, ResultList); BOOST_CHECK_EQUAL(ResultList.size(), 8U); USTR = ResultList[0].first; USTR.convertString(topString, izenelib::util::UString::UTF_8); USTR = ResultList[ResultList.size() - 1].first; USTR.convertString(bottomString, izenelib::util::UString::UTF_8); BOOST_CHECK_EQUAL(topString, "jia fang"); BOOST_CHECK_EQUAL(bottomString, "jiezhi"); prefix = "jia"; ResultList.clear(); cout<<"TEST 3"<<endl; izenelib::util::UString Uquery2(prefix, izenelib::util::UString::UTF_8); autofillManager_->getAutoFillList(Uquery2, ResultList); BOOST_CHECK_EQUAL(ResultList.size(), 5U); USTR = ResultList[0].first; USTR.convertString(topString, izenelib::util::UString::UTF_8); USTR = ResultList[ResultList.size() - 1].first; USTR.convertString(bottomString, izenelib::util::UString::UTF_8); BOOST_CHECK_EQUAL(topString, "jia fang"); BOOST_CHECK_EQUAL(bottomString, "jiake"); } void testInitAutoFill() { createAutoFillDic(); CollectionPath collectionPath_; collectionPath_.setBasePath("./"); collectionPath_.setQueryDataPath("/home/lscm/codebase/sf1r-engine/testbin//querydata"); collectionPath_.setScdPath("/scd"); std::string collection_name_ = "b5m_test"; std::string cronName_ = "30 2 * * *"; std::vector<UserQuery> QueryList; prepareQueryData(QueryList); std::string instance = "b5mp"; bool isFromLevelDB = false; BOOST_CHECK_EQUAL(autofillManager_->Init_ForTest(collectionPath_, collection_name_, cronName_, instance, isFromLevelDB, QueryList), true); cout << "Begin test init autofill..............................."<<endl; checkAutofillResult(); } void testStartAutoFillFromLevelDB(bool isupdate) { CollectionPath collectionPath_; collectionPath_.setBasePath("./"); collectionPath_.setQueryDataPath("/home/lscm/codebase/sf1r-engine/testbin//querydata"); collectionPath_.setScdPath("/scd"); std::string collection_name_ = "b5m_test"; std::string cronName_ = "30 2 * * *"; std::vector<UserQuery> QueryList; prepareQueryData(QueryList); std::string instance = "b5mp"; bool isFromLevelDB = true; BOOST_CHECK_EQUAL(autofillManager_->Init_ForTest(collectionPath_, collection_name_, cronName_, instance, isFromLevelDB, QueryList), true); cout << "Begin testStartAutoFillFromLevelDB ...................."<<endl; if (!isupdate) { checkAutofillResult(); } else checkAutofillUpdateResult(); } void testUpdateAutofill() { std::vector<UserQuery> QueryList; prepareQueryData_Update(QueryList); autofillManager_->updateFromLog_ForTest(QueryList); cout << "Begin update AutoFill ................................."<<endl; checkAutofillUpdateResult(); } void stopAutofill() { if (autofillManager_ != NULL) { delete autofillManager_; autofillManager_ = NULL; } } }; BOOST_AUTO_TEST_SUITE(AutoFill) BOOST_FIXTURE_TEST_CASE(checkAutofill, AutoFillTestFixture) { clearAutoFillDic(); bool isupdate = false; BOOST_TEST_MESSAGE("[Test init AutoFill]"); testInitAutoFill(); stopAutofill(); BOOST_TEST_MESSAGE("[Test restart AutoFill]"); buildNewAutoFill(); testStartAutoFillFromLevelDB(isupdate); BOOST_TEST_MESSAGE("[Test update AutoFill]"); testUpdateAutofill(); stopAutofill(); isupdate = true; BOOST_TEST_MESSAGE("[Test update AutoFill]"); buildNewAutoFill(); testStartAutoFillFromLevelDB(isupdate); stopAutofill(); clearAutoFillDic(); } BOOST_AUTO_TEST_SUITE_END() }
/// /// @file t_AutofillManager.cpp /// @brief test autofill works /// @author Hongliang Zhao <[email protected]> /// @date Created 2013-02-05 /// #include <mining-manager/auto-fill-submanager/AutoFillSubManager.h> #include <mining-manager/auto-fill-submanager/AutoFillChildManager.h> #include <boost/test/unit_test.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/path.hpp> #include <log-manager/UserQuery.h> #include <log-manager/LogAnalysis.h> using namespace sf1r; using namespace std; using namespace boost; namespace sf1r { void prepareQueryData_Update(std::vector<UserQuery> & QueryList) { std::vector<string> rawQueryList; rawQueryList.push_back("ipad 3"); rawQueryList.push_back("ipad 2"); rawQueryList.push_back("ipad 2 16g"); rawQueryList.push_back("iphone"); rawQueryList.push_back("iphone4s"); rawQueryList.push_back(" jia fang "); rawQueryList.push_back("jeep , "); rawQueryList.push_back(",iphone "); rawQueryList.push_back("jiafang|jianpan"); unsigned int queryCount = 0; for (std::vector<string>::iterator i = rawQueryList.begin(); i != rawQueryList.end(); ++i) { ++queryCount; UserQuery userQuery; userQuery.setHitDocsNum(queryCount); userQuery.setCount(queryCount); userQuery.setQuery(*i); QueryList.push_back(userQuery); } } void prepareQueryData(std::vector<UserQuery> & QueryList) { std::vector<string> rawQueryList; rawQueryList.push_back("iphone"); rawQueryList.push_back("iphone5"); rawQueryList.push_back("iphone4s"); rawQueryList.push_back("iphone4s8g"); rawQueryList.push_back("ipad"); rawQueryList.push_back("jiezhi"); rawQueryList.push_back("jiake"); rawQueryList.push_back("jiafa");; rawQueryList.push_back("jiumuwang"); rawQueryList.push_back("jianpan"); rawQueryList.push_back("jeep"); rawQueryList.push_back("jiafang1"); rawQueryList.push_back("jiafang|jianpan"); rawQueryList.push_back(" jia fang "); rawQueryList.push_back("jeep , "); rawQueryList.push_back(",iphone "); unsigned int queryCount = 0; for (std::vector<string>::iterator i = rawQueryList.begin(); i != rawQueryList.end(); ++i) { ++queryCount; UserQuery userQuery; userQuery.setHitDocsNum(queryCount); userQuery.setCount(queryCount); userQuery.setQuery(*i); QueryList.push_back(userQuery); } } void createAutoFillDic() { if (!boost::filesystem::is_directory("./querydata")) { boost::filesystem::create_directories("./querydata"); } if (!boost::filesystem::is_directory("./scd")) { boost::filesystem::create_directories("./scd"); } } void removeAutoFillDic() { if (boost::filesystem::is_directory("./querydata")) { boost::filesystem::remove_all("./querydata"); } if (boost::filesystem::is_directory("./scd")) { boost::filesystem::remove_all("./scd"); } } void clearAutoFillDic() { boost::filesystem::path path1("./querydata"); boost::filesystem::remove_all(path1); boost::filesystem::path path2("./scd"); boost::filesystem::remove_all(path2); } class AutoFillTestFixture { private: AutoFillChildManager* autofillManager_; public: AutoFillTestFixture() { autofillManager_ = new AutoFillChildManager(false); } ~AutoFillTestFixture() { if (autofillManager_ != NULL) { delete autofillManager_; autofillManager_ = NULL; } } void buildNewAutoFill() { stopAutofill(); autofillManager_ = new AutoFillChildManager(false); } void checkAutofillUpdateResult() { std::vector<std::pair<izenelib::util::UString, uint32_t> > ResultList; std::string topString; std::string bottomString; std::string prefix = "i"; izenelib::util::UString Uquery(prefix, izenelib::util::UString::UTF_8); ResultList.clear(); autofillManager_->getAutoFillList(Uquery, ResultList); BOOST_CHECK_EQUAL(ResultList.size(), 8U); cout<<"TEST 1"<<endl; izenelib::util::UString USTR; USTR = ResultList[0].first; USTR.convertString(topString, izenelib::util::UString::UTF_8); USTR = ResultList[ResultList.size() - 1].first; USTR.convertString(bottomString, izenelib::util::UString::UTF_8); BOOST_CHECK_EQUAL(topString, "iphone4s"); BOOST_CHECK_EQUAL(bottomString, "ipad 3"); prefix = "j"; ResultList.clear(); cout<<"TEST 2"<<endl; izenelib::util::UString Uquery1(prefix, izenelib::util::UString::UTF_8); autofillManager_->getAutoFillList(Uquery1, ResultList); BOOST_CHECK_EQUAL(ResultList.size(), 8U); USTR = ResultList[0].first; USTR.convertString(topString, izenelib::util::UString::UTF_8); USTR = ResultList[ResultList.size() - 1].first; USTR.convertString(bottomString, izenelib::util::UString::UTF_8); BOOST_CHECK_EQUAL(topString, "jia fang"); BOOST_CHECK_EQUAL(bottomString, "jiezhi"); prefix = "jia"; ResultList.clear(); cout<<"TEST 3"<<endl; izenelib::util::UString Uquery2(prefix, izenelib::util::UString::UTF_8); autofillManager_->getAutoFillList(Uquery2, ResultList); BOOST_CHECK_EQUAL(ResultList.size(), 5U); USTR = ResultList[0].first; USTR.convertString(topString, izenelib::util::UString::UTF_8); USTR = ResultList[ResultList.size() - 1].first; USTR.convertString(bottomString, izenelib::util::UString::UTF_8); BOOST_CHECK_EQUAL(topString, "jia fang"); BOOST_CHECK_EQUAL(bottomString, "jiake"); } void checkAutofillResult() { std::vector<std::pair<izenelib::util::UString, uint32_t> > ResultList; std::string topString; std::string bottomString; std::string prefix = "i"; izenelib::util::UString Uquery(prefix, izenelib::util::UString::UTF_8); ResultList.clear(); autofillManager_->getAutoFillList(Uquery, ResultList); BOOST_CHECK_EQUAL(ResultList.size(), 5U); cout<<"TEST 1"<<endl; izenelib::util::UString USTR; USTR = ResultList[0].first; USTR.convertString(topString, izenelib::util::UString::UTF_8); USTR = ResultList[ResultList.size() - 1].first; USTR.convertString(bottomString, izenelib::util::UString::UTF_8); BOOST_CHECK_EQUAL(topString, "ipad"); BOOST_CHECK_EQUAL(bottomString, "iphone"); prefix = "j"; ResultList.clear(); cout<<"TEST 2"<<endl; izenelib::util::UString Uquery1(prefix, izenelib::util::UString::UTF_8); autofillManager_->getAutoFillList(Uquery1, ResultList); BOOST_CHECK_EQUAL(ResultList.size(), 8U); USTR = ResultList[0].first; USTR.convertString(topString, izenelib::util::UString::UTF_8); USTR = ResultList[ResultList.size() - 1].first; USTR.convertString(bottomString, izenelib::util::UString::UTF_8); BOOST_CHECK_EQUAL(topString, "jia fang"); BOOST_CHECK_EQUAL(bottomString, "jiezhi"); prefix = "jia"; ResultList.clear(); cout<<"TEST 3"<<endl; izenelib::util::UString Uquery2(prefix, izenelib::util::UString::UTF_8); autofillManager_->getAutoFillList(Uquery2, ResultList); BOOST_CHECK_EQUAL(ResultList.size(), 5U); USTR = ResultList[0].first; USTR.convertString(topString, izenelib::util::UString::UTF_8); USTR = ResultList[ResultList.size() - 1].first; USTR.convertString(bottomString, izenelib::util::UString::UTF_8); BOOST_CHECK_EQUAL(topString, "jia fang"); BOOST_CHECK_EQUAL(bottomString, "jiake"); } void testInitAutoFill() { createAutoFillDic(); CollectionPath collectionPath_; collectionPath_.setBasePath("./"); collectionPath_.setQueryDataPath("./querydata"); collectionPath_.setScdPath("/scd"); std::string collection_name_ = "b5m_test"; std::string cronName_ = "30 2 * * *"; std::vector<UserQuery> QueryList; prepareQueryData(QueryList); std::string instance = "b5mp"; bool isFromLevelDB = false; BOOST_CHECK_EQUAL(autofillManager_->Init_ForTest(collectionPath_, collection_name_, cronName_, instance, isFromLevelDB, QueryList), true); cout << "Begin test init autofill..............................."<<endl; checkAutofillResult(); } void testStartAutoFillFromLevelDB(bool isupdate) { CollectionPath collectionPath_; collectionPath_.setBasePath("./"); collectionPath_.setQueryDataPath("./querydata"); collectionPath_.setScdPath("/scd"); std::string collection_name_ = "b5m_test"; std::string cronName_ = "30 2 * * *"; std::vector<UserQuery> QueryList; prepareQueryData(QueryList); std::string instance = "b5mp"; bool isFromLevelDB = true; BOOST_CHECK_EQUAL(autofillManager_->Init_ForTest(collectionPath_, collection_name_, cronName_, instance, isFromLevelDB, QueryList), true); cout << "Begin testStartAutoFillFromLevelDB ...................."<<endl; if (!isupdate) { checkAutofillResult(); } else checkAutofillUpdateResult(); } void testUpdateAutofill() { std::vector<UserQuery> QueryList; prepareQueryData_Update(QueryList); autofillManager_->updateFromLog_ForTest(QueryList); cout << "Begin update AutoFill ................................."<<endl; checkAutofillUpdateResult(); } void stopAutofill() { if (autofillManager_ != NULL) { delete autofillManager_; autofillManager_ = NULL; } } }; BOOST_AUTO_TEST_SUITE(AutoFill) BOOST_FIXTURE_TEST_CASE(checkAutofill, AutoFillTestFixture) { clearAutoFillDic(); bool isupdate = false; BOOST_TEST_MESSAGE("[Test init AutoFill]"); testInitAutoFill(); stopAutofill(); BOOST_TEST_MESSAGE("[Test restart AutoFill]"); buildNewAutoFill(); testStartAutoFillFromLevelDB(isupdate); BOOST_TEST_MESSAGE("[Test update AutoFill]"); testUpdateAutofill(); stopAutofill(); isupdate = true; BOOST_TEST_MESSAGE("[Test update AutoFill]"); buildNewAutoFill(); testStartAutoFillFromLevelDB(isupdate); stopAutofill(); clearAutoFillDic(); } BOOST_AUTO_TEST_SUITE_END() }
fix unit test
fix unit test
C++
apache-2.0
izenecloud/sf1r-lite,pombredanne/sf1r-lite,izenecloud/sf1r-lite,pombredanne/sf1r-lite,pombredanne/sf1r-lite,izenecloud/sf1r-lite,izenecloud/sf1r-lite,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-ad-delivery,pombredanne/sf1r-lite,izenecloud/sf1r-lite,izenecloud/sf1r-ad-delivery,pombredanne/sf1r-lite,izenecloud/sf1r-ad-delivery
7001193f0291d28a015d5407d7b4644a2a81b0e5
src/arch/alpha/tlb.hh
src/arch/alpha/tlb.hh
/* * 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: Nathan Binkert * Steve Reinhardt */ #ifndef __ALPHA_MEMORY_HH__ #define __ALPHA_MEMORY_HH__ #include <map> #include "arch/alpha/ev5.hh" #include "arch/alpha/isa_traits.hh" #include "arch/alpha/pagetable.hh" #include "arch/alpha/utility.hh" #include "arch/alpha/vtophys.hh" #include "base/statistics.hh" #include "mem/request.hh" #include "sim/faults.hh" #include "sim/sim_object.hh" class ThreadContext; namespace AlphaISA { class PTE; class TLB : public SimObject { protected: typedef std::multimap<Addr, int> PageTable; PageTable lookupTable; // Quick lookup into page table PTE *table; // the Page Table int size; // TLB Size int nlu; // not last used entry (for replacement) void nextnlu() { if (++nlu >= size) nlu = 0; } PTE *lookup(Addr vpn, uint8_t asn) const; public: TLB(const std::string &name, int size); virtual ~TLB(); int getsize() const { return size; } PTE &index(bool advance = true); void insert(Addr vaddr, PTE &pte); void flushAll(); void flushProcesses(); void flushAddr(Addr addr, uint8_t asn); // static helper functions... really EV5 VM traits static bool validVirtualAddress(Addr vaddr) { // unimplemented bits must be all 0 or all 1 Addr unimplBits = vaddr & EV5::VAddrUnImplMask; return (unimplBits == 0) || (unimplBits == EV5::VAddrUnImplMask); } static Fault checkCacheability(RequestPtr &req); // Checkpointing virtual void serialize(std::ostream &os); virtual void unserialize(Checkpoint *cp, const std::string &section); // Most recently used page table entries PTE *PTECache[2]; inline void flushCache() { memset(PTECache, 0, 2 * sizeof(PTE*)); } }; class ITB : public TLB { protected: mutable Stats::Scalar<> hits; mutable Stats::Scalar<> misses; mutable Stats::Scalar<> acv; mutable Stats::Formula accesses; public: ITB(const std::string &name, int size); virtual void regStats(); Fault translate(RequestPtr &req, ThreadContext *tc) const; }; class DTB : public TLB { protected: mutable Stats::Scalar<> read_hits; mutable Stats::Scalar<> read_misses; mutable Stats::Scalar<> read_acv; mutable Stats::Scalar<> read_accesses; mutable Stats::Scalar<> write_hits; mutable Stats::Scalar<> write_misses; mutable Stats::Scalar<> write_acv; mutable Stats::Scalar<> write_accesses; Stats::Formula hits; Stats::Formula misses; Stats::Formula acv; Stats::Formula accesses; public: DTB(const std::string &name, int size); virtual void regStats(); Fault translate(RequestPtr &req, ThreadContext *tc, bool write) const; }; } #endif // __ALPHA_MEMORY_HH__
/* * 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: Nathan Binkert * Steve Reinhardt */ #ifndef __ALPHA_MEMORY_HH__ #define __ALPHA_MEMORY_HH__ #include <map> #include "arch/alpha/ev5.hh" #include "arch/alpha/isa_traits.hh" #include "arch/alpha/pagetable.hh" #include "arch/alpha/utility.hh" #include "arch/alpha/vtophys.hh" #include "base/statistics.hh" #include "mem/request.hh" #include "sim/faults.hh" #include "sim/sim_object.hh" class ThreadContext; namespace AlphaISA { class PTE; class TLB : public SimObject { protected: typedef std::multimap<Addr, int> PageTable; PageTable lookupTable; // Quick lookup into page table PTE *table; // the Page Table int size; // TLB Size int nlu; // not last used entry (for replacement) void nextnlu() { if (++nlu >= size) nlu = 0; } PTE *lookup(Addr vpn, uint8_t asn) const; public: TLB(const std::string &name, int size); virtual ~TLB(); int getsize() const { return size; } PTE &index(bool advance = true); void insert(Addr vaddr, PTE &pte); void flushAll(); void flushProcesses(); void flushAddr(Addr addr, uint8_t asn); // static helper functions... really EV5 VM traits static bool validVirtualAddress(Addr vaddr) { // unimplemented bits must be all 0 or all 1 Addr unimplBits = vaddr & EV5::VAddrUnImplMask; return (unimplBits == 0) || (unimplBits == EV5::VAddrUnImplMask); } static Fault checkCacheability(RequestPtr &req); // Checkpointing virtual void serialize(std::ostream &os); virtual void unserialize(Checkpoint *cp, const std::string &section); // Most recently used page table entries PTE *PTECache[3]; inline void flushCache() { memset(PTECache, 0, 3 * sizeof(PTE*)); } }; class ITB : public TLB { protected: mutable Stats::Scalar<> hits; mutable Stats::Scalar<> misses; mutable Stats::Scalar<> acv; mutable Stats::Formula accesses; public: ITB(const std::string &name, int size); virtual void regStats(); Fault translate(RequestPtr &req, ThreadContext *tc) const; }; class DTB : public TLB { protected: mutable Stats::Scalar<> read_hits; mutable Stats::Scalar<> read_misses; mutable Stats::Scalar<> read_acv; mutable Stats::Scalar<> read_accesses; mutable Stats::Scalar<> write_hits; mutable Stats::Scalar<> write_misses; mutable Stats::Scalar<> write_acv; mutable Stats::Scalar<> write_accesses; Stats::Formula hits; Stats::Formula misses; Stats::Formula acv; Stats::Formula accesses; public: DTB(const std::string &name, int size); virtual void regStats(); Fault translate(RequestPtr &req, ThreadContext *tc, bool write) const; }; } #endif // __ALPHA_MEMORY_HH__
Fix an off by one error with the tlb caching mechanism.
Alpha: Fix an off by one error with the tlb caching mechanism.
C++
bsd-3-clause
andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin